three.cjs 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '180dev';
  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 depth value, converts it to floating point, and clamps to the range `[0,1]`.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const DepthFormat = 1026;
  670. /**
  671. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  672. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  673. *
  674. * @type {number}
  675. * @constant
  676. */
  677. const DepthStencilFormat = 1027;
  678. /**
  679. * Discards the green, blue and alpha components and reads just the red component.
  680. *
  681. * @type {number}
  682. * @constant
  683. */
  684. const RedFormat = 1028;
  685. /**
  686. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const RedIntegerFormat = 1029;
  692. /**
  693. * Discards the alpha, and blue components and reads the red, and green components.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RGFormat = 1030;
  699. /**
  700. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RGIntegerFormat = 1031;
  706. /**
  707. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGBIntegerFormat = 1032;
  713. /**
  714. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGBAIntegerFormat = 1033;
  720. /**
  721. * A DXT1-compressed image in an RGB image format.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGB_S3TC_DXT1_Format = 33776;
  727. /**
  728. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGBA_S3TC_DXT1_Format = 33777;
  734. /**
  735. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGBA_S3TC_DXT3_Format = 33778;
  741. /**
  742. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  743. * compression in how the alpha compression is done.
  744. *
  745. * @type {number}
  746. * @constant
  747. */
  748. const RGBA_S3TC_DXT5_Format = 33779;
  749. /**
  750. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  751. *
  752. * @type {number}
  753. * @constant
  754. */
  755. const RGB_PVRTC_4BPPV1_Format = 35840;
  756. /**
  757. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGB_PVRTC_2BPPV1_Format = 35841;
  763. /**
  764. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGBA_PVRTC_4BPPV1_Format = 35842;
  770. /**
  771. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGBA_PVRTC_2BPPV1_Format = 35843;
  777. /**
  778. * ETC1 RGB format.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGB_ETC1_Format = 36196;
  784. /**
  785. * ETC2 RGB format.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGB_ETC2_Format = 37492;
  791. /**
  792. * ETC2 RGBA format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGBA_ETC2_EAC_Format = 37496;
  798. /**
  799. * ASTC RGBA 4x4 format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGBA_ASTC_4x4_Format = 37808;
  805. /**
  806. * ASTC RGBA 5x4 format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const RGBA_ASTC_5x4_Format = 37809;
  812. /**
  813. * ASTC RGBA 5x5 format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const RGBA_ASTC_5x5_Format = 37810;
  819. /**
  820. * ASTC RGBA 6x5 format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const RGBA_ASTC_6x5_Format = 37811;
  826. /**
  827. * ASTC RGBA 6x6 format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const RGBA_ASTC_6x6_Format = 37812;
  833. /**
  834. * ASTC RGBA 8x5 format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const RGBA_ASTC_8x5_Format = 37813;
  840. /**
  841. * ASTC RGBA 8x6 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_8x6_Format = 37814;
  847. /**
  848. * ASTC RGBA 8x8 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_8x8_Format = 37815;
  854. /**
  855. * ASTC RGBA 10x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_10x5_Format = 37816;
  861. /**
  862. * ASTC RGBA 10x6 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_10x6_Format = 37817;
  868. /**
  869. * ASTC RGBA 10x8 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_10x8_Format = 37818;
  875. /**
  876. * ASTC RGBA 10x10 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_10x10_Format = 37819;
  882. /**
  883. * ASTC RGBA 12x10 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_12x10_Format = 37820;
  889. /**
  890. * ASTC RGBA 12x12 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_12x12_Format = 37821;
  896. /**
  897. * BPTC RGBA format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_BPTC_Format = 36492;
  903. /**
  904. * BPTC Signed RGB format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGB_BPTC_SIGNED_Format = 36494;
  910. /**
  911. * BPTC Unsigned RGB format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGB_BPTC_UNSIGNED_Format = 36495;
  917. /**
  918. * RGTC1 Red format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RED_RGTC1_Format = 36283;
  924. /**
  925. * RGTC1 Signed Red format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const SIGNED_RED_RGTC1_Format = 36284;
  931. /**
  932. * RGTC2 Red Green format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RED_GREEN_RGTC2_Format = 36285;
  938. /**
  939. * RGTC2 Signed Red Green format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  945. /**
  946. * Animations are played once.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const LoopOnce = 2200;
  952. /**
  953. * Animations are played with a chosen number of repetitions, each time jumping from
  954. * the end of the clip directly to its beginning.
  955. *
  956. * @type {number}
  957. * @constant
  958. */
  959. const LoopRepeat = 2201;
  960. /**
  961. * Animations are played with a chosen number of repetitions, alternately playing forward
  962. * and backward.
  963. *
  964. * @type {number}
  965. * @constant
  966. */
  967. const LoopPingPong = 2202;
  968. /**
  969. * Discrete interpolation mode for keyframe tracks.
  970. *
  971. * @type {number}
  972. * @constant
  973. */
  974. const InterpolateDiscrete = 2300;
  975. /**
  976. * Linear interpolation mode for keyframe tracks.
  977. *
  978. * @type {number}
  979. * @constant
  980. */
  981. const InterpolateLinear = 2301;
  982. /**
  983. * Smooth interpolation mode for keyframe tracks.
  984. *
  985. * @type {number}
  986. * @constant
  987. */
  988. const InterpolateSmooth = 2302;
  989. /**
  990. * Zero curvature ending for animations.
  991. *
  992. * @type {number}
  993. * @constant
  994. */
  995. const ZeroCurvatureEnding = 2400;
  996. /**
  997. * Zero slope ending for animations.
  998. *
  999. * @type {number}
  1000. * @constant
  1001. */
  1002. const ZeroSlopeEnding = 2401;
  1003. /**
  1004. * Wrap around ending for animations.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const WrapAroundEnding = 2402;
  1010. /**
  1011. * Default animation blend mode.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const NormalAnimationBlendMode = 2500;
  1017. /**
  1018. * Additive animation blend mode. Can be used to layer motions on top of
  1019. * each other to build complex performances from smaller re-usable assets.
  1020. *
  1021. * @type {number}
  1022. * @constant
  1023. */
  1024. const AdditiveAnimationBlendMode = 2501;
  1025. /**
  1026. * For every three vertices draw a single triangle.
  1027. *
  1028. * @type {number}
  1029. * @constant
  1030. */
  1031. const TrianglesDrawMode = 0;
  1032. /**
  1033. * For each vertex draw a triangle from the last three vertices.
  1034. *
  1035. * @type {number}
  1036. * @constant
  1037. */
  1038. const TriangleStripDrawMode = 1;
  1039. /**
  1040. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1041. *
  1042. * @type {number}
  1043. * @constant
  1044. */
  1045. const TriangleFanDrawMode = 2;
  1046. /**
  1047. * Basic depth packing.
  1048. *
  1049. * @type {number}
  1050. * @constant
  1051. */
  1052. const BasicDepthPacking = 3200;
  1053. /**
  1054. * A depth value is packed into 32 bit RGBA.
  1055. *
  1056. * @type {number}
  1057. * @constant
  1058. */
  1059. const RGBADepthPacking = 3201;
  1060. /**
  1061. * A depth value is packed into 24 bit RGB.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const RGBDepthPacking = 3202;
  1067. /**
  1068. * A depth value is packed into 16 bit RG.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const RGDepthPacking = 3203;
  1074. /**
  1075. * Normal information is relative to the underlying surface.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const TangentSpaceNormalMap = 0;
  1081. /**
  1082. * Normal information is relative to the object orientation.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const ObjectSpaceNormalMap = 1;
  1088. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1089. /**
  1090. * No color space.
  1091. *
  1092. * @type {string}
  1093. * @constant
  1094. */
  1095. const NoColorSpace = '';
  1096. /**
  1097. * sRGB color space.
  1098. *
  1099. * @type {string}
  1100. * @constant
  1101. */
  1102. const SRGBColorSpace = 'srgb';
  1103. /**
  1104. * sRGB-linear color space.
  1105. *
  1106. * @type {string}
  1107. * @constant
  1108. */
  1109. const LinearSRGBColorSpace = 'srgb-linear';
  1110. /**
  1111. * Linear transfer function.
  1112. *
  1113. * @type {string}
  1114. * @constant
  1115. */
  1116. const LinearTransfer = 'linear';
  1117. /**
  1118. * sRGB transfer function.
  1119. *
  1120. * @type {string}
  1121. * @constant
  1122. */
  1123. const SRGBTransfer = 'srgb';
  1124. /**
  1125. * Sets the stencil buffer value to `0`.
  1126. *
  1127. * @type {number}
  1128. * @constant
  1129. */
  1130. const ZeroStencilOp = 0;
  1131. /**
  1132. * Keeps the current value.
  1133. *
  1134. * @type {number}
  1135. * @constant
  1136. */
  1137. const KeepStencilOp = 7680;
  1138. /**
  1139. * Sets the stencil buffer value to the specified reference value.
  1140. *
  1141. * @type {number}
  1142. * @constant
  1143. */
  1144. const ReplaceStencilOp = 7681;
  1145. /**
  1146. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1147. *
  1148. * @type {number}
  1149. * @constant
  1150. */
  1151. const IncrementStencilOp = 7682;
  1152. /**
  1153. * Decrements the current stencil buffer value. Clamps to `0`.
  1154. *
  1155. * @type {number}
  1156. * @constant
  1157. */
  1158. const DecrementStencilOp = 7683;
  1159. /**
  1160. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1161. * the maximum representable unsigned value.
  1162. *
  1163. * @type {number}
  1164. * @constant
  1165. */
  1166. const IncrementWrapStencilOp = 34055;
  1167. /**
  1168. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1169. * unsigned value when decrementing a stencil buffer value of `0`.
  1170. *
  1171. * @type {number}
  1172. * @constant
  1173. */
  1174. const DecrementWrapStencilOp = 34056;
  1175. /**
  1176. * Inverts the current stencil buffer value bitwise.
  1177. *
  1178. * @type {number}
  1179. * @constant
  1180. */
  1181. const InvertStencilOp = 5386;
  1182. /**
  1183. * Will never return true.
  1184. *
  1185. * @type {number}
  1186. * @constant
  1187. */
  1188. const NeverStencilFunc = 512;
  1189. /**
  1190. * Will return true if the stencil reference value is less than the current stencil value.
  1191. *
  1192. * @type {number}
  1193. * @constant
  1194. */
  1195. const LessStencilFunc = 513;
  1196. /**
  1197. * Will return true if the stencil reference value is equal to the current stencil value.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const EqualStencilFunc = 514;
  1203. /**
  1204. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const LessEqualStencilFunc = 515;
  1210. /**
  1211. * Will return true if the stencil reference value is greater than the current stencil value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const GreaterStencilFunc = 516;
  1217. /**
  1218. * Will return true if the stencil reference value is not equal to the current stencil value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const NotEqualStencilFunc = 517;
  1224. /**
  1225. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const GreaterEqualStencilFunc = 518;
  1231. /**
  1232. * Will always return true.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const AlwaysStencilFunc = 519;
  1238. /**
  1239. * Never pass.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const NeverCompare = 512;
  1245. /**
  1246. * Pass if the incoming value is less than the texture value.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const LessCompare = 513;
  1252. /**
  1253. * Pass if the incoming value equals the texture value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const EqualCompare = 514;
  1259. /**
  1260. * Pass if the incoming value is less than or equal to the texture value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const LessEqualCompare = 515;
  1266. /**
  1267. * Pass if the incoming value is greater than the texture value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const GreaterCompare = 516;
  1273. /**
  1274. * Pass if the incoming value is not equal to the texture value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const NotEqualCompare = 517;
  1280. /**
  1281. * Pass if the incoming value is greater than or equal to the texture value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const GreaterEqualCompare = 518;
  1287. /**
  1288. * Always pass.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const AlwaysCompare = 519;
  1294. /**
  1295. * The contents are intended to be specified once by the application, and used many
  1296. * times as the source for drawing and image specification commands.
  1297. *
  1298. * @type {number}
  1299. * @constant
  1300. */
  1301. const StaticDrawUsage = 35044;
  1302. /**
  1303. * The contents are intended to be respecified repeatedly by the application, and
  1304. * used many times as the source for drawing and image specification commands.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const DynamicDrawUsage = 35048;
  1310. /**
  1311. * The contents are intended to be specified once by the application, and used at most
  1312. * a few times as the source for drawing and image specification commands.
  1313. *
  1314. * @type {number}
  1315. * @constant
  1316. */
  1317. const StreamDrawUsage = 35040;
  1318. /**
  1319. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1320. * many times by the application.
  1321. *
  1322. * @type {number}
  1323. * @constant
  1324. */
  1325. const StaticReadUsage = 35045;
  1326. /**
  1327. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1328. * many times by the application.
  1329. *
  1330. * @type {number}
  1331. * @constant
  1332. */
  1333. const DynamicReadUsage = 35049;
  1334. /**
  1335. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1336. * a few times by the application
  1337. *
  1338. * @type {number}
  1339. * @constant
  1340. */
  1341. const StreamReadUsage = 35041;
  1342. /**
  1343. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1344. * the source for WebGL drawing and image specification commands.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const StaticCopyUsage = 35046;
  1350. /**
  1351. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1352. * as the source for WebGL drawing and image specification commands.
  1353. *
  1354. * @type {number}
  1355. * @constant
  1356. */
  1357. const DynamicCopyUsage = 35050;
  1358. /**
  1359. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1360. * as the source for WebGL drawing and image specification commands.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const StreamCopyUsage = 35042;
  1366. /**
  1367. * GLSL 1 shader code.
  1368. *
  1369. * @type {string}
  1370. * @constant
  1371. */
  1372. const GLSL1 = '100';
  1373. /**
  1374. * GLSL 3 shader code.
  1375. *
  1376. * @type {string}
  1377. * @constant
  1378. */
  1379. const GLSL3 = '300 es';
  1380. /**
  1381. * WebGL coordinate system.
  1382. *
  1383. * @type {number}
  1384. * @constant
  1385. */
  1386. const WebGLCoordinateSystem = 2000;
  1387. /**
  1388. * WebGPU coordinate system.
  1389. *
  1390. * @type {number}
  1391. * @constant
  1392. */
  1393. const WebGPUCoordinateSystem = 2001;
  1394. /**
  1395. * Represents the different timestamp query types.
  1396. *
  1397. * @type {ConstantsTimestampQuery}
  1398. * @constant
  1399. */
  1400. const TimestampQuery = {
  1401. COMPUTE: 'compute',
  1402. RENDER: 'render'
  1403. };
  1404. /**
  1405. * Represents mouse buttons and interaction types in context of controls.
  1406. *
  1407. * @type {ConstantsInterpolationSamplingType}
  1408. * @constant
  1409. */
  1410. const InterpolationSamplingType = {
  1411. PERSPECTIVE: 'perspective',
  1412. LINEAR: 'linear',
  1413. FLAT: 'flat'
  1414. };
  1415. /**
  1416. * Represents the different interpolation sampling modes.
  1417. *
  1418. * @type {ConstantsInterpolationSamplingMode}
  1419. * @constant
  1420. */
  1421. const InterpolationSamplingMode = {
  1422. NORMAL: 'normal',
  1423. CENTROID: 'centroid',
  1424. SAMPLE: 'sample',
  1425. FIRST: 'first',
  1426. EITHER: 'either'
  1427. };
  1428. /**
  1429. * This type represents mouse buttons and interaction types in context of controls.
  1430. *
  1431. * @typedef {Object} ConstantsMouse
  1432. * @property {number} MIDDLE - The left mouse button.
  1433. * @property {number} LEFT - The middle mouse button.
  1434. * @property {number} RIGHT - The right mouse button.
  1435. * @property {number} ROTATE - A rotate interaction.
  1436. * @property {number} DOLLY - A dolly interaction.
  1437. * @property {number} PAN - A pan interaction.
  1438. **/
  1439. /**
  1440. * This type represents touch interaction types in context of controls.
  1441. *
  1442. * @typedef {Object} ConstantsTouch
  1443. * @property {number} ROTATE - A rotate interaction.
  1444. * @property {number} PAN - A pan interaction.
  1445. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1446. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1447. **/
  1448. /**
  1449. * This type represents the different timestamp query types.
  1450. *
  1451. * @typedef {Object} ConstantsTimestampQuery
  1452. * @property {string} COMPUTE - A `compute` timestamp query.
  1453. * @property {string} RENDER - A `render` timestamp query.
  1454. **/
  1455. /**
  1456. * Represents the different interpolation sampling types.
  1457. *
  1458. * @typedef {Object} ConstantsInterpolationSamplingType
  1459. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1460. * @property {string} LINEAR - Linear interpolation.
  1461. * @property {string} FLAT - Flat interpolation.
  1462. */
  1463. /**
  1464. * Represents the different interpolation sampling modes.
  1465. *
  1466. * @typedef {Object} ConstantsInterpolationSamplingMode
  1467. * @property {string} NORMAL - Normal sampling mode.
  1468. * @property {string} CENTROID - Centroid sampling mode.
  1469. * @property {string} SAMPLE - Sample-specific sampling mode.
  1470. * @property {string} FLAT_FIRST - Flat interpolation using the first vertex.
  1471. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1472. */
  1473. /**
  1474. * This modules allows to dispatch event objects on custom JavaScript objects.
  1475. *
  1476. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1477. *
  1478. * Code Example:
  1479. * ```js
  1480. * class Car extends EventDispatcher {
  1481. * start() {
  1482. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1483. * }
  1484. *};
  1485. *
  1486. * // Using events with the custom object
  1487. * const car = new Car();
  1488. * car.addEventListener( 'start', function ( event ) {
  1489. * alert( event.message );
  1490. * } );
  1491. *
  1492. * car.start();
  1493. * ```
  1494. */
  1495. class EventDispatcher {
  1496. /**
  1497. * Adds the given event listener to the given event type.
  1498. *
  1499. * @param {string} type - The type of event to listen to.
  1500. * @param {Function} listener - The function that gets called when the event is fired.
  1501. */
  1502. addEventListener( type, listener ) {
  1503. if ( this._listeners === undefined ) this._listeners = {};
  1504. const listeners = this._listeners;
  1505. if ( listeners[ type ] === undefined ) {
  1506. listeners[ type ] = [];
  1507. }
  1508. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1509. listeners[ type ].push( listener );
  1510. }
  1511. }
  1512. /**
  1513. * Returns `true` if the given event listener has been added to the given event type.
  1514. *
  1515. * @param {string} type - The type of event.
  1516. * @param {Function} listener - The listener to check.
  1517. * @return {boolean} Whether the given event listener has been added to the given event type.
  1518. */
  1519. hasEventListener( type, listener ) {
  1520. const listeners = this._listeners;
  1521. if ( listeners === undefined ) return false;
  1522. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1523. }
  1524. /**
  1525. * Removes the given event listener from the given event type.
  1526. *
  1527. * @param {string} type - The type of event.
  1528. * @param {Function} listener - The listener to remove.
  1529. */
  1530. removeEventListener( type, listener ) {
  1531. const listeners = this._listeners;
  1532. if ( listeners === undefined ) return;
  1533. const listenerArray = listeners[ type ];
  1534. if ( listenerArray !== undefined ) {
  1535. const index = listenerArray.indexOf( listener );
  1536. if ( index !== -1 ) {
  1537. listenerArray.splice( index, 1 );
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * Dispatches an event object.
  1543. *
  1544. * @param {Object} event - The event that gets fired.
  1545. */
  1546. dispatchEvent( event ) {
  1547. const listeners = this._listeners;
  1548. if ( listeners === undefined ) return;
  1549. const listenerArray = listeners[ event.type ];
  1550. if ( listenerArray !== undefined ) {
  1551. event.target = this;
  1552. // Make a copy, in case listeners are removed while iterating.
  1553. const array = listenerArray.slice( 0 );
  1554. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1555. array[ i ].call( this, event );
  1556. }
  1557. event.target = null;
  1558. }
  1559. }
  1560. }
  1561. 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' ];
  1562. let _seed = 1234567;
  1563. const DEG2RAD = Math.PI / 180;
  1564. const RAD2DEG = 180 / Math.PI;
  1565. /**
  1566. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1567. * (universally unique identifier).
  1568. *
  1569. * @return {string} The UUID.
  1570. */
  1571. function generateUUID() {
  1572. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1573. const d0 = Math.random() * 0xffffffff | 0;
  1574. const d1 = Math.random() * 0xffffffff | 0;
  1575. const d2 = Math.random() * 0xffffffff | 0;
  1576. const d3 = Math.random() * 0xffffffff | 0;
  1577. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1578. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1579. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1580. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1581. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1582. return uuid.toLowerCase();
  1583. }
  1584. /**
  1585. * Clamps the given value between min and max.
  1586. *
  1587. * @param {number} value - The value to clamp.
  1588. * @param {number} min - The min value.
  1589. * @param {number} max - The max value.
  1590. * @return {number} The clamped value.
  1591. */
  1592. function clamp( value, min, max ) {
  1593. return Math.max( min, Math.min( max, value ) );
  1594. }
  1595. /**
  1596. * Computes the Euclidean modulo of the given parameters that
  1597. * is `( ( n % m ) + m ) % m`.
  1598. *
  1599. * @param {number} n - The first parameter.
  1600. * @param {number} m - The second parameter.
  1601. * @return {number} The Euclidean modulo.
  1602. */
  1603. function euclideanModulo( n, m ) {
  1604. // https://en.wikipedia.org/wiki/Modulo_operation
  1605. return ( ( n % m ) + m ) % m;
  1606. }
  1607. /**
  1608. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1609. * for the given value.
  1610. *
  1611. * @param {number} x - The value to be mapped.
  1612. * @param {number} a1 - Minimum value for range A.
  1613. * @param {number} a2 - Maximum value for range A.
  1614. * @param {number} b1 - Minimum value for range B.
  1615. * @param {number} b2 - Maximum value for range B.
  1616. * @return {number} The mapped value.
  1617. */
  1618. function mapLinear( x, a1, a2, b1, b2 ) {
  1619. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1620. }
  1621. /**
  1622. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1623. * between the start and end point.
  1624. *
  1625. * @param {number} x - The start point
  1626. * @param {number} y - The end point.
  1627. * @param {number} value - A value between start and end.
  1628. * @return {number} The interpolation factor.
  1629. */
  1630. function inverseLerp( x, y, value ) {
  1631. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1632. if ( x !== y ) {
  1633. return ( value - x ) / ( y - x );
  1634. } else {
  1635. return 0;
  1636. }
  1637. }
  1638. /**
  1639. * Returns a value linearly interpolated from two known points based on the given interval -
  1640. * `t = 0` will return `x` and `t = 1` will return `y`.
  1641. *
  1642. * @param {number} x - The start point
  1643. * @param {number} y - The end point.
  1644. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1645. * @return {number} The interpolated value.
  1646. */
  1647. function lerp( x, y, t ) {
  1648. return ( 1 - t ) * x + t * y;
  1649. }
  1650. /**
  1651. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1652. * time to maintain frame rate independent movement. For details, see
  1653. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1654. *
  1655. * @param {number} x - The current point.
  1656. * @param {number} y - The target point.
  1657. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1658. * and a lower value will make the movement more gradual.
  1659. * @param {number} dt - Delta time in seconds.
  1660. * @return {number} The interpolated value.
  1661. */
  1662. function damp( x, y, lambda, dt ) {
  1663. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1664. }
  1665. /**
  1666. * Returns a value that alternates between `0` and the given `length` parameter.
  1667. *
  1668. * @param {number} x - The value to pingpong.
  1669. * @param {number} [length=1] - The positive value the function will pingpong to.
  1670. * @return {number} The alternated value.
  1671. */
  1672. function pingpong( x, length = 1 ) {
  1673. // https://www.desmos.com/calculator/vcsjnyz7x4
  1674. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1675. }
  1676. /**
  1677. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1678. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1679. * the `min` and `max`.
  1680. *
  1681. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1682. *
  1683. * @param {number} x - The value to evaluate based on its position between min and max.
  1684. * @param {number} min - The min value. Any x value below min will be `0`.
  1685. * @param {number} max - The max value. Any x value above max will be `1`.
  1686. * @return {number} The alternated value.
  1687. */
  1688. function smoothstep( x, min, max ) {
  1689. if ( x <= min ) return 0;
  1690. if ( x >= max ) return 1;
  1691. x = ( x - min ) / ( max - min );
  1692. return x * x * ( 3 - 2 * x );
  1693. }
  1694. /**
  1695. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1696. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1697. *
  1698. * @param {number} x - The value to evaluate based on its position between min and max.
  1699. * @param {number} min - The min value. Any x value below min will be `0`.
  1700. * @param {number} max - The max value. Any x value above max will be `1`.
  1701. * @return {number} The alternated value.
  1702. */
  1703. function smootherstep( x, min, max ) {
  1704. if ( x <= min ) return 0;
  1705. if ( x >= max ) return 1;
  1706. x = ( x - min ) / ( max - min );
  1707. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1708. }
  1709. /**
  1710. * Returns a random integer from `<low, high>` interval.
  1711. *
  1712. * @param {number} low - The lower value boundary.
  1713. * @param {number} high - The upper value boundary
  1714. * @return {number} A random integer.
  1715. */
  1716. function randInt( low, high ) {
  1717. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1718. }
  1719. /**
  1720. * Returns a random float from `<low, high>` interval.
  1721. *
  1722. * @param {number} low - The lower value boundary.
  1723. * @param {number} high - The upper value boundary
  1724. * @return {number} A random float.
  1725. */
  1726. function randFloat( low, high ) {
  1727. return low + Math.random() * ( high - low );
  1728. }
  1729. /**
  1730. * Returns a random integer from `<-range/2, range/2>` interval.
  1731. *
  1732. * @param {number} range - Defines the value range.
  1733. * @return {number} A random float.
  1734. */
  1735. function randFloatSpread( range ) {
  1736. return range * ( 0.5 - Math.random() );
  1737. }
  1738. /**
  1739. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1740. *
  1741. * @param {number} [s] - The integer seed.
  1742. * @return {number} A random float.
  1743. */
  1744. function seededRandom( s ) {
  1745. if ( s !== undefined ) _seed = s;
  1746. // Mulberry32 generator
  1747. let t = _seed += 0x6D2B79F5;
  1748. t = Math.imul( t ^ t >>> 15, t | 1 );
  1749. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1750. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1751. }
  1752. /**
  1753. * Converts degrees to radians.
  1754. *
  1755. * @param {number} degrees - A value in degrees.
  1756. * @return {number} The converted value in radians.
  1757. */
  1758. function degToRad( degrees ) {
  1759. return degrees * DEG2RAD;
  1760. }
  1761. /**
  1762. * Converts radians to degrees.
  1763. *
  1764. * @param {number} radians - A value in radians.
  1765. * @return {number} The converted value in degrees.
  1766. */
  1767. function radToDeg( radians ) {
  1768. return radians * RAD2DEG;
  1769. }
  1770. /**
  1771. * Returns `true` if the given number is a power of two.
  1772. *
  1773. * @param {number} value - The value to check.
  1774. * @return {boolean} Whether the given number is a power of two or not.
  1775. */
  1776. function isPowerOfTwo( value ) {
  1777. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1778. }
  1779. /**
  1780. * Returns the smallest power of two that is greater than or equal to the given number.
  1781. *
  1782. * @param {number} value - The value to find a POT for.
  1783. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1784. */
  1785. function ceilPowerOfTwo( value ) {
  1786. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1787. }
  1788. /**
  1789. * Returns the largest power of two that is less than or equal to the given number.
  1790. *
  1791. * @param {number} value - The value to find a POT for.
  1792. * @return {number} The largest power of two that is less than or equal to the given number.
  1793. */
  1794. function floorPowerOfTwo( value ) {
  1795. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1796. }
  1797. /**
  1798. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1799. * defined by the given angles and order.
  1800. *
  1801. * Rotations are applied to the axes in the order specified by order:
  1802. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1803. *
  1804. * @param {Quaternion} q - The quaternion to set.
  1805. * @param {number} a - The rotation applied to the first axis, in radians.
  1806. * @param {number} b - The rotation applied to the second axis, in radians.
  1807. * @param {number} c - The rotation applied to the third axis, in radians.
  1808. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1809. */
  1810. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1811. const cos = Math.cos;
  1812. const sin = Math.sin;
  1813. const c2 = cos( b / 2 );
  1814. const s2 = sin( b / 2 );
  1815. const c13 = cos( ( a + c ) / 2 );
  1816. const s13 = sin( ( a + c ) / 2 );
  1817. const c1_3 = cos( ( a - c ) / 2 );
  1818. const s1_3 = sin( ( a - c ) / 2 );
  1819. const c3_1 = cos( ( c - a ) / 2 );
  1820. const s3_1 = sin( ( c - a ) / 2 );
  1821. switch ( order ) {
  1822. case 'XYX':
  1823. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1824. break;
  1825. case 'YZY':
  1826. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1827. break;
  1828. case 'ZXZ':
  1829. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1830. break;
  1831. case 'XZX':
  1832. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1833. break;
  1834. case 'YXY':
  1835. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1836. break;
  1837. case 'ZYZ':
  1838. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1839. break;
  1840. default:
  1841. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1842. }
  1843. }
  1844. /**
  1845. * Denormalizes the given value according to the given typed array.
  1846. *
  1847. * @param {number} value - The value to denormalize.
  1848. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1849. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1850. */
  1851. function denormalize( value, array ) {
  1852. switch ( array.constructor ) {
  1853. case Float32Array:
  1854. return value;
  1855. case Uint32Array:
  1856. return value / 4294967295.0;
  1857. case Uint16Array:
  1858. return value / 65535.0;
  1859. case Uint8Array:
  1860. return value / 255.0;
  1861. case Int32Array:
  1862. return Math.max( value / 2147483647.0, -1 );
  1863. case Int16Array:
  1864. return Math.max( value / 32767.0, -1 );
  1865. case Int8Array:
  1866. return Math.max( value / 127.0, -1 );
  1867. default:
  1868. throw new Error( 'Invalid component type.' );
  1869. }
  1870. }
  1871. /**
  1872. * Normalizes the given value according to the given typed array.
  1873. *
  1874. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1875. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1876. * @return {number} The normalize value.
  1877. */
  1878. function normalize( value, array ) {
  1879. switch ( array.constructor ) {
  1880. case Float32Array:
  1881. return value;
  1882. case Uint32Array:
  1883. return Math.round( value * 4294967295.0 );
  1884. case Uint16Array:
  1885. return Math.round( value * 65535.0 );
  1886. case Uint8Array:
  1887. return Math.round( value * 255.0 );
  1888. case Int32Array:
  1889. return Math.round( value * 2147483647.0 );
  1890. case Int16Array:
  1891. return Math.round( value * 32767.0 );
  1892. case Int8Array:
  1893. return Math.round( value * 127.0 );
  1894. default:
  1895. throw new Error( 'Invalid component type.' );
  1896. }
  1897. }
  1898. /**
  1899. * @class
  1900. * @classdesc A collection of math utility functions.
  1901. * @hideconstructor
  1902. */
  1903. const MathUtils = {
  1904. DEG2RAD: DEG2RAD,
  1905. RAD2DEG: RAD2DEG,
  1906. /**
  1907. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1908. * (universally unique identifier).
  1909. *
  1910. * @static
  1911. * @method
  1912. * @return {string} The UUID.
  1913. */
  1914. generateUUID: generateUUID,
  1915. /**
  1916. * Clamps the given value between min and max.
  1917. *
  1918. * @static
  1919. * @method
  1920. * @param {number} value - The value to clamp.
  1921. * @param {number} min - The min value.
  1922. * @param {number} max - The max value.
  1923. * @return {number} The clamped value.
  1924. */
  1925. clamp: clamp,
  1926. /**
  1927. * Computes the Euclidean modulo of the given parameters that
  1928. * is `( ( n % m ) + m ) % m`.
  1929. *
  1930. * @static
  1931. * @method
  1932. * @param {number} n - The first parameter.
  1933. * @param {number} m - The second parameter.
  1934. * @return {number} The Euclidean modulo.
  1935. */
  1936. euclideanModulo: euclideanModulo,
  1937. /**
  1938. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1939. * for the given value.
  1940. *
  1941. * @static
  1942. * @method
  1943. * @param {number} x - The value to be mapped.
  1944. * @param {number} a1 - Minimum value for range A.
  1945. * @param {number} a2 - Maximum value for range A.
  1946. * @param {number} b1 - Minimum value for range B.
  1947. * @param {number} b2 - Maximum value for range B.
  1948. * @return {number} The mapped value.
  1949. */
  1950. mapLinear: mapLinear,
  1951. /**
  1952. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1953. * between the start and end point.
  1954. *
  1955. * @static
  1956. * @method
  1957. * @param {number} x - The start point
  1958. * @param {number} y - The end point.
  1959. * @param {number} value - A value between start and end.
  1960. * @return {number} The interpolation factor.
  1961. */
  1962. inverseLerp: inverseLerp,
  1963. /**
  1964. * Returns a value linearly interpolated from two known points based on the given interval -
  1965. * `t = 0` will return `x` and `t = 1` will return `y`.
  1966. *
  1967. * @static
  1968. * @method
  1969. * @param {number} x - The start point
  1970. * @param {number} y - The end point.
  1971. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1972. * @return {number} The interpolated value.
  1973. */
  1974. lerp: lerp,
  1975. /**
  1976. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1977. * time to maintain frame rate independent movement. For details, see
  1978. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1979. *
  1980. * @static
  1981. * @method
  1982. * @param {number} x - The current point.
  1983. * @param {number} y - The target point.
  1984. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1985. * and a lower value will make the movement more gradual.
  1986. * @param {number} dt - Delta time in seconds.
  1987. * @return {number} The interpolated value.
  1988. */
  1989. damp: damp,
  1990. /**
  1991. * Returns a value that alternates between `0` and the given `length` parameter.
  1992. *
  1993. * @static
  1994. * @method
  1995. * @param {number} x - The value to pingpong.
  1996. * @param {number} [length=1] - The positive value the function will pingpong to.
  1997. * @return {number} The alternated value.
  1998. */
  1999. pingpong: pingpong,
  2000. /**
  2001. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2002. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2003. * the `min` and `max`.
  2004. *
  2005. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2006. *
  2007. * @static
  2008. * @method
  2009. * @param {number} x - The value to evaluate based on its position between min and max.
  2010. * @param {number} min - The min value. Any x value below min will be `0`.
  2011. * @param {number} max - The max value. Any x value above max will be `1`.
  2012. * @return {number} The alternated value.
  2013. */
  2014. smoothstep: smoothstep,
  2015. /**
  2016. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2017. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2018. *
  2019. * @static
  2020. * @method
  2021. * @param {number} x - The value to evaluate based on its position between min and max.
  2022. * @param {number} min - The min value. Any x value below min will be `0`.
  2023. * @param {number} max - The max value. Any x value above max will be `1`.
  2024. * @return {number} The alternated value.
  2025. */
  2026. smootherstep: smootherstep,
  2027. /**
  2028. * Returns a random integer from `<low, high>` interval.
  2029. *
  2030. * @static
  2031. * @method
  2032. * @param {number} low - The lower value boundary.
  2033. * @param {number} high - The upper value boundary
  2034. * @return {number} A random integer.
  2035. */
  2036. randInt: randInt,
  2037. /**
  2038. * Returns a random float from `<low, high>` interval.
  2039. *
  2040. * @static
  2041. * @method
  2042. * @param {number} low - The lower value boundary.
  2043. * @param {number} high - The upper value boundary
  2044. * @return {number} A random float.
  2045. */
  2046. randFloat: randFloat,
  2047. /**
  2048. * Returns a random integer from `<-range/2, range/2>` interval.
  2049. *
  2050. * @static
  2051. * @method
  2052. * @param {number} range - Defines the value range.
  2053. * @return {number} A random float.
  2054. */
  2055. randFloatSpread: randFloatSpread,
  2056. /**
  2057. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2058. *
  2059. * @static
  2060. * @method
  2061. * @param {number} [s] - The integer seed.
  2062. * @return {number} A random float.
  2063. */
  2064. seededRandom: seededRandom,
  2065. /**
  2066. * Converts degrees to radians.
  2067. *
  2068. * @static
  2069. * @method
  2070. * @param {number} degrees - A value in degrees.
  2071. * @return {number} The converted value in radians.
  2072. */
  2073. degToRad: degToRad,
  2074. /**
  2075. * Converts radians to degrees.
  2076. *
  2077. * @static
  2078. * @method
  2079. * @param {number} radians - A value in radians.
  2080. * @return {number} The converted value in degrees.
  2081. */
  2082. radToDeg: radToDeg,
  2083. /**
  2084. * Returns `true` if the given number is a power of two.
  2085. *
  2086. * @static
  2087. * @method
  2088. * @param {number} value - The value to check.
  2089. * @return {boolean} Whether the given number is a power of two or not.
  2090. */
  2091. isPowerOfTwo: isPowerOfTwo,
  2092. /**
  2093. * Returns the smallest power of two that is greater than or equal to the given number.
  2094. *
  2095. * @static
  2096. * @method
  2097. * @param {number} value - The value to find a POT for.
  2098. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2099. */
  2100. ceilPowerOfTwo: ceilPowerOfTwo,
  2101. /**
  2102. * Returns the largest power of two that is less than or equal to the given number.
  2103. *
  2104. * @static
  2105. * @method
  2106. * @param {number} value - The value to find a POT for.
  2107. * @return {number} The largest power of two that is less than or equal to the given number.
  2108. */
  2109. floorPowerOfTwo: floorPowerOfTwo,
  2110. /**
  2111. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2112. * defined by the given angles and order.
  2113. *
  2114. * Rotations are applied to the axes in the order specified by order:
  2115. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2116. *
  2117. * @static
  2118. * @method
  2119. * @param {Quaternion} q - The quaternion to set.
  2120. * @param {number} a - The rotation applied to the first axis, in radians.
  2121. * @param {number} b - The rotation applied to the second axis, in radians.
  2122. * @param {number} c - The rotation applied to the third axis, in radians.
  2123. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2124. */
  2125. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2126. /**
  2127. * Normalizes the given value according to the given typed array.
  2128. *
  2129. * @static
  2130. * @method
  2131. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2132. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2133. * @return {number} The normalize value.
  2134. */
  2135. normalize: normalize,
  2136. /**
  2137. * Denormalizes the given value according to the given typed array.
  2138. *
  2139. * @static
  2140. * @method
  2141. * @param {number} value - The value to denormalize.
  2142. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2143. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2144. */
  2145. denormalize: denormalize
  2146. };
  2147. /**
  2148. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2149. * (labeled x and y), which can be used to represent a number of things, such as:
  2150. *
  2151. * - A point in 2D space (i.e. a position on a plane).
  2152. * - A direction and length across a plane. In three.js the length will
  2153. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2154. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2155. * - Any arbitrary ordered pair of numbers.
  2156. *
  2157. * There are other things a 2D vector can be used to represent, such as
  2158. * momentum vectors, complex numbers and so on, however these are the most
  2159. * common uses in three.js.
  2160. *
  2161. * Iterating through a vector instance will yield its components `(x, y)` in
  2162. * the corresponding order.
  2163. * ```js
  2164. * const a = new THREE.Vector2( 0, 1 );
  2165. *
  2166. * //no arguments; will be initialised to (0, 0)
  2167. * const b = new THREE.Vector2( );
  2168. *
  2169. * const d = a.distanceTo( b );
  2170. * ```
  2171. */
  2172. class Vector2 {
  2173. /**
  2174. * Constructs a new 2D vector.
  2175. *
  2176. * @param {number} [x=0] - The x value of this vector.
  2177. * @param {number} [y=0] - The y value of this vector.
  2178. */
  2179. constructor( x = 0, y = 0 ) {
  2180. /**
  2181. * This flag can be used for type testing.
  2182. *
  2183. * @type {boolean}
  2184. * @readonly
  2185. * @default true
  2186. */
  2187. Vector2.prototype.isVector2 = true;
  2188. /**
  2189. * The x value of this vector.
  2190. *
  2191. * @type {number}
  2192. */
  2193. this.x = x;
  2194. /**
  2195. * The y value of this vector.
  2196. *
  2197. * @type {number}
  2198. */
  2199. this.y = y;
  2200. }
  2201. /**
  2202. * Alias for {@link Vector2#x}.
  2203. *
  2204. * @type {number}
  2205. */
  2206. get width() {
  2207. return this.x;
  2208. }
  2209. set width( value ) {
  2210. this.x = value;
  2211. }
  2212. /**
  2213. * Alias for {@link Vector2#y}.
  2214. *
  2215. * @type {number}
  2216. */
  2217. get height() {
  2218. return this.y;
  2219. }
  2220. set height( value ) {
  2221. this.y = value;
  2222. }
  2223. /**
  2224. * Sets the vector components.
  2225. *
  2226. * @param {number} x - The value of the x component.
  2227. * @param {number} y - The value of the y component.
  2228. * @return {Vector2} A reference to this vector.
  2229. */
  2230. set( x, y ) {
  2231. this.x = x;
  2232. this.y = y;
  2233. return this;
  2234. }
  2235. /**
  2236. * Sets the vector components to the same value.
  2237. *
  2238. * @param {number} scalar - The value to set for all vector components.
  2239. * @return {Vector2} A reference to this vector.
  2240. */
  2241. setScalar( scalar ) {
  2242. this.x = scalar;
  2243. this.y = scalar;
  2244. return this;
  2245. }
  2246. /**
  2247. * Sets the vector's x component to the given value
  2248. *
  2249. * @param {number} x - The value to set.
  2250. * @return {Vector2} A reference to this vector.
  2251. */
  2252. setX( x ) {
  2253. this.x = x;
  2254. return this;
  2255. }
  2256. /**
  2257. * Sets the vector's y component to the given value
  2258. *
  2259. * @param {number} y - The value to set.
  2260. * @return {Vector2} A reference to this vector.
  2261. */
  2262. setY( y ) {
  2263. this.y = y;
  2264. return this;
  2265. }
  2266. /**
  2267. * Allows to set a vector component with an index.
  2268. *
  2269. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2270. * @param {number} value - The value to set.
  2271. * @return {Vector2} A reference to this vector.
  2272. */
  2273. setComponent( index, value ) {
  2274. switch ( index ) {
  2275. case 0: this.x = value; break;
  2276. case 1: this.y = value; break;
  2277. default: throw new Error( 'index is out of range: ' + index );
  2278. }
  2279. return this;
  2280. }
  2281. /**
  2282. * Returns the value of the vector component which matches the given index.
  2283. *
  2284. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2285. * @return {number} A vector component value.
  2286. */
  2287. getComponent( index ) {
  2288. switch ( index ) {
  2289. case 0: return this.x;
  2290. case 1: return this.y;
  2291. default: throw new Error( 'index is out of range: ' + index );
  2292. }
  2293. }
  2294. /**
  2295. * Returns a new vector with copied values from this instance.
  2296. *
  2297. * @return {Vector2} A clone of this instance.
  2298. */
  2299. clone() {
  2300. return new this.constructor( this.x, this.y );
  2301. }
  2302. /**
  2303. * Copies the values of the given vector to this instance.
  2304. *
  2305. * @param {Vector2} v - The vector to copy.
  2306. * @return {Vector2} A reference to this vector.
  2307. */
  2308. copy( v ) {
  2309. this.x = v.x;
  2310. this.y = v.y;
  2311. return this;
  2312. }
  2313. /**
  2314. * Adds the given vector to this instance.
  2315. *
  2316. * @param {Vector2} v - The vector to add.
  2317. * @return {Vector2} A reference to this vector.
  2318. */
  2319. add( v ) {
  2320. this.x += v.x;
  2321. this.y += v.y;
  2322. return this;
  2323. }
  2324. /**
  2325. * Adds the given scalar value to all components of this instance.
  2326. *
  2327. * @param {number} s - The scalar to add.
  2328. * @return {Vector2} A reference to this vector.
  2329. */
  2330. addScalar( s ) {
  2331. this.x += s;
  2332. this.y += s;
  2333. return this;
  2334. }
  2335. /**
  2336. * Adds the given vectors and stores the result in this instance.
  2337. *
  2338. * @param {Vector2} a - The first vector.
  2339. * @param {Vector2} b - The second vector.
  2340. * @return {Vector2} A reference to this vector.
  2341. */
  2342. addVectors( a, b ) {
  2343. this.x = a.x + b.x;
  2344. this.y = a.y + b.y;
  2345. return this;
  2346. }
  2347. /**
  2348. * Adds the given vector scaled by the given factor to this instance.
  2349. *
  2350. * @param {Vector2} v - The vector.
  2351. * @param {number} s - The factor that scales `v`.
  2352. * @return {Vector2} A reference to this vector.
  2353. */
  2354. addScaledVector( v, s ) {
  2355. this.x += v.x * s;
  2356. this.y += v.y * s;
  2357. return this;
  2358. }
  2359. /**
  2360. * Subtracts the given vector from this instance.
  2361. *
  2362. * @param {Vector2} v - The vector to subtract.
  2363. * @return {Vector2} A reference to this vector.
  2364. */
  2365. sub( v ) {
  2366. this.x -= v.x;
  2367. this.y -= v.y;
  2368. return this;
  2369. }
  2370. /**
  2371. * Subtracts the given scalar value from all components of this instance.
  2372. *
  2373. * @param {number} s - The scalar to subtract.
  2374. * @return {Vector2} A reference to this vector.
  2375. */
  2376. subScalar( s ) {
  2377. this.x -= s;
  2378. this.y -= s;
  2379. return this;
  2380. }
  2381. /**
  2382. * Subtracts the given vectors and stores the result in this instance.
  2383. *
  2384. * @param {Vector2} a - The first vector.
  2385. * @param {Vector2} b - The second vector.
  2386. * @return {Vector2} A reference to this vector.
  2387. */
  2388. subVectors( a, b ) {
  2389. this.x = a.x - b.x;
  2390. this.y = a.y - b.y;
  2391. return this;
  2392. }
  2393. /**
  2394. * Multiplies the given vector with this instance.
  2395. *
  2396. * @param {Vector2} v - The vector to multiply.
  2397. * @return {Vector2} A reference to this vector.
  2398. */
  2399. multiply( v ) {
  2400. this.x *= v.x;
  2401. this.y *= v.y;
  2402. return this;
  2403. }
  2404. /**
  2405. * Multiplies the given scalar value with all components of this instance.
  2406. *
  2407. * @param {number} scalar - The scalar to multiply.
  2408. * @return {Vector2} A reference to this vector.
  2409. */
  2410. multiplyScalar( scalar ) {
  2411. this.x *= scalar;
  2412. this.y *= scalar;
  2413. return this;
  2414. }
  2415. /**
  2416. * Divides this instance by the given vector.
  2417. *
  2418. * @param {Vector2} v - The vector to divide.
  2419. * @return {Vector2} A reference to this vector.
  2420. */
  2421. divide( v ) {
  2422. this.x /= v.x;
  2423. this.y /= v.y;
  2424. return this;
  2425. }
  2426. /**
  2427. * Divides this vector by the given scalar.
  2428. *
  2429. * @param {number} scalar - The scalar to divide.
  2430. * @return {Vector2} A reference to this vector.
  2431. */
  2432. divideScalar( scalar ) {
  2433. return this.multiplyScalar( 1 / scalar );
  2434. }
  2435. /**
  2436. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2437. * the given 3x3 matrix.
  2438. *
  2439. * @param {Matrix3} m - The matrix to apply.
  2440. * @return {Vector2} A reference to this vector.
  2441. */
  2442. applyMatrix3( m ) {
  2443. const x = this.x, y = this.y;
  2444. const e = m.elements;
  2445. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2446. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2447. return this;
  2448. }
  2449. /**
  2450. * If this vector's x or y value is greater than the given vector's x or y
  2451. * value, replace that value with the corresponding min value.
  2452. *
  2453. * @param {Vector2} v - The vector.
  2454. * @return {Vector2} A reference to this vector.
  2455. */
  2456. min( v ) {
  2457. this.x = Math.min( this.x, v.x );
  2458. this.y = Math.min( this.y, v.y );
  2459. return this;
  2460. }
  2461. /**
  2462. * If this vector's x or y value is less than the given vector's x or y
  2463. * value, replace that value with the corresponding max value.
  2464. *
  2465. * @param {Vector2} v - The vector.
  2466. * @return {Vector2} A reference to this vector.
  2467. */
  2468. max( v ) {
  2469. this.x = Math.max( this.x, v.x );
  2470. this.y = Math.max( this.y, v.y );
  2471. return this;
  2472. }
  2473. /**
  2474. * If this vector's x or y value is greater than the max vector's x or y
  2475. * value, it is replaced by the corresponding value.
  2476. * If this vector's x or y value is less than the min vector's x or y value,
  2477. * it is replaced by the corresponding value.
  2478. *
  2479. * @param {Vector2} min - The minimum x and y values.
  2480. * @param {Vector2} max - The maximum x and y values in the desired range.
  2481. * @return {Vector2} A reference to this vector.
  2482. */
  2483. clamp( min, max ) {
  2484. // assumes min < max, componentwise
  2485. this.x = clamp( this.x, min.x, max.x );
  2486. this.y = clamp( this.y, min.y, max.y );
  2487. return this;
  2488. }
  2489. /**
  2490. * If this vector's x or y values are greater than the max value, they are
  2491. * replaced by the max value.
  2492. * If this vector's x or y values are less than the min value, they are
  2493. * replaced by the min value.
  2494. *
  2495. * @param {number} minVal - The minimum value the components will be clamped to.
  2496. * @param {number} maxVal - The maximum value the components will be clamped to.
  2497. * @return {Vector2} A reference to this vector.
  2498. */
  2499. clampScalar( minVal, maxVal ) {
  2500. this.x = clamp( this.x, minVal, maxVal );
  2501. this.y = clamp( this.y, minVal, maxVal );
  2502. return this;
  2503. }
  2504. /**
  2505. * If this vector's length is greater than the max value, it is replaced by
  2506. * the max value.
  2507. * If this vector's length is less than the min value, it is replaced by the
  2508. * min value.
  2509. *
  2510. * @param {number} min - The minimum value the vector length will be clamped to.
  2511. * @param {number} max - The maximum value the vector length will be clamped to.
  2512. * @return {Vector2} A reference to this vector.
  2513. */
  2514. clampLength( min, max ) {
  2515. const length = this.length();
  2516. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2517. }
  2518. /**
  2519. * The components of this vector are rounded down to the nearest integer value.
  2520. *
  2521. * @return {Vector2} A reference to this vector.
  2522. */
  2523. floor() {
  2524. this.x = Math.floor( this.x );
  2525. this.y = Math.floor( this.y );
  2526. return this;
  2527. }
  2528. /**
  2529. * The components of this vector are rounded up to the nearest integer value.
  2530. *
  2531. * @return {Vector2} A reference to this vector.
  2532. */
  2533. ceil() {
  2534. this.x = Math.ceil( this.x );
  2535. this.y = Math.ceil( this.y );
  2536. return this;
  2537. }
  2538. /**
  2539. * The components of this vector are rounded to the nearest integer value
  2540. *
  2541. * @return {Vector2} A reference to this vector.
  2542. */
  2543. round() {
  2544. this.x = Math.round( this.x );
  2545. this.y = Math.round( this.y );
  2546. return this;
  2547. }
  2548. /**
  2549. * The components of this vector are rounded towards zero (up if negative,
  2550. * down if positive) to an integer value.
  2551. *
  2552. * @return {Vector2} A reference to this vector.
  2553. */
  2554. roundToZero() {
  2555. this.x = Math.trunc( this.x );
  2556. this.y = Math.trunc( this.y );
  2557. return this;
  2558. }
  2559. /**
  2560. * Inverts this vector - i.e. sets x = -x and y = -y.
  2561. *
  2562. * @return {Vector2} A reference to this vector.
  2563. */
  2564. negate() {
  2565. this.x = - this.x;
  2566. this.y = - this.y;
  2567. return this;
  2568. }
  2569. /**
  2570. * Calculates the dot product of the given vector with this instance.
  2571. *
  2572. * @param {Vector2} v - The vector to compute the dot product with.
  2573. * @return {number} The result of the dot product.
  2574. */
  2575. dot( v ) {
  2576. return this.x * v.x + this.y * v.y;
  2577. }
  2578. /**
  2579. * Calculates the cross product of the given vector with this instance.
  2580. *
  2581. * @param {Vector2} v - The vector to compute the cross product with.
  2582. * @return {number} The result of the cross product.
  2583. */
  2584. cross( v ) {
  2585. return this.x * v.y - this.y * v.x;
  2586. }
  2587. /**
  2588. * Computes the square of the Euclidean length (straight-line length) from
  2589. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2590. * compare the length squared instead as it is slightly more efficient to calculate.
  2591. *
  2592. * @return {number} The square length of this vector.
  2593. */
  2594. lengthSq() {
  2595. return this.x * this.x + this.y * this.y;
  2596. }
  2597. /**
  2598. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2599. *
  2600. * @return {number} The length of this vector.
  2601. */
  2602. length() {
  2603. return Math.sqrt( this.x * this.x + this.y * this.y );
  2604. }
  2605. /**
  2606. * Computes the Manhattan length of this vector.
  2607. *
  2608. * @return {number} The length of this vector.
  2609. */
  2610. manhattanLength() {
  2611. return Math.abs( this.x ) + Math.abs( this.y );
  2612. }
  2613. /**
  2614. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2615. * with the same direction as this one, but with a vector length of `1`.
  2616. *
  2617. * @return {Vector2} A reference to this vector.
  2618. */
  2619. normalize() {
  2620. return this.divideScalar( this.length() || 1 );
  2621. }
  2622. /**
  2623. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2624. *
  2625. * @return {number} The angle in radians.
  2626. */
  2627. angle() {
  2628. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2629. return angle;
  2630. }
  2631. /**
  2632. * Returns the angle between the given vector and this instance in radians.
  2633. *
  2634. * @param {Vector2} v - The vector to compute the angle with.
  2635. * @return {number} The angle in radians.
  2636. */
  2637. angleTo( v ) {
  2638. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2639. if ( denominator === 0 ) return Math.PI / 2;
  2640. const theta = this.dot( v ) / denominator;
  2641. // clamp, to handle numerical problems
  2642. return Math.acos( clamp( theta, -1, 1 ) );
  2643. }
  2644. /**
  2645. * Computes the distance from the given vector to this instance.
  2646. *
  2647. * @param {Vector2} v - The vector to compute the distance to.
  2648. * @return {number} The distance.
  2649. */
  2650. distanceTo( v ) {
  2651. return Math.sqrt( this.distanceToSquared( v ) );
  2652. }
  2653. /**
  2654. * Computes the squared distance from the given vector to this instance.
  2655. * If you are just comparing the distance with another distance, you should compare
  2656. * the distance squared instead as it is slightly more efficient to calculate.
  2657. *
  2658. * @param {Vector2} v - The vector to compute the squared distance to.
  2659. * @return {number} The squared distance.
  2660. */
  2661. distanceToSquared( v ) {
  2662. const dx = this.x - v.x, dy = this.y - v.y;
  2663. return dx * dx + dy * dy;
  2664. }
  2665. /**
  2666. * Computes the Manhattan distance from the given vector to this instance.
  2667. *
  2668. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2669. * @return {number} The Manhattan distance.
  2670. */
  2671. manhattanDistanceTo( v ) {
  2672. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2673. }
  2674. /**
  2675. * Sets this vector to a vector with the same direction as this one, but
  2676. * with the specified length.
  2677. *
  2678. * @param {number} length - The new length of this vector.
  2679. * @return {Vector2} A reference to this vector.
  2680. */
  2681. setLength( length ) {
  2682. return this.normalize().multiplyScalar( length );
  2683. }
  2684. /**
  2685. * Linearly interpolates between the given vector and this instance, where
  2686. * alpha is the percent distance along the line - alpha = 0 will be this
  2687. * vector, and alpha = 1 will be the given one.
  2688. *
  2689. * @param {Vector2} v - The vector to interpolate towards.
  2690. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2691. * @return {Vector2} A reference to this vector.
  2692. */
  2693. lerp( v, alpha ) {
  2694. this.x += ( v.x - this.x ) * alpha;
  2695. this.y += ( v.y - this.y ) * alpha;
  2696. return this;
  2697. }
  2698. /**
  2699. * Linearly interpolates between the given vectors, where alpha is the percent
  2700. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2701. * be the second one. The result is stored in this instance.
  2702. *
  2703. * @param {Vector2} v1 - The first vector.
  2704. * @param {Vector2} v2 - The second vector.
  2705. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2706. * @return {Vector2} A reference to this vector.
  2707. */
  2708. lerpVectors( v1, v2, alpha ) {
  2709. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2710. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2711. return this;
  2712. }
  2713. /**
  2714. * Returns `true` if this vector is equal with the given one.
  2715. *
  2716. * @param {Vector2} v - The vector to test for equality.
  2717. * @return {boolean} Whether this vector is equal with the given one.
  2718. */
  2719. equals( v ) {
  2720. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2721. }
  2722. /**
  2723. * Sets this vector's x value to be `array[ offset ]` and y
  2724. * value to be `array[ offset + 1 ]`.
  2725. *
  2726. * @param {Array<number>} array - An array holding the vector component values.
  2727. * @param {number} [offset=0] - The offset into the array.
  2728. * @return {Vector2} A reference to this vector.
  2729. */
  2730. fromArray( array, offset = 0 ) {
  2731. this.x = array[ offset ];
  2732. this.y = array[ offset + 1 ];
  2733. return this;
  2734. }
  2735. /**
  2736. * Writes the components of this vector to the given array. If no array is provided,
  2737. * the method returns a new instance.
  2738. *
  2739. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2740. * @param {number} [offset=0] - Index of the first element in the array.
  2741. * @return {Array<number>} The vector components.
  2742. */
  2743. toArray( array = [], offset = 0 ) {
  2744. array[ offset ] = this.x;
  2745. array[ offset + 1 ] = this.y;
  2746. return array;
  2747. }
  2748. /**
  2749. * Sets the components of this vector from the given buffer attribute.
  2750. *
  2751. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2752. * @param {number} index - The index into the attribute.
  2753. * @return {Vector2} A reference to this vector.
  2754. */
  2755. fromBufferAttribute( attribute, index ) {
  2756. this.x = attribute.getX( index );
  2757. this.y = attribute.getY( index );
  2758. return this;
  2759. }
  2760. /**
  2761. * Rotates this vector around the given center by the given angle.
  2762. *
  2763. * @param {Vector2} center - The point around which to rotate.
  2764. * @param {number} angle - The angle to rotate, in radians.
  2765. * @return {Vector2} A reference to this vector.
  2766. */
  2767. rotateAround( center, angle ) {
  2768. const c = Math.cos( angle ), s = Math.sin( angle );
  2769. const x = this.x - center.x;
  2770. const y = this.y - center.y;
  2771. this.x = x * c - y * s + center.x;
  2772. this.y = x * s + y * c + center.y;
  2773. return this;
  2774. }
  2775. /**
  2776. * Sets each component of this vector to a pseudo-random value between `0` and
  2777. * `1`, excluding `1`.
  2778. *
  2779. * @return {Vector2} A reference to this vector.
  2780. */
  2781. random() {
  2782. this.x = Math.random();
  2783. this.y = Math.random();
  2784. return this;
  2785. }
  2786. *[ Symbol.iterator ]() {
  2787. yield this.x;
  2788. yield this.y;
  2789. }
  2790. }
  2791. /**
  2792. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2793. *
  2794. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2795. * the corresponding order.
  2796. *
  2797. * Note that three.js expects Quaternions to be normalized.
  2798. * ```js
  2799. * const quaternion = new THREE.Quaternion();
  2800. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2801. *
  2802. * const vector = new THREE.Vector3( 1, 0, 0 );
  2803. * vector.applyQuaternion( quaternion );
  2804. * ```
  2805. */
  2806. class Quaternion {
  2807. /**
  2808. * Constructs a new quaternion.
  2809. *
  2810. * @param {number} [x=0] - The x value of this quaternion.
  2811. * @param {number} [y=0] - The y value of this quaternion.
  2812. * @param {number} [z=0] - The z value of this quaternion.
  2813. * @param {number} [w=1] - The w value of this quaternion.
  2814. */
  2815. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2816. /**
  2817. * This flag can be used for type testing.
  2818. *
  2819. * @type {boolean}
  2820. * @readonly
  2821. * @default true
  2822. */
  2823. this.isQuaternion = true;
  2824. this._x = x;
  2825. this._y = y;
  2826. this._z = z;
  2827. this._w = w;
  2828. }
  2829. /**
  2830. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2831. * quaternion data are managed in flat arrays.
  2832. *
  2833. * @param {Array<number>} dst - The destination array.
  2834. * @param {number} dstOffset - An offset into the destination array.
  2835. * @param {Array<number>} src0 - The source array of the first quaternion.
  2836. * @param {number} srcOffset0 - An offset into the first source array.
  2837. * @param {Array<number>} src1 - The source array of the second quaternion.
  2838. * @param {number} srcOffset1 - An offset into the second source array.
  2839. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2840. * @see {@link Quaternion#slerp}
  2841. */
  2842. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2843. // fuzz-free, array-based Quaternion SLERP operation
  2844. let x0 = src0[ srcOffset0 + 0 ],
  2845. y0 = src0[ srcOffset0 + 1 ],
  2846. z0 = src0[ srcOffset0 + 2 ],
  2847. w0 = src0[ srcOffset0 + 3 ];
  2848. const x1 = src1[ srcOffset1 + 0 ],
  2849. y1 = src1[ srcOffset1 + 1 ],
  2850. z1 = src1[ srcOffset1 + 2 ],
  2851. w1 = src1[ srcOffset1 + 3 ];
  2852. if ( t === 0 ) {
  2853. dst[ dstOffset + 0 ] = x0;
  2854. dst[ dstOffset + 1 ] = y0;
  2855. dst[ dstOffset + 2 ] = z0;
  2856. dst[ dstOffset + 3 ] = w0;
  2857. return;
  2858. }
  2859. if ( t === 1 ) {
  2860. dst[ dstOffset + 0 ] = x1;
  2861. dst[ dstOffset + 1 ] = y1;
  2862. dst[ dstOffset + 2 ] = z1;
  2863. dst[ dstOffset + 3 ] = w1;
  2864. return;
  2865. }
  2866. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2867. let s = 1 - t;
  2868. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2869. dir = ( cos >= 0 ? 1 : -1 ),
  2870. sqrSin = 1 - cos * cos;
  2871. // Skip the Slerp for tiny steps to avoid numeric problems:
  2872. if ( sqrSin > Number.EPSILON ) {
  2873. const sin = Math.sqrt( sqrSin ),
  2874. len = Math.atan2( sin, cos * dir );
  2875. s = Math.sin( s * len ) / sin;
  2876. t = Math.sin( t * len ) / sin;
  2877. }
  2878. const tDir = t * dir;
  2879. x0 = x0 * s + x1 * tDir;
  2880. y0 = y0 * s + y1 * tDir;
  2881. z0 = z0 * s + z1 * tDir;
  2882. w0 = w0 * s + w1 * tDir;
  2883. // Normalize in case we just did a lerp:
  2884. if ( s === 1 - t ) {
  2885. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2886. x0 *= f;
  2887. y0 *= f;
  2888. z0 *= f;
  2889. w0 *= f;
  2890. }
  2891. }
  2892. dst[ dstOffset ] = x0;
  2893. dst[ dstOffset + 1 ] = y0;
  2894. dst[ dstOffset + 2 ] = z0;
  2895. dst[ dstOffset + 3 ] = w0;
  2896. }
  2897. /**
  2898. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2899. * in flat arrays.
  2900. *
  2901. * @param {Array<number>} dst - The destination array.
  2902. * @param {number} dstOffset - An offset into the destination array.
  2903. * @param {Array<number>} src0 - The source array of the first quaternion.
  2904. * @param {number} srcOffset0 - An offset into the first source array.
  2905. * @param {Array<number>} src1 - The source array of the second quaternion.
  2906. * @param {number} srcOffset1 - An offset into the second source array.
  2907. * @return {Array<number>} The destination array.
  2908. * @see {@link Quaternion#multiplyQuaternions}.
  2909. */
  2910. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2911. const x0 = src0[ srcOffset0 ];
  2912. const y0 = src0[ srcOffset0 + 1 ];
  2913. const z0 = src0[ srcOffset0 + 2 ];
  2914. const w0 = src0[ srcOffset0 + 3 ];
  2915. const x1 = src1[ srcOffset1 ];
  2916. const y1 = src1[ srcOffset1 + 1 ];
  2917. const z1 = src1[ srcOffset1 + 2 ];
  2918. const w1 = src1[ srcOffset1 + 3 ];
  2919. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2920. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2921. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2922. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2923. return dst;
  2924. }
  2925. /**
  2926. * The x value of this quaternion.
  2927. *
  2928. * @type {number}
  2929. * @default 0
  2930. */
  2931. get x() {
  2932. return this._x;
  2933. }
  2934. set x( value ) {
  2935. this._x = value;
  2936. this._onChangeCallback();
  2937. }
  2938. /**
  2939. * The y value of this quaternion.
  2940. *
  2941. * @type {number}
  2942. * @default 0
  2943. */
  2944. get y() {
  2945. return this._y;
  2946. }
  2947. set y( value ) {
  2948. this._y = value;
  2949. this._onChangeCallback();
  2950. }
  2951. /**
  2952. * The z value of this quaternion.
  2953. *
  2954. * @type {number}
  2955. * @default 0
  2956. */
  2957. get z() {
  2958. return this._z;
  2959. }
  2960. set z( value ) {
  2961. this._z = value;
  2962. this._onChangeCallback();
  2963. }
  2964. /**
  2965. * The w value of this quaternion.
  2966. *
  2967. * @type {number}
  2968. * @default 1
  2969. */
  2970. get w() {
  2971. return this._w;
  2972. }
  2973. set w( value ) {
  2974. this._w = value;
  2975. this._onChangeCallback();
  2976. }
  2977. /**
  2978. * Sets the quaternion components.
  2979. *
  2980. * @param {number} x - The x value of this quaternion.
  2981. * @param {number} y - The y value of this quaternion.
  2982. * @param {number} z - The z value of this quaternion.
  2983. * @param {number} w - The w value of this quaternion.
  2984. * @return {Quaternion} A reference to this quaternion.
  2985. */
  2986. set( x, y, z, w ) {
  2987. this._x = x;
  2988. this._y = y;
  2989. this._z = z;
  2990. this._w = w;
  2991. this._onChangeCallback();
  2992. return this;
  2993. }
  2994. /**
  2995. * Returns a new quaternion with copied values from this instance.
  2996. *
  2997. * @return {Quaternion} A clone of this instance.
  2998. */
  2999. clone() {
  3000. return new this.constructor( this._x, this._y, this._z, this._w );
  3001. }
  3002. /**
  3003. * Copies the values of the given quaternion to this instance.
  3004. *
  3005. * @param {Quaternion} quaternion - The quaternion to copy.
  3006. * @return {Quaternion} A reference to this quaternion.
  3007. */
  3008. copy( quaternion ) {
  3009. this._x = quaternion.x;
  3010. this._y = quaternion.y;
  3011. this._z = quaternion.z;
  3012. this._w = quaternion.w;
  3013. this._onChangeCallback();
  3014. return this;
  3015. }
  3016. /**
  3017. * Sets this quaternion from the rotation specified by the given
  3018. * Euler angles.
  3019. *
  3020. * @param {Euler} euler - The Euler angles.
  3021. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3022. * @return {Quaternion} A reference to this quaternion.
  3023. */
  3024. setFromEuler( euler, update = true ) {
  3025. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3026. // http://www.mathworks.com/matlabcentral/fileexchange/
  3027. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3028. // content/SpinCalc.m
  3029. const cos = Math.cos;
  3030. const sin = Math.sin;
  3031. const c1 = cos( x / 2 );
  3032. const c2 = cos( y / 2 );
  3033. const c3 = cos( z / 2 );
  3034. const s1 = sin( x / 2 );
  3035. const s2 = sin( y / 2 );
  3036. const s3 = sin( z / 2 );
  3037. switch ( order ) {
  3038. case 'XYZ':
  3039. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3040. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3041. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3042. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3043. break;
  3044. case 'YXZ':
  3045. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3046. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3047. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3048. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3049. break;
  3050. case 'ZXY':
  3051. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3052. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3053. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3054. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3055. break;
  3056. case 'ZYX':
  3057. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3058. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3059. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3060. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3061. break;
  3062. case 'YZX':
  3063. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3064. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3065. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3066. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3067. break;
  3068. case 'XZY':
  3069. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3070. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3071. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3072. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3073. break;
  3074. default:
  3075. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3076. }
  3077. if ( update === true ) this._onChangeCallback();
  3078. return this;
  3079. }
  3080. /**
  3081. * Sets this quaternion from the given axis and angle.
  3082. *
  3083. * @param {Vector3} axis - The normalized axis.
  3084. * @param {number} angle - The angle in radians.
  3085. * @return {Quaternion} A reference to this quaternion.
  3086. */
  3087. setFromAxisAngle( axis, angle ) {
  3088. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3089. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3090. this._x = axis.x * s;
  3091. this._y = axis.y * s;
  3092. this._z = axis.z * s;
  3093. this._w = Math.cos( halfAngle );
  3094. this._onChangeCallback();
  3095. return this;
  3096. }
  3097. /**
  3098. * Sets this quaternion from the given rotation matrix.
  3099. *
  3100. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3101. * @return {Quaternion} A reference to this quaternion.
  3102. */
  3103. setFromRotationMatrix( m ) {
  3104. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3105. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3106. const te = m.elements,
  3107. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3108. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3109. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3110. trace = m11 + m22 + m33;
  3111. if ( trace > 0 ) {
  3112. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3113. this._w = 0.25 / s;
  3114. this._x = ( m32 - m23 ) * s;
  3115. this._y = ( m13 - m31 ) * s;
  3116. this._z = ( m21 - m12 ) * s;
  3117. } else if ( m11 > m22 && m11 > m33 ) {
  3118. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3119. this._w = ( m32 - m23 ) / s;
  3120. this._x = 0.25 * s;
  3121. this._y = ( m12 + m21 ) / s;
  3122. this._z = ( m13 + m31 ) / s;
  3123. } else if ( m22 > m33 ) {
  3124. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3125. this._w = ( m13 - m31 ) / s;
  3126. this._x = ( m12 + m21 ) / s;
  3127. this._y = 0.25 * s;
  3128. this._z = ( m23 + m32 ) / s;
  3129. } else {
  3130. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3131. this._w = ( m21 - m12 ) / s;
  3132. this._x = ( m13 + m31 ) / s;
  3133. this._y = ( m23 + m32 ) / s;
  3134. this._z = 0.25 * s;
  3135. }
  3136. this._onChangeCallback();
  3137. return this;
  3138. }
  3139. /**
  3140. * Sets this quaternion to the rotation required to rotate the direction vector
  3141. * `vFrom` to the direction vector `vTo`.
  3142. *
  3143. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3144. * @param {Vector3} vTo - The second (normalized) direction vector.
  3145. * @return {Quaternion} A reference to this quaternion.
  3146. */
  3147. setFromUnitVectors( vFrom, vTo ) {
  3148. // assumes direction vectors vFrom and vTo are normalized
  3149. let r = vFrom.dot( vTo ) + 1;
  3150. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3151. // vFrom and vTo point in opposite directions
  3152. r = 0;
  3153. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3154. this._x = - vFrom.y;
  3155. this._y = vFrom.x;
  3156. this._z = 0;
  3157. this._w = r;
  3158. } else {
  3159. this._x = 0;
  3160. this._y = - vFrom.z;
  3161. this._z = vFrom.y;
  3162. this._w = r;
  3163. }
  3164. } else {
  3165. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3166. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3167. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3168. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3169. this._w = r;
  3170. }
  3171. return this.normalize();
  3172. }
  3173. /**
  3174. * Returns the angle between this quaternion and the given one in radians.
  3175. *
  3176. * @param {Quaternion} q - The quaternion to compute the angle with.
  3177. * @return {number} The angle in radians.
  3178. */
  3179. angleTo( q ) {
  3180. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3181. }
  3182. /**
  3183. * Rotates this quaternion by a given angular step to the given quaternion.
  3184. * The method ensures that the final quaternion will not overshoot `q`.
  3185. *
  3186. * @param {Quaternion} q - The target quaternion.
  3187. * @param {number} step - The angular step in radians.
  3188. * @return {Quaternion} A reference to this quaternion.
  3189. */
  3190. rotateTowards( q, step ) {
  3191. const angle = this.angleTo( q );
  3192. if ( angle === 0 ) return this;
  3193. const t = Math.min( 1, step / angle );
  3194. this.slerp( q, t );
  3195. return this;
  3196. }
  3197. /**
  3198. * Sets this quaternion to the identity quaternion; that is, to the
  3199. * quaternion that represents "no rotation".
  3200. *
  3201. * @return {Quaternion} A reference to this quaternion.
  3202. */
  3203. identity() {
  3204. return this.set( 0, 0, 0, 1 );
  3205. }
  3206. /**
  3207. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3208. * quaternion is assumed to have unit length.
  3209. *
  3210. * @return {Quaternion} A reference to this quaternion.
  3211. */
  3212. invert() {
  3213. return this.conjugate();
  3214. }
  3215. /**
  3216. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3217. * quaternion represents the same rotation in the opposite direction about
  3218. * the rotational axis.
  3219. *
  3220. * @return {Quaternion} A reference to this quaternion.
  3221. */
  3222. conjugate() {
  3223. this._x *= -1;
  3224. this._y *= -1;
  3225. this._z *= -1;
  3226. this._onChangeCallback();
  3227. return this;
  3228. }
  3229. /**
  3230. * Calculates the dot product of this quaternion and the given one.
  3231. *
  3232. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3233. * @return {number} The result of the dot product.
  3234. */
  3235. dot( v ) {
  3236. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3237. }
  3238. /**
  3239. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3240. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3241. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3242. * {@link Quaternion#length}.
  3243. *
  3244. * @return {number} The squared Euclidean length.
  3245. */
  3246. lengthSq() {
  3247. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3248. }
  3249. /**
  3250. * Computes the Euclidean length (straight-line length) of this quaternion,
  3251. * considered as a 4 dimensional vector.
  3252. *
  3253. * @return {number} The Euclidean length.
  3254. */
  3255. length() {
  3256. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3257. }
  3258. /**
  3259. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3260. * the same rotation as this one, but has a length equal to `1`.
  3261. *
  3262. * @return {Quaternion} A reference to this quaternion.
  3263. */
  3264. normalize() {
  3265. let l = this.length();
  3266. if ( l === 0 ) {
  3267. this._x = 0;
  3268. this._y = 0;
  3269. this._z = 0;
  3270. this._w = 1;
  3271. } else {
  3272. l = 1 / l;
  3273. this._x = this._x * l;
  3274. this._y = this._y * l;
  3275. this._z = this._z * l;
  3276. this._w = this._w * l;
  3277. }
  3278. this._onChangeCallback();
  3279. return this;
  3280. }
  3281. /**
  3282. * Multiplies this quaternion by the given one.
  3283. *
  3284. * @param {Quaternion} q - The quaternion.
  3285. * @return {Quaternion} A reference to this quaternion.
  3286. */
  3287. multiply( q ) {
  3288. return this.multiplyQuaternions( this, q );
  3289. }
  3290. /**
  3291. * Pre-multiplies this quaternion by the given one.
  3292. *
  3293. * @param {Quaternion} q - The quaternion.
  3294. * @return {Quaternion} A reference to this quaternion.
  3295. */
  3296. premultiply( q ) {
  3297. return this.multiplyQuaternions( q, this );
  3298. }
  3299. /**
  3300. * Multiplies the given quaternions and stores the result in this instance.
  3301. *
  3302. * @param {Quaternion} a - The first quaternion.
  3303. * @param {Quaternion} b - The second quaternion.
  3304. * @return {Quaternion} A reference to this quaternion.
  3305. */
  3306. multiplyQuaternions( a, b ) {
  3307. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3308. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3309. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3310. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3311. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3312. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3313. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3314. this._onChangeCallback();
  3315. return this;
  3316. }
  3317. /**
  3318. * Performs a spherical linear interpolation between quaternions.
  3319. *
  3320. * @param {Quaternion} qb - The target quaternion.
  3321. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3322. * @return {Quaternion} A reference to this quaternion.
  3323. */
  3324. slerp( qb, t ) {
  3325. if ( t === 0 ) return this;
  3326. if ( t === 1 ) return this.copy( qb );
  3327. const x = this._x, y = this._y, z = this._z, w = this._w;
  3328. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3329. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3330. if ( cosHalfTheta < 0 ) {
  3331. this._w = - qb._w;
  3332. this._x = - qb._x;
  3333. this._y = - qb._y;
  3334. this._z = - qb._z;
  3335. cosHalfTheta = - cosHalfTheta;
  3336. } else {
  3337. this.copy( qb );
  3338. }
  3339. if ( cosHalfTheta >= 1.0 ) {
  3340. this._w = w;
  3341. this._x = x;
  3342. this._y = y;
  3343. this._z = z;
  3344. return this;
  3345. }
  3346. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3347. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3348. const s = 1 - t;
  3349. this._w = s * w + t * this._w;
  3350. this._x = s * x + t * this._x;
  3351. this._y = s * y + t * this._y;
  3352. this._z = s * z + t * this._z;
  3353. this.normalize(); // normalize calls _onChangeCallback()
  3354. return this;
  3355. }
  3356. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3357. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3358. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3359. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3360. this._w = ( w * ratioA + this._w * ratioB );
  3361. this._x = ( x * ratioA + this._x * ratioB );
  3362. this._y = ( y * ratioA + this._y * ratioB );
  3363. this._z = ( z * ratioA + this._z * ratioB );
  3364. this._onChangeCallback();
  3365. return this;
  3366. }
  3367. /**
  3368. * Performs a spherical linear interpolation between the given quaternions
  3369. * and stores the result in this quaternion.
  3370. *
  3371. * @param {Quaternion} qa - The source quaternion.
  3372. * @param {Quaternion} qb - The target quaternion.
  3373. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3374. * @return {Quaternion} A reference to this quaternion.
  3375. */
  3376. slerpQuaternions( qa, qb, t ) {
  3377. return this.copy( qa ).slerp( qb, t );
  3378. }
  3379. /**
  3380. * Sets this quaternion to a uniformly random, normalized quaternion.
  3381. *
  3382. * @return {Quaternion} A reference to this quaternion.
  3383. */
  3384. random() {
  3385. // Ken Shoemake
  3386. // Uniform random rotations
  3387. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3388. const theta1 = 2 * Math.PI * Math.random();
  3389. const theta2 = 2 * Math.PI * Math.random();
  3390. const x0 = Math.random();
  3391. const r1 = Math.sqrt( 1 - x0 );
  3392. const r2 = Math.sqrt( x0 );
  3393. return this.set(
  3394. r1 * Math.sin( theta1 ),
  3395. r1 * Math.cos( theta1 ),
  3396. r2 * Math.sin( theta2 ),
  3397. r2 * Math.cos( theta2 ),
  3398. );
  3399. }
  3400. /**
  3401. * Returns `true` if this quaternion is equal with the given one.
  3402. *
  3403. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3404. * @return {boolean} Whether this quaternion is equal with the given one.
  3405. */
  3406. equals( quaternion ) {
  3407. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3408. }
  3409. /**
  3410. * Sets this quaternion's components from the given array.
  3411. *
  3412. * @param {Array<number>} array - An array holding the quaternion component values.
  3413. * @param {number} [offset=0] - The offset into the array.
  3414. * @return {Quaternion} A reference to this quaternion.
  3415. */
  3416. fromArray( array, offset = 0 ) {
  3417. this._x = array[ offset ];
  3418. this._y = array[ offset + 1 ];
  3419. this._z = array[ offset + 2 ];
  3420. this._w = array[ offset + 3 ];
  3421. this._onChangeCallback();
  3422. return this;
  3423. }
  3424. /**
  3425. * Writes the components of this quaternion to the given array. If no array is provided,
  3426. * the method returns a new instance.
  3427. *
  3428. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3429. * @param {number} [offset=0] - Index of the first element in the array.
  3430. * @return {Array<number>} The quaternion components.
  3431. */
  3432. toArray( array = [], offset = 0 ) {
  3433. array[ offset ] = this._x;
  3434. array[ offset + 1 ] = this._y;
  3435. array[ offset + 2 ] = this._z;
  3436. array[ offset + 3 ] = this._w;
  3437. return array;
  3438. }
  3439. /**
  3440. * Sets the components of this quaternion from the given buffer attribute.
  3441. *
  3442. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3443. * @param {number} index - The index into the attribute.
  3444. * @return {Quaternion} A reference to this quaternion.
  3445. */
  3446. fromBufferAttribute( attribute, index ) {
  3447. this._x = attribute.getX( index );
  3448. this._y = attribute.getY( index );
  3449. this._z = attribute.getZ( index );
  3450. this._w = attribute.getW( index );
  3451. this._onChangeCallback();
  3452. return this;
  3453. }
  3454. /**
  3455. * This methods defines the serialization result of this class. Returns the
  3456. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3457. *
  3458. * @return {Array<number>} The serialized quaternion.
  3459. */
  3460. toJSON() {
  3461. return this.toArray();
  3462. }
  3463. _onChange( callback ) {
  3464. this._onChangeCallback = callback;
  3465. return this;
  3466. }
  3467. _onChangeCallback() {}
  3468. *[ Symbol.iterator ]() {
  3469. yield this._x;
  3470. yield this._y;
  3471. yield this._z;
  3472. yield this._w;
  3473. }
  3474. }
  3475. /**
  3476. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3477. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3478. *
  3479. * - A point in 3D space.
  3480. * - A direction and length in 3D space. In three.js the length will
  3481. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3482. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3483. * - Any arbitrary ordered triplet of numbers.
  3484. *
  3485. * There are other things a 3D vector can be used to represent, such as
  3486. * momentum vectors and so on, however these are the most
  3487. * common uses in three.js.
  3488. *
  3489. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3490. * the corresponding order.
  3491. * ```js
  3492. * const a = new THREE.Vector3( 0, 1, 0 );
  3493. *
  3494. * //no arguments; will be initialised to (0, 0, 0)
  3495. * const b = new THREE.Vector3( );
  3496. *
  3497. * const d = a.distanceTo( b );
  3498. * ```
  3499. */
  3500. class Vector3 {
  3501. /**
  3502. * Constructs a new 3D vector.
  3503. *
  3504. * @param {number} [x=0] - The x value of this vector.
  3505. * @param {number} [y=0] - The y value of this vector.
  3506. * @param {number} [z=0] - The z value of this vector.
  3507. */
  3508. constructor( x = 0, y = 0, z = 0 ) {
  3509. /**
  3510. * This flag can be used for type testing.
  3511. *
  3512. * @type {boolean}
  3513. * @readonly
  3514. * @default true
  3515. */
  3516. Vector3.prototype.isVector3 = true;
  3517. /**
  3518. * The x value of this vector.
  3519. *
  3520. * @type {number}
  3521. */
  3522. this.x = x;
  3523. /**
  3524. * The y value of this vector.
  3525. *
  3526. * @type {number}
  3527. */
  3528. this.y = y;
  3529. /**
  3530. * The z value of this vector.
  3531. *
  3532. * @type {number}
  3533. */
  3534. this.z = z;
  3535. }
  3536. /**
  3537. * Sets the vector components.
  3538. *
  3539. * @param {number} x - The value of the x component.
  3540. * @param {number} y - The value of the y component.
  3541. * @param {number} z - The value of the z component.
  3542. * @return {Vector3} A reference to this vector.
  3543. */
  3544. set( x, y, z ) {
  3545. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3546. this.x = x;
  3547. this.y = y;
  3548. this.z = z;
  3549. return this;
  3550. }
  3551. /**
  3552. * Sets the vector components to the same value.
  3553. *
  3554. * @param {number} scalar - The value to set for all vector components.
  3555. * @return {Vector3} A reference to this vector.
  3556. */
  3557. setScalar( scalar ) {
  3558. this.x = scalar;
  3559. this.y = scalar;
  3560. this.z = scalar;
  3561. return this;
  3562. }
  3563. /**
  3564. * Sets the vector's x component to the given value
  3565. *
  3566. * @param {number} x - The value to set.
  3567. * @return {Vector3} A reference to this vector.
  3568. */
  3569. setX( x ) {
  3570. this.x = x;
  3571. return this;
  3572. }
  3573. /**
  3574. * Sets the vector's y component to the given value
  3575. *
  3576. * @param {number} y - The value to set.
  3577. * @return {Vector3} A reference to this vector.
  3578. */
  3579. setY( y ) {
  3580. this.y = y;
  3581. return this;
  3582. }
  3583. /**
  3584. * Sets the vector's z component to the given value
  3585. *
  3586. * @param {number} z - The value to set.
  3587. * @return {Vector3} A reference to this vector.
  3588. */
  3589. setZ( z ) {
  3590. this.z = z;
  3591. return this;
  3592. }
  3593. /**
  3594. * Allows to set a vector component with an index.
  3595. *
  3596. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3597. * @param {number} value - The value to set.
  3598. * @return {Vector3} A reference to this vector.
  3599. */
  3600. setComponent( index, value ) {
  3601. switch ( index ) {
  3602. case 0: this.x = value; break;
  3603. case 1: this.y = value; break;
  3604. case 2: this.z = value; break;
  3605. default: throw new Error( 'index is out of range: ' + index );
  3606. }
  3607. return this;
  3608. }
  3609. /**
  3610. * Returns the value of the vector component which matches the given index.
  3611. *
  3612. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3613. * @return {number} A vector component value.
  3614. */
  3615. getComponent( index ) {
  3616. switch ( index ) {
  3617. case 0: return this.x;
  3618. case 1: return this.y;
  3619. case 2: return this.z;
  3620. default: throw new Error( 'index is out of range: ' + index );
  3621. }
  3622. }
  3623. /**
  3624. * Returns a new vector with copied values from this instance.
  3625. *
  3626. * @return {Vector3} A clone of this instance.
  3627. */
  3628. clone() {
  3629. return new this.constructor( this.x, this.y, this.z );
  3630. }
  3631. /**
  3632. * Copies the values of the given vector to this instance.
  3633. *
  3634. * @param {Vector3} v - The vector to copy.
  3635. * @return {Vector3} A reference to this vector.
  3636. */
  3637. copy( v ) {
  3638. this.x = v.x;
  3639. this.y = v.y;
  3640. this.z = v.z;
  3641. return this;
  3642. }
  3643. /**
  3644. * Adds the given vector to this instance.
  3645. *
  3646. * @param {Vector3} v - The vector to add.
  3647. * @return {Vector3} A reference to this vector.
  3648. */
  3649. add( v ) {
  3650. this.x += v.x;
  3651. this.y += v.y;
  3652. this.z += v.z;
  3653. return this;
  3654. }
  3655. /**
  3656. * Adds the given scalar value to all components of this instance.
  3657. *
  3658. * @param {number} s - The scalar to add.
  3659. * @return {Vector3} A reference to this vector.
  3660. */
  3661. addScalar( s ) {
  3662. this.x += s;
  3663. this.y += s;
  3664. this.z += s;
  3665. return this;
  3666. }
  3667. /**
  3668. * Adds the given vectors and stores the result in this instance.
  3669. *
  3670. * @param {Vector3} a - The first vector.
  3671. * @param {Vector3} b - The second vector.
  3672. * @return {Vector3} A reference to this vector.
  3673. */
  3674. addVectors( a, b ) {
  3675. this.x = a.x + b.x;
  3676. this.y = a.y + b.y;
  3677. this.z = a.z + b.z;
  3678. return this;
  3679. }
  3680. /**
  3681. * Adds the given vector scaled by the given factor to this instance.
  3682. *
  3683. * @param {Vector3|Vector4} v - The vector.
  3684. * @param {number} s - The factor that scales `v`.
  3685. * @return {Vector3} A reference to this vector.
  3686. */
  3687. addScaledVector( v, s ) {
  3688. this.x += v.x * s;
  3689. this.y += v.y * s;
  3690. this.z += v.z * s;
  3691. return this;
  3692. }
  3693. /**
  3694. * Subtracts the given vector from this instance.
  3695. *
  3696. * @param {Vector3} v - The vector to subtract.
  3697. * @return {Vector3} A reference to this vector.
  3698. */
  3699. sub( v ) {
  3700. this.x -= v.x;
  3701. this.y -= v.y;
  3702. this.z -= v.z;
  3703. return this;
  3704. }
  3705. /**
  3706. * Subtracts the given scalar value from all components of this instance.
  3707. *
  3708. * @param {number} s - The scalar to subtract.
  3709. * @return {Vector3} A reference to this vector.
  3710. */
  3711. subScalar( s ) {
  3712. this.x -= s;
  3713. this.y -= s;
  3714. this.z -= s;
  3715. return this;
  3716. }
  3717. /**
  3718. * Subtracts the given vectors and stores the result in this instance.
  3719. *
  3720. * @param {Vector3} a - The first vector.
  3721. * @param {Vector3} b - The second vector.
  3722. * @return {Vector3} A reference to this vector.
  3723. */
  3724. subVectors( a, b ) {
  3725. this.x = a.x - b.x;
  3726. this.y = a.y - b.y;
  3727. this.z = a.z - b.z;
  3728. return this;
  3729. }
  3730. /**
  3731. * Multiplies the given vector with this instance.
  3732. *
  3733. * @param {Vector3} v - The vector to multiply.
  3734. * @return {Vector3} A reference to this vector.
  3735. */
  3736. multiply( v ) {
  3737. this.x *= v.x;
  3738. this.y *= v.y;
  3739. this.z *= v.z;
  3740. return this;
  3741. }
  3742. /**
  3743. * Multiplies the given scalar value with all components of this instance.
  3744. *
  3745. * @param {number} scalar - The scalar to multiply.
  3746. * @return {Vector3} A reference to this vector.
  3747. */
  3748. multiplyScalar( scalar ) {
  3749. this.x *= scalar;
  3750. this.y *= scalar;
  3751. this.z *= scalar;
  3752. return this;
  3753. }
  3754. /**
  3755. * Multiplies the given vectors and stores the result in this instance.
  3756. *
  3757. * @param {Vector3} a - The first vector.
  3758. * @param {Vector3} b - The second vector.
  3759. * @return {Vector3} A reference to this vector.
  3760. */
  3761. multiplyVectors( a, b ) {
  3762. this.x = a.x * b.x;
  3763. this.y = a.y * b.y;
  3764. this.z = a.z * b.z;
  3765. return this;
  3766. }
  3767. /**
  3768. * Applies the given Euler rotation to this vector.
  3769. *
  3770. * @param {Euler} euler - The Euler angles.
  3771. * @return {Vector3} A reference to this vector.
  3772. */
  3773. applyEuler( euler ) {
  3774. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3775. }
  3776. /**
  3777. * Applies a rotation specified by an axis and an angle to this vector.
  3778. *
  3779. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3780. * @param {number} angle - The angle in radians.
  3781. * @return {Vector3} A reference to this vector.
  3782. */
  3783. applyAxisAngle( axis, angle ) {
  3784. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3785. }
  3786. /**
  3787. * Multiplies this vector with the given 3x3 matrix.
  3788. *
  3789. * @param {Matrix3} m - The 3x3 matrix.
  3790. * @return {Vector3} A reference to this vector.
  3791. */
  3792. applyMatrix3( m ) {
  3793. const x = this.x, y = this.y, z = this.z;
  3794. const e = m.elements;
  3795. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3796. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3797. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3798. return this;
  3799. }
  3800. /**
  3801. * Multiplies this vector by the given normal matrix and normalizes
  3802. * the result.
  3803. *
  3804. * @param {Matrix3} m - The normal matrix.
  3805. * @return {Vector3} A reference to this vector.
  3806. */
  3807. applyNormalMatrix( m ) {
  3808. return this.applyMatrix3( m ).normalize();
  3809. }
  3810. /**
  3811. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3812. * divides by perspective.
  3813. *
  3814. * @param {Matrix4} m - The matrix to apply.
  3815. * @return {Vector3} A reference to this vector.
  3816. */
  3817. applyMatrix4( m ) {
  3818. const x = this.x, y = this.y, z = this.z;
  3819. const e = m.elements;
  3820. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3821. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3822. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3823. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3824. return this;
  3825. }
  3826. /**
  3827. * Applies the given Quaternion to this vector.
  3828. *
  3829. * @param {Quaternion} q - The Quaternion.
  3830. * @return {Vector3} A reference to this vector.
  3831. */
  3832. applyQuaternion( q ) {
  3833. // quaternion q is assumed to have unit length
  3834. const vx = this.x, vy = this.y, vz = this.z;
  3835. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3836. // t = 2 * cross( q.xyz, v );
  3837. const tx = 2 * ( qy * vz - qz * vy );
  3838. const ty = 2 * ( qz * vx - qx * vz );
  3839. const tz = 2 * ( qx * vy - qy * vx );
  3840. // v + q.w * t + cross( q.xyz, t );
  3841. this.x = vx + qw * tx + qy * tz - qz * ty;
  3842. this.y = vy + qw * ty + qz * tx - qx * tz;
  3843. this.z = vz + qw * tz + qx * ty - qy * tx;
  3844. return this;
  3845. }
  3846. /**
  3847. * Projects this vector from world space into the camera's normalized
  3848. * device coordinate (NDC) space.
  3849. *
  3850. * @param {Camera} camera - The camera.
  3851. * @return {Vector3} A reference to this vector.
  3852. */
  3853. project( camera ) {
  3854. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3855. }
  3856. /**
  3857. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3858. * space into world space.
  3859. *
  3860. * @param {Camera} camera - The camera.
  3861. * @return {Vector3} A reference to this vector.
  3862. */
  3863. unproject( camera ) {
  3864. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3865. }
  3866. /**
  3867. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3868. * subset of the given 4x4 matrix and then normalizes the result.
  3869. *
  3870. * @param {Matrix4} m - The matrix.
  3871. * @return {Vector3} A reference to this vector.
  3872. */
  3873. transformDirection( m ) {
  3874. // input: THREE.Matrix4 affine matrix
  3875. // vector interpreted as a direction
  3876. const x = this.x, y = this.y, z = this.z;
  3877. const e = m.elements;
  3878. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3879. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3880. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3881. return this.normalize();
  3882. }
  3883. /**
  3884. * Divides this instance by the given vector.
  3885. *
  3886. * @param {Vector3} v - The vector to divide.
  3887. * @return {Vector3} A reference to this vector.
  3888. */
  3889. divide( v ) {
  3890. this.x /= v.x;
  3891. this.y /= v.y;
  3892. this.z /= v.z;
  3893. return this;
  3894. }
  3895. /**
  3896. * Divides this vector by the given scalar.
  3897. *
  3898. * @param {number} scalar - The scalar to divide.
  3899. * @return {Vector3} A reference to this vector.
  3900. */
  3901. divideScalar( scalar ) {
  3902. return this.multiplyScalar( 1 / scalar );
  3903. }
  3904. /**
  3905. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3906. * value, replace that value with the corresponding min value.
  3907. *
  3908. * @param {Vector3} v - The vector.
  3909. * @return {Vector3} A reference to this vector.
  3910. */
  3911. min( v ) {
  3912. this.x = Math.min( this.x, v.x );
  3913. this.y = Math.min( this.y, v.y );
  3914. this.z = Math.min( this.z, v.z );
  3915. return this;
  3916. }
  3917. /**
  3918. * If this vector's x, y or z value is less than the given vector's x, y or z
  3919. * value, replace that value with the corresponding max value.
  3920. *
  3921. * @param {Vector3} v - The vector.
  3922. * @return {Vector3} A reference to this vector.
  3923. */
  3924. max( v ) {
  3925. this.x = Math.max( this.x, v.x );
  3926. this.y = Math.max( this.y, v.y );
  3927. this.z = Math.max( this.z, v.z );
  3928. return this;
  3929. }
  3930. /**
  3931. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3932. * value, it is replaced by the corresponding value.
  3933. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3934. * it is replaced by the corresponding value.
  3935. *
  3936. * @param {Vector3} min - The minimum x, y and z values.
  3937. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3938. * @return {Vector3} A reference to this vector.
  3939. */
  3940. clamp( min, max ) {
  3941. // assumes min < max, componentwise
  3942. this.x = clamp( this.x, min.x, max.x );
  3943. this.y = clamp( this.y, min.y, max.y );
  3944. this.z = clamp( this.z, min.z, max.z );
  3945. return this;
  3946. }
  3947. /**
  3948. * If this vector's x, y or z values are greater than the max value, they are
  3949. * replaced by the max value.
  3950. * If this vector's x, y or z values are less than the min value, they are
  3951. * replaced by the min value.
  3952. *
  3953. * @param {number} minVal - The minimum value the components will be clamped to.
  3954. * @param {number} maxVal - The maximum value the components will be clamped to.
  3955. * @return {Vector3} A reference to this vector.
  3956. */
  3957. clampScalar( minVal, maxVal ) {
  3958. this.x = clamp( this.x, minVal, maxVal );
  3959. this.y = clamp( this.y, minVal, maxVal );
  3960. this.z = clamp( this.z, minVal, maxVal );
  3961. return this;
  3962. }
  3963. /**
  3964. * If this vector's length is greater than the max value, it is replaced by
  3965. * the max value.
  3966. * If this vector's length is less than the min value, it is replaced by the
  3967. * min value.
  3968. *
  3969. * @param {number} min - The minimum value the vector length will be clamped to.
  3970. * @param {number} max - The maximum value the vector length will be clamped to.
  3971. * @return {Vector3} A reference to this vector.
  3972. */
  3973. clampLength( min, max ) {
  3974. const length = this.length();
  3975. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3976. }
  3977. /**
  3978. * The components of this vector are rounded down to the nearest integer value.
  3979. *
  3980. * @return {Vector3} A reference to this vector.
  3981. */
  3982. floor() {
  3983. this.x = Math.floor( this.x );
  3984. this.y = Math.floor( this.y );
  3985. this.z = Math.floor( this.z );
  3986. return this;
  3987. }
  3988. /**
  3989. * The components of this vector are rounded up to the nearest integer value.
  3990. *
  3991. * @return {Vector3} A reference to this vector.
  3992. */
  3993. ceil() {
  3994. this.x = Math.ceil( this.x );
  3995. this.y = Math.ceil( this.y );
  3996. this.z = Math.ceil( this.z );
  3997. return this;
  3998. }
  3999. /**
  4000. * The components of this vector are rounded to the nearest integer value
  4001. *
  4002. * @return {Vector3} A reference to this vector.
  4003. */
  4004. round() {
  4005. this.x = Math.round( this.x );
  4006. this.y = Math.round( this.y );
  4007. this.z = Math.round( this.z );
  4008. return this;
  4009. }
  4010. /**
  4011. * The components of this vector are rounded towards zero (up if negative,
  4012. * down if positive) to an integer value.
  4013. *
  4014. * @return {Vector3} A reference to this vector.
  4015. */
  4016. roundToZero() {
  4017. this.x = Math.trunc( this.x );
  4018. this.y = Math.trunc( this.y );
  4019. this.z = Math.trunc( this.z );
  4020. return this;
  4021. }
  4022. /**
  4023. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4024. *
  4025. * @return {Vector3} A reference to this vector.
  4026. */
  4027. negate() {
  4028. this.x = - this.x;
  4029. this.y = - this.y;
  4030. this.z = - this.z;
  4031. return this;
  4032. }
  4033. /**
  4034. * Calculates the dot product of the given vector with this instance.
  4035. *
  4036. * @param {Vector3} v - The vector to compute the dot product with.
  4037. * @return {number} The result of the dot product.
  4038. */
  4039. dot( v ) {
  4040. return this.x * v.x + this.y * v.y + this.z * v.z;
  4041. }
  4042. // TODO lengthSquared?
  4043. /**
  4044. * Computes the square of the Euclidean length (straight-line length) from
  4045. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4046. * compare the length squared instead as it is slightly more efficient to calculate.
  4047. *
  4048. * @return {number} The square length of this vector.
  4049. */
  4050. lengthSq() {
  4051. return this.x * this.x + this.y * this.y + this.z * this.z;
  4052. }
  4053. /**
  4054. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4055. *
  4056. * @return {number} The length of this vector.
  4057. */
  4058. length() {
  4059. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4060. }
  4061. /**
  4062. * Computes the Manhattan length of this vector.
  4063. *
  4064. * @return {number} The length of this vector.
  4065. */
  4066. manhattanLength() {
  4067. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4068. }
  4069. /**
  4070. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4071. * with the same direction as this one, but with a vector length of `1`.
  4072. *
  4073. * @return {Vector3} A reference to this vector.
  4074. */
  4075. normalize() {
  4076. return this.divideScalar( this.length() || 1 );
  4077. }
  4078. /**
  4079. * Sets this vector to a vector with the same direction as this one, but
  4080. * with the specified length.
  4081. *
  4082. * @param {number} length - The new length of this vector.
  4083. * @return {Vector3} A reference to this vector.
  4084. */
  4085. setLength( length ) {
  4086. return this.normalize().multiplyScalar( length );
  4087. }
  4088. /**
  4089. * Linearly interpolates between the given vector and this instance, where
  4090. * alpha is the percent distance along the line - alpha = 0 will be this
  4091. * vector, and alpha = 1 will be the given one.
  4092. *
  4093. * @param {Vector3} v - The vector to interpolate towards.
  4094. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4095. * @return {Vector3} A reference to this vector.
  4096. */
  4097. lerp( v, alpha ) {
  4098. this.x += ( v.x - this.x ) * alpha;
  4099. this.y += ( v.y - this.y ) * alpha;
  4100. this.z += ( v.z - this.z ) * alpha;
  4101. return this;
  4102. }
  4103. /**
  4104. * Linearly interpolates between the given vectors, where alpha is the percent
  4105. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4106. * be the second one. The result is stored in this instance.
  4107. *
  4108. * @param {Vector3} v1 - The first vector.
  4109. * @param {Vector3} v2 - The second vector.
  4110. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4111. * @return {Vector3} A reference to this vector.
  4112. */
  4113. lerpVectors( v1, v2, alpha ) {
  4114. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4115. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4116. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4117. return this;
  4118. }
  4119. /**
  4120. * Calculates the cross product of the given vector with this instance.
  4121. *
  4122. * @param {Vector3} v - The vector to compute the cross product with.
  4123. * @return {Vector3} The result of the cross product.
  4124. */
  4125. cross( v ) {
  4126. return this.crossVectors( this, v );
  4127. }
  4128. /**
  4129. * Calculates the cross product of the given vectors and stores the result
  4130. * in this instance.
  4131. *
  4132. * @param {Vector3} a - The first vector.
  4133. * @param {Vector3} b - The second vector.
  4134. * @return {Vector3} A reference to this vector.
  4135. */
  4136. crossVectors( a, b ) {
  4137. const ax = a.x, ay = a.y, az = a.z;
  4138. const bx = b.x, by = b.y, bz = b.z;
  4139. this.x = ay * bz - az * by;
  4140. this.y = az * bx - ax * bz;
  4141. this.z = ax * by - ay * bx;
  4142. return this;
  4143. }
  4144. /**
  4145. * Projects this vector onto the given one.
  4146. *
  4147. * @param {Vector3} v - The vector to project to.
  4148. * @return {Vector3} A reference to this vector.
  4149. */
  4150. projectOnVector( v ) {
  4151. const denominator = v.lengthSq();
  4152. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4153. const scalar = v.dot( this ) / denominator;
  4154. return this.copy( v ).multiplyScalar( scalar );
  4155. }
  4156. /**
  4157. * Projects this vector onto a plane by subtracting this
  4158. * vector projected onto the plane's normal from this vector.
  4159. *
  4160. * @param {Vector3} planeNormal - The plane normal.
  4161. * @return {Vector3} A reference to this vector.
  4162. */
  4163. projectOnPlane( planeNormal ) {
  4164. _vector$c.copy( this ).projectOnVector( planeNormal );
  4165. return this.sub( _vector$c );
  4166. }
  4167. /**
  4168. * Reflects this vector off a plane orthogonal to the given normal vector.
  4169. *
  4170. * @param {Vector3} normal - The (normalized) normal vector.
  4171. * @return {Vector3} A reference to this vector.
  4172. */
  4173. reflect( normal ) {
  4174. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4175. }
  4176. /**
  4177. * Returns the angle between the given vector and this instance in radians.
  4178. *
  4179. * @param {Vector3} v - The vector to compute the angle with.
  4180. * @return {number} The angle in radians.
  4181. */
  4182. angleTo( v ) {
  4183. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4184. if ( denominator === 0 ) return Math.PI / 2;
  4185. const theta = this.dot( v ) / denominator;
  4186. // clamp, to handle numerical problems
  4187. return Math.acos( clamp( theta, -1, 1 ) );
  4188. }
  4189. /**
  4190. * Computes the distance from the given vector to this instance.
  4191. *
  4192. * @param {Vector3} v - The vector to compute the distance to.
  4193. * @return {number} The distance.
  4194. */
  4195. distanceTo( v ) {
  4196. return Math.sqrt( this.distanceToSquared( v ) );
  4197. }
  4198. /**
  4199. * Computes the squared distance from the given vector to this instance.
  4200. * If you are just comparing the distance with another distance, you should compare
  4201. * the distance squared instead as it is slightly more efficient to calculate.
  4202. *
  4203. * @param {Vector3} v - The vector to compute the squared distance to.
  4204. * @return {number} The squared distance.
  4205. */
  4206. distanceToSquared( v ) {
  4207. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4208. return dx * dx + dy * dy + dz * dz;
  4209. }
  4210. /**
  4211. * Computes the Manhattan distance from the given vector to this instance.
  4212. *
  4213. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4214. * @return {number} The Manhattan distance.
  4215. */
  4216. manhattanDistanceTo( v ) {
  4217. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4218. }
  4219. /**
  4220. * Sets the vector components from the given spherical coordinates.
  4221. *
  4222. * @param {Spherical} s - The spherical coordinates.
  4223. * @return {Vector3} A reference to this vector.
  4224. */
  4225. setFromSpherical( s ) {
  4226. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4227. }
  4228. /**
  4229. * Sets the vector components from the given spherical coordinates.
  4230. *
  4231. * @param {number} radius - The radius.
  4232. * @param {number} phi - The phi angle in radians.
  4233. * @param {number} theta - The theta angle in radians.
  4234. * @return {Vector3} A reference to this vector.
  4235. */
  4236. setFromSphericalCoords( radius, phi, theta ) {
  4237. const sinPhiRadius = Math.sin( phi ) * radius;
  4238. this.x = sinPhiRadius * Math.sin( theta );
  4239. this.y = Math.cos( phi ) * radius;
  4240. this.z = sinPhiRadius * Math.cos( theta );
  4241. return this;
  4242. }
  4243. /**
  4244. * Sets the vector components from the given cylindrical coordinates.
  4245. *
  4246. * @param {Cylindrical} c - The cylindrical coordinates.
  4247. * @return {Vector3} A reference to this vector.
  4248. */
  4249. setFromCylindrical( c ) {
  4250. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4251. }
  4252. /**
  4253. * Sets the vector components from the given cylindrical coordinates.
  4254. *
  4255. * @param {number} radius - The radius.
  4256. * @param {number} theta - The theta angle in radians.
  4257. * @param {number} y - The y value.
  4258. * @return {Vector3} A reference to this vector.
  4259. */
  4260. setFromCylindricalCoords( radius, theta, y ) {
  4261. this.x = radius * Math.sin( theta );
  4262. this.y = y;
  4263. this.z = radius * Math.cos( theta );
  4264. return this;
  4265. }
  4266. /**
  4267. * Sets the vector components to the position elements of the
  4268. * given transformation matrix.
  4269. *
  4270. * @param {Matrix4} m - The 4x4 matrix.
  4271. * @return {Vector3} A reference to this vector.
  4272. */
  4273. setFromMatrixPosition( m ) {
  4274. const e = m.elements;
  4275. this.x = e[ 12 ];
  4276. this.y = e[ 13 ];
  4277. this.z = e[ 14 ];
  4278. return this;
  4279. }
  4280. /**
  4281. * Sets the vector components to the scale elements of the
  4282. * given transformation matrix.
  4283. *
  4284. * @param {Matrix4} m - The 4x4 matrix.
  4285. * @return {Vector3} A reference to this vector.
  4286. */
  4287. setFromMatrixScale( m ) {
  4288. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4289. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4290. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4291. this.x = sx;
  4292. this.y = sy;
  4293. this.z = sz;
  4294. return this;
  4295. }
  4296. /**
  4297. * Sets the vector components from the specified matrix column.
  4298. *
  4299. * @param {Matrix4} m - The 4x4 matrix.
  4300. * @param {number} index - The column index.
  4301. * @return {Vector3} A reference to this vector.
  4302. */
  4303. setFromMatrixColumn( m, index ) {
  4304. return this.fromArray( m.elements, index * 4 );
  4305. }
  4306. /**
  4307. * Sets the vector components from the specified matrix column.
  4308. *
  4309. * @param {Matrix3} m - The 3x3 matrix.
  4310. * @param {number} index - The column index.
  4311. * @return {Vector3} A reference to this vector.
  4312. */
  4313. setFromMatrix3Column( m, index ) {
  4314. return this.fromArray( m.elements, index * 3 );
  4315. }
  4316. /**
  4317. * Sets the vector components from the given Euler angles.
  4318. *
  4319. * @param {Euler} e - The Euler angles to set.
  4320. * @return {Vector3} A reference to this vector.
  4321. */
  4322. setFromEuler( e ) {
  4323. this.x = e._x;
  4324. this.y = e._y;
  4325. this.z = e._z;
  4326. return this;
  4327. }
  4328. /**
  4329. * Sets the vector components from the RGB components of the
  4330. * given color.
  4331. *
  4332. * @param {Color} c - The color to set.
  4333. * @return {Vector3} A reference to this vector.
  4334. */
  4335. setFromColor( c ) {
  4336. this.x = c.r;
  4337. this.y = c.g;
  4338. this.z = c.b;
  4339. return this;
  4340. }
  4341. /**
  4342. * Returns `true` if this vector is equal with the given one.
  4343. *
  4344. * @param {Vector3} v - The vector to test for equality.
  4345. * @return {boolean} Whether this vector is equal with the given one.
  4346. */
  4347. equals( v ) {
  4348. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4349. }
  4350. /**
  4351. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4352. * and z value to be `array[ offset + 2 ]`.
  4353. *
  4354. * @param {Array<number>} array - An array holding the vector component values.
  4355. * @param {number} [offset=0] - The offset into the array.
  4356. * @return {Vector3} A reference to this vector.
  4357. */
  4358. fromArray( array, offset = 0 ) {
  4359. this.x = array[ offset ];
  4360. this.y = array[ offset + 1 ];
  4361. this.z = array[ offset + 2 ];
  4362. return this;
  4363. }
  4364. /**
  4365. * Writes the components of this vector to the given array. If no array is provided,
  4366. * the method returns a new instance.
  4367. *
  4368. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4369. * @param {number} [offset=0] - Index of the first element in the array.
  4370. * @return {Array<number>} The vector components.
  4371. */
  4372. toArray( array = [], offset = 0 ) {
  4373. array[ offset ] = this.x;
  4374. array[ offset + 1 ] = this.y;
  4375. array[ offset + 2 ] = this.z;
  4376. return array;
  4377. }
  4378. /**
  4379. * Sets the components of this vector from the given buffer attribute.
  4380. *
  4381. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4382. * @param {number} index - The index into the attribute.
  4383. * @return {Vector3} A reference to this vector.
  4384. */
  4385. fromBufferAttribute( attribute, index ) {
  4386. this.x = attribute.getX( index );
  4387. this.y = attribute.getY( index );
  4388. this.z = attribute.getZ( index );
  4389. return this;
  4390. }
  4391. /**
  4392. * Sets each component of this vector to a pseudo-random value between `0` and
  4393. * `1`, excluding `1`.
  4394. *
  4395. * @return {Vector3} A reference to this vector.
  4396. */
  4397. random() {
  4398. this.x = Math.random();
  4399. this.y = Math.random();
  4400. this.z = Math.random();
  4401. return this;
  4402. }
  4403. /**
  4404. * Sets this vector to a uniformly random point on a unit sphere.
  4405. *
  4406. * @return {Vector3} A reference to this vector.
  4407. */
  4408. randomDirection() {
  4409. // https://mathworld.wolfram.com/SpherePointPicking.html
  4410. const theta = Math.random() * Math.PI * 2;
  4411. const u = Math.random() * 2 - 1;
  4412. const c = Math.sqrt( 1 - u * u );
  4413. this.x = c * Math.cos( theta );
  4414. this.y = u;
  4415. this.z = c * Math.sin( theta );
  4416. return this;
  4417. }
  4418. *[ Symbol.iterator ]() {
  4419. yield this.x;
  4420. yield this.y;
  4421. yield this.z;
  4422. }
  4423. }
  4424. const _vector$c = /*@__PURE__*/ new Vector3();
  4425. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4426. /**
  4427. * Represents a 3x3 matrix.
  4428. *
  4429. * A Note on Row-Major and Column-Major Ordering:
  4430. *
  4431. * The constructor and {@link Matrix3#set} method take arguments in
  4432. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4433. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4434. * This means that calling:
  4435. * ```js
  4436. * const m = new THREE.Matrix();
  4437. * m.set( 11, 12, 13,
  4438. * 21, 22, 23,
  4439. * 31, 32, 33 );
  4440. * ```
  4441. * will result in the elements array containing:
  4442. * ```js
  4443. * m.elements = [ 11, 21, 31,
  4444. * 12, 22, 32,
  4445. * 13, 23, 33 ];
  4446. * ```
  4447. * and internally all calculations are performed using column-major ordering.
  4448. * However, as the actual ordering makes no difference mathematically and
  4449. * most people are used to thinking about matrices in row-major order, the
  4450. * three.js documentation shows matrices in row-major order. Just bear in
  4451. * mind that if you are reading the source code, you'll have to take the
  4452. * transpose of any matrices outlined here to make sense of the calculations.
  4453. */
  4454. class Matrix3 {
  4455. /**
  4456. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4457. * in row-major order. If no arguments are provided, the constructor
  4458. * initializes the matrix as an identity matrix.
  4459. *
  4460. * @param {number} [n11] - 1-1 matrix element.
  4461. * @param {number} [n12] - 1-2 matrix element.
  4462. * @param {number} [n13] - 1-3 matrix element.
  4463. * @param {number} [n21] - 2-1 matrix element.
  4464. * @param {number} [n22] - 2-2 matrix element.
  4465. * @param {number} [n23] - 2-3 matrix element.
  4466. * @param {number} [n31] - 3-1 matrix element.
  4467. * @param {number} [n32] - 3-2 matrix element.
  4468. * @param {number} [n33] - 3-3 matrix element.
  4469. */
  4470. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4471. /**
  4472. * This flag can be used for type testing.
  4473. *
  4474. * @type {boolean}
  4475. * @readonly
  4476. * @default true
  4477. */
  4478. Matrix3.prototype.isMatrix3 = true;
  4479. /**
  4480. * A column-major list of matrix values.
  4481. *
  4482. * @type {Array<number>}
  4483. */
  4484. this.elements = [
  4485. 1, 0, 0,
  4486. 0, 1, 0,
  4487. 0, 0, 1
  4488. ];
  4489. if ( n11 !== undefined ) {
  4490. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4491. }
  4492. }
  4493. /**
  4494. * Sets the elements of the matrix.The arguments are supposed to be
  4495. * in row-major order.
  4496. *
  4497. * @param {number} [n11] - 1-1 matrix element.
  4498. * @param {number} [n12] - 1-2 matrix element.
  4499. * @param {number} [n13] - 1-3 matrix element.
  4500. * @param {number} [n21] - 2-1 matrix element.
  4501. * @param {number} [n22] - 2-2 matrix element.
  4502. * @param {number} [n23] - 2-3 matrix element.
  4503. * @param {number} [n31] - 3-1 matrix element.
  4504. * @param {number} [n32] - 3-2 matrix element.
  4505. * @param {number} [n33] - 3-3 matrix element.
  4506. * @return {Matrix3} A reference to this matrix.
  4507. */
  4508. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4509. const te = this.elements;
  4510. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4511. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4512. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4513. return this;
  4514. }
  4515. /**
  4516. * Sets this matrix to the 3x3 identity matrix.
  4517. *
  4518. * @return {Matrix3} A reference to this matrix.
  4519. */
  4520. identity() {
  4521. this.set(
  4522. 1, 0, 0,
  4523. 0, 1, 0,
  4524. 0, 0, 1
  4525. );
  4526. return this;
  4527. }
  4528. /**
  4529. * Copies the values of the given matrix to this instance.
  4530. *
  4531. * @param {Matrix3} m - The matrix to copy.
  4532. * @return {Matrix3} A reference to this matrix.
  4533. */
  4534. copy( m ) {
  4535. const te = this.elements;
  4536. const me = m.elements;
  4537. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4538. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4539. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4540. return this;
  4541. }
  4542. /**
  4543. * Extracts the basis of this matrix into the three axis vectors provided.
  4544. *
  4545. * @param {Vector3} xAxis - The basis's x axis.
  4546. * @param {Vector3} yAxis - The basis's y axis.
  4547. * @param {Vector3} zAxis - The basis's z axis.
  4548. * @return {Matrix3} A reference to this matrix.
  4549. */
  4550. extractBasis( xAxis, yAxis, zAxis ) {
  4551. xAxis.setFromMatrix3Column( this, 0 );
  4552. yAxis.setFromMatrix3Column( this, 1 );
  4553. zAxis.setFromMatrix3Column( this, 2 );
  4554. return this;
  4555. }
  4556. /**
  4557. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4558. *
  4559. * @param {Matrix4} m - The 4x4 matrix.
  4560. * @return {Matrix3} A reference to this matrix.
  4561. */
  4562. setFromMatrix4( m ) {
  4563. const me = m.elements;
  4564. this.set(
  4565. me[ 0 ], me[ 4 ], me[ 8 ],
  4566. me[ 1 ], me[ 5 ], me[ 9 ],
  4567. me[ 2 ], me[ 6 ], me[ 10 ]
  4568. );
  4569. return this;
  4570. }
  4571. /**
  4572. * Post-multiplies this matrix by the given 3x3 matrix.
  4573. *
  4574. * @param {Matrix3} m - The matrix to multiply with.
  4575. * @return {Matrix3} A reference to this matrix.
  4576. */
  4577. multiply( m ) {
  4578. return this.multiplyMatrices( this, m );
  4579. }
  4580. /**
  4581. * Pre-multiplies this matrix by the given 3x3 matrix.
  4582. *
  4583. * @param {Matrix3} m - The matrix to multiply with.
  4584. * @return {Matrix3} A reference to this matrix.
  4585. */
  4586. premultiply( m ) {
  4587. return this.multiplyMatrices( m, this );
  4588. }
  4589. /**
  4590. * Multiples the given 3x3 matrices and stores the result
  4591. * in this matrix.
  4592. *
  4593. * @param {Matrix3} a - The first matrix.
  4594. * @param {Matrix3} b - The second matrix.
  4595. * @return {Matrix3} A reference to this matrix.
  4596. */
  4597. multiplyMatrices( a, b ) {
  4598. const ae = a.elements;
  4599. const be = b.elements;
  4600. const te = this.elements;
  4601. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4602. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4603. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4604. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4605. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4606. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4607. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4608. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4609. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4610. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4611. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4612. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4613. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4614. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4615. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4616. return this;
  4617. }
  4618. /**
  4619. * Multiplies every component of the matrix by the given scalar.
  4620. *
  4621. * @param {number} s - The scalar.
  4622. * @return {Matrix3} A reference to this matrix.
  4623. */
  4624. multiplyScalar( s ) {
  4625. const te = this.elements;
  4626. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4627. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4628. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4629. return this;
  4630. }
  4631. /**
  4632. * Computes and returns the determinant of this matrix.
  4633. *
  4634. * @return {number} The determinant.
  4635. */
  4636. determinant() {
  4637. const te = this.elements;
  4638. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4639. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4640. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4641. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4642. }
  4643. /**
  4644. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4645. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4646. * a zero matrix instead.
  4647. *
  4648. * @return {Matrix3} A reference to this matrix.
  4649. */
  4650. invert() {
  4651. const te = this.elements,
  4652. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4653. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4654. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4655. t11 = n33 * n22 - n32 * n23,
  4656. t12 = n32 * n13 - n33 * n12,
  4657. t13 = n23 * n12 - n22 * n13,
  4658. det = n11 * t11 + n21 * t12 + n31 * t13;
  4659. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4660. const detInv = 1 / det;
  4661. te[ 0 ] = t11 * detInv;
  4662. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4663. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4664. te[ 3 ] = t12 * detInv;
  4665. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4666. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4667. te[ 6 ] = t13 * detInv;
  4668. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4669. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4670. return this;
  4671. }
  4672. /**
  4673. * Transposes this matrix in place.
  4674. *
  4675. * @return {Matrix3} A reference to this matrix.
  4676. */
  4677. transpose() {
  4678. let tmp;
  4679. const m = this.elements;
  4680. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4681. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4682. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4683. return this;
  4684. }
  4685. /**
  4686. * Computes the normal matrix which is the inverse transpose of the upper
  4687. * left 3x3 portion of the given 4x4 matrix.
  4688. *
  4689. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4690. * @return {Matrix3} A reference to this matrix.
  4691. */
  4692. getNormalMatrix( matrix4 ) {
  4693. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4694. }
  4695. /**
  4696. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4697. *
  4698. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4699. * @return {Matrix3} A reference to this matrix.
  4700. */
  4701. transposeIntoArray( r ) {
  4702. const m = this.elements;
  4703. r[ 0 ] = m[ 0 ];
  4704. r[ 1 ] = m[ 3 ];
  4705. r[ 2 ] = m[ 6 ];
  4706. r[ 3 ] = m[ 1 ];
  4707. r[ 4 ] = m[ 4 ];
  4708. r[ 5 ] = m[ 7 ];
  4709. r[ 6 ] = m[ 2 ];
  4710. r[ 7 ] = m[ 5 ];
  4711. r[ 8 ] = m[ 8 ];
  4712. return this;
  4713. }
  4714. /**
  4715. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4716. *
  4717. * @param {number} tx - Offset x.
  4718. * @param {number} ty - Offset y.
  4719. * @param {number} sx - Repeat x.
  4720. * @param {number} sy - Repeat y.
  4721. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4722. * @param {number} cx - Center x of rotation.
  4723. * @param {number} cy - Center y of rotation
  4724. * @return {Matrix3} A reference to this matrix.
  4725. */
  4726. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4727. const c = Math.cos( rotation );
  4728. const s = Math.sin( rotation );
  4729. this.set(
  4730. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4731. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4732. 0, 0, 1
  4733. );
  4734. return this;
  4735. }
  4736. /**
  4737. * Scales this matrix with the given scalar values.
  4738. *
  4739. * @param {number} sx - The amount to scale in the X axis.
  4740. * @param {number} sy - The amount to scale in the Y axis.
  4741. * @return {Matrix3} A reference to this matrix.
  4742. */
  4743. scale( sx, sy ) {
  4744. this.premultiply( _m3.makeScale( sx, sy ) );
  4745. return this;
  4746. }
  4747. /**
  4748. * Rotates this matrix by the given angle.
  4749. *
  4750. * @param {number} theta - The rotation in radians.
  4751. * @return {Matrix3} A reference to this matrix.
  4752. */
  4753. rotate( theta ) {
  4754. this.premultiply( _m3.makeRotation( - theta ) );
  4755. return this;
  4756. }
  4757. /**
  4758. * Translates this matrix by the given scalar values.
  4759. *
  4760. * @param {number} tx - The amount to translate in the X axis.
  4761. * @param {number} ty - The amount to translate in the Y axis.
  4762. * @return {Matrix3} A reference to this matrix.
  4763. */
  4764. translate( tx, ty ) {
  4765. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4766. return this;
  4767. }
  4768. // for 2D Transforms
  4769. /**
  4770. * Sets this matrix as a 2D translation transform.
  4771. *
  4772. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4773. * @param {number} y - The amount to translate in the Y axis.
  4774. * @return {Matrix3} A reference to this matrix.
  4775. */
  4776. makeTranslation( x, y ) {
  4777. if ( x.isVector2 ) {
  4778. this.set(
  4779. 1, 0, x.x,
  4780. 0, 1, x.y,
  4781. 0, 0, 1
  4782. );
  4783. } else {
  4784. this.set(
  4785. 1, 0, x,
  4786. 0, 1, y,
  4787. 0, 0, 1
  4788. );
  4789. }
  4790. return this;
  4791. }
  4792. /**
  4793. * Sets this matrix as a 2D rotational transformation.
  4794. *
  4795. * @param {number} theta - The rotation in radians.
  4796. * @return {Matrix3} A reference to this matrix.
  4797. */
  4798. makeRotation( theta ) {
  4799. // counterclockwise
  4800. const c = Math.cos( theta );
  4801. const s = Math.sin( theta );
  4802. this.set(
  4803. c, - s, 0,
  4804. s, c, 0,
  4805. 0, 0, 1
  4806. );
  4807. return this;
  4808. }
  4809. /**
  4810. * Sets this matrix as a 2D scale transform.
  4811. *
  4812. * @param {number} x - The amount to scale in the X axis.
  4813. * @param {number} y - The amount to scale in the Y axis.
  4814. * @return {Matrix3} A reference to this matrix.
  4815. */
  4816. makeScale( x, y ) {
  4817. this.set(
  4818. x, 0, 0,
  4819. 0, y, 0,
  4820. 0, 0, 1
  4821. );
  4822. return this;
  4823. }
  4824. /**
  4825. * Returns `true` if this matrix is equal with the given one.
  4826. *
  4827. * @param {Matrix3} matrix - The matrix to test for equality.
  4828. * @return {boolean} Whether this matrix is equal with the given one.
  4829. */
  4830. equals( matrix ) {
  4831. const te = this.elements;
  4832. const me = matrix.elements;
  4833. for ( let i = 0; i < 9; i ++ ) {
  4834. if ( te[ i ] !== me[ i ] ) return false;
  4835. }
  4836. return true;
  4837. }
  4838. /**
  4839. * Sets the elements of the matrix from the given array.
  4840. *
  4841. * @param {Array<number>} array - The matrix elements in column-major order.
  4842. * @param {number} [offset=0] - Index of the first element in the array.
  4843. * @return {Matrix3} A reference to this matrix.
  4844. */
  4845. fromArray( array, offset = 0 ) {
  4846. for ( let i = 0; i < 9; i ++ ) {
  4847. this.elements[ i ] = array[ i + offset ];
  4848. }
  4849. return this;
  4850. }
  4851. /**
  4852. * Writes the elements of this matrix to the given array. If no array is provided,
  4853. * the method returns a new instance.
  4854. *
  4855. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4856. * @param {number} [offset=0] - Index of the first element in the array.
  4857. * @return {Array<number>} The matrix elements in column-major order.
  4858. */
  4859. toArray( array = [], offset = 0 ) {
  4860. const te = this.elements;
  4861. array[ offset ] = te[ 0 ];
  4862. array[ offset + 1 ] = te[ 1 ];
  4863. array[ offset + 2 ] = te[ 2 ];
  4864. array[ offset + 3 ] = te[ 3 ];
  4865. array[ offset + 4 ] = te[ 4 ];
  4866. array[ offset + 5 ] = te[ 5 ];
  4867. array[ offset + 6 ] = te[ 6 ];
  4868. array[ offset + 7 ] = te[ 7 ];
  4869. array[ offset + 8 ] = te[ 8 ];
  4870. return array;
  4871. }
  4872. /**
  4873. * Returns a matrix with copied values from this instance.
  4874. *
  4875. * @return {Matrix3} A clone of this instance.
  4876. */
  4877. clone() {
  4878. return new this.constructor().fromArray( this.elements );
  4879. }
  4880. }
  4881. const _m3 = /*@__PURE__*/ new Matrix3();
  4882. function arrayNeedsUint32( array ) {
  4883. // assumes larger values usually on last
  4884. for ( let i = array.length - 1; i >= 0; -- i ) {
  4885. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4886. }
  4887. return false;
  4888. }
  4889. const TYPED_ARRAYS = {
  4890. Int8Array: Int8Array,
  4891. Uint8Array: Uint8Array,
  4892. Uint8ClampedArray: Uint8ClampedArray,
  4893. Int16Array: Int16Array,
  4894. Uint16Array: Uint16Array,
  4895. Int32Array: Int32Array,
  4896. Uint32Array: Uint32Array,
  4897. Float32Array: Float32Array,
  4898. Float64Array: Float64Array
  4899. };
  4900. function getTypedArray( type, buffer ) {
  4901. return new TYPED_ARRAYS[ type ]( buffer );
  4902. }
  4903. function createElementNS( name ) {
  4904. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4905. }
  4906. function createCanvasElement() {
  4907. const canvas = createElementNS( 'canvas' );
  4908. canvas.style.display = 'block';
  4909. return canvas;
  4910. }
  4911. const _cache = {};
  4912. function warnOnce( message ) {
  4913. if ( message in _cache ) return;
  4914. _cache[ message ] = true;
  4915. console.warn( message );
  4916. }
  4917. function probeAsync( gl, sync, interval ) {
  4918. return new Promise( function ( resolve, reject ) {
  4919. function probe() {
  4920. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4921. case gl.WAIT_FAILED:
  4922. reject();
  4923. break;
  4924. case gl.TIMEOUT_EXPIRED:
  4925. setTimeout( probe, interval );
  4926. break;
  4927. default:
  4928. resolve();
  4929. }
  4930. }
  4931. setTimeout( probe, interval );
  4932. } );
  4933. }
  4934. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4935. 0.4123908, 0.3575843, 0.1804808,
  4936. 0.2126390, 0.7151687, 0.0721923,
  4937. 0.0193308, 0.1191948, 0.9505322
  4938. );
  4939. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4940. 3.2409699, -1.5373832, -0.4986108,
  4941. -0.9692436, 1.8759675, 0.0415551,
  4942. 0.0556301, -0.203977, 1.0569715
  4943. );
  4944. function createColorManagement() {
  4945. const ColorManagement = {
  4946. enabled: true,
  4947. workingColorSpace: LinearSRGBColorSpace,
  4948. /**
  4949. * Implementations of supported color spaces.
  4950. *
  4951. * Required:
  4952. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4953. * - whitePoint: reference white [ x y ]
  4954. * - transfer: transfer function (pre-defined)
  4955. * - toXYZ: Matrix3 RGB to XYZ transform
  4956. * - fromXYZ: Matrix3 XYZ to RGB transform
  4957. * - luminanceCoefficients: RGB luminance coefficients
  4958. *
  4959. * Optional:
  4960. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  4961. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4962. *
  4963. * Reference:
  4964. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4965. */
  4966. spaces: {},
  4967. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4968. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4969. return color;
  4970. }
  4971. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4972. color.r = SRGBToLinear( color.r );
  4973. color.g = SRGBToLinear( color.g );
  4974. color.b = SRGBToLinear( color.b );
  4975. }
  4976. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4977. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4978. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4979. }
  4980. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  4981. color.r = LinearToSRGB( color.r );
  4982. color.g = LinearToSRGB( color.g );
  4983. color.b = LinearToSRGB( color.b );
  4984. }
  4985. return color;
  4986. },
  4987. workingToColorSpace: function ( color, targetColorSpace ) {
  4988. return this.convert( color, this.workingColorSpace, targetColorSpace );
  4989. },
  4990. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  4991. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  4992. },
  4993. getPrimaries: function ( colorSpace ) {
  4994. return this.spaces[ colorSpace ].primaries;
  4995. },
  4996. getTransfer: function ( colorSpace ) {
  4997. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  4998. return this.spaces[ colorSpace ].transfer;
  4999. },
  5000. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5001. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5002. },
  5003. define: function ( colorSpaces ) {
  5004. Object.assign( this.spaces, colorSpaces );
  5005. },
  5006. // Internal APIs
  5007. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5008. return targetMatrix
  5009. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5010. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5011. },
  5012. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5013. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5014. },
  5015. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5016. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5017. },
  5018. // Deprecated
  5019. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5020. warnOnce( 'THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5021. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5022. },
  5023. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5024. warnOnce( 'THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5025. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5026. },
  5027. };
  5028. /******************************************************************************
  5029. * sRGB definitions
  5030. */
  5031. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5032. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5033. const D65 = [ 0.3127, 0.3290 ];
  5034. ColorManagement.define( {
  5035. [ LinearSRGBColorSpace ]: {
  5036. primaries: REC709_PRIMARIES,
  5037. whitePoint: D65,
  5038. transfer: LinearTransfer,
  5039. toXYZ: LINEAR_REC709_TO_XYZ,
  5040. fromXYZ: XYZ_TO_LINEAR_REC709,
  5041. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5042. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5043. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5044. },
  5045. [ SRGBColorSpace ]: {
  5046. primaries: REC709_PRIMARIES,
  5047. whitePoint: D65,
  5048. transfer: SRGBTransfer,
  5049. toXYZ: LINEAR_REC709_TO_XYZ,
  5050. fromXYZ: XYZ_TO_LINEAR_REC709,
  5051. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5052. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5053. },
  5054. } );
  5055. return ColorManagement;
  5056. }
  5057. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5058. function SRGBToLinear( c ) {
  5059. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5060. }
  5061. function LinearToSRGB( c ) {
  5062. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5063. }
  5064. let _canvas;
  5065. /**
  5066. * A class containing utility functions for images.
  5067. *
  5068. * @hideconstructor
  5069. */
  5070. class ImageUtils {
  5071. /**
  5072. * Returns a data URI containing a representation of the given image.
  5073. *
  5074. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5075. * @param {string} [type='image/png'] - Indicates the image format.
  5076. * @return {string} The data URI.
  5077. */
  5078. static getDataURL( image, type = 'image/png' ) {
  5079. if ( /^data:/i.test( image.src ) ) {
  5080. return image.src;
  5081. }
  5082. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5083. return image.src;
  5084. }
  5085. let canvas;
  5086. if ( image instanceof HTMLCanvasElement ) {
  5087. canvas = image;
  5088. } else {
  5089. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5090. _canvas.width = image.width;
  5091. _canvas.height = image.height;
  5092. const context = _canvas.getContext( '2d' );
  5093. if ( image instanceof ImageData ) {
  5094. context.putImageData( image, 0, 0 );
  5095. } else {
  5096. context.drawImage( image, 0, 0, image.width, image.height );
  5097. }
  5098. canvas = _canvas;
  5099. }
  5100. return canvas.toDataURL( type );
  5101. }
  5102. /**
  5103. * Converts the given sRGB image data to linear color space.
  5104. *
  5105. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5106. * @return {HTMLCanvasElement|Object} The converted image.
  5107. */
  5108. static sRGBToLinear( image ) {
  5109. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5110. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5111. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5112. const canvas = createElementNS( 'canvas' );
  5113. canvas.width = image.width;
  5114. canvas.height = image.height;
  5115. const context = canvas.getContext( '2d' );
  5116. context.drawImage( image, 0, 0, image.width, image.height );
  5117. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5118. const data = imageData.data;
  5119. for ( let i = 0; i < data.length; i ++ ) {
  5120. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5121. }
  5122. context.putImageData( imageData, 0, 0 );
  5123. return canvas;
  5124. } else if ( image.data ) {
  5125. const data = image.data.slice( 0 );
  5126. for ( let i = 0; i < data.length; i ++ ) {
  5127. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5128. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5129. } else {
  5130. // assuming float
  5131. data[ i ] = SRGBToLinear( data[ i ] );
  5132. }
  5133. }
  5134. return {
  5135. data: data,
  5136. width: image.width,
  5137. height: image.height
  5138. };
  5139. } else {
  5140. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5141. return image;
  5142. }
  5143. }
  5144. }
  5145. let _sourceId = 0;
  5146. /**
  5147. * Represents the data source of a texture.
  5148. *
  5149. * The main purpose of this class is to decouple the data definition from the texture
  5150. * definition so the same data can be used with multiple texture instances.
  5151. */
  5152. class Source {
  5153. /**
  5154. * Constructs a new video texture.
  5155. *
  5156. * @param {any} [data=null] - The data definition of a texture.
  5157. */
  5158. constructor( data = null ) {
  5159. /**
  5160. * This flag can be used for type testing.
  5161. *
  5162. * @type {boolean}
  5163. * @readonly
  5164. * @default true
  5165. */
  5166. this.isSource = true;
  5167. /**
  5168. * The ID of the source.
  5169. *
  5170. * @name Source#id
  5171. * @type {number}
  5172. * @readonly
  5173. */
  5174. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5175. /**
  5176. * The UUID of the source.
  5177. *
  5178. * @type {string}
  5179. * @readonly
  5180. */
  5181. this.uuid = generateUUID();
  5182. /**
  5183. * The data definition of a texture.
  5184. *
  5185. * @type {any}
  5186. */
  5187. this.data = data;
  5188. /**
  5189. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5190. * provides more control on how texture data should be processed. When `dataReady` is set
  5191. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5192. * the data into the GPU memory.
  5193. *
  5194. * @type {boolean}
  5195. * @default true
  5196. */
  5197. this.dataReady = true;
  5198. /**
  5199. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5200. *
  5201. * @type {number}
  5202. * @readonly
  5203. * @default 0
  5204. */
  5205. this.version = 0;
  5206. }
  5207. /**
  5208. * Returns the dimensions of the source into the given target vector.
  5209. *
  5210. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5211. * @return {(Vector2|Vector3)} The dimensions of the source.
  5212. */
  5213. getSize( target ) {
  5214. const data = this.data;
  5215. if ( data instanceof HTMLVideoElement ) {
  5216. target.set( data.videoWidth, data.videoHeight, 0 );
  5217. } else if ( data instanceof VideoFrame ) {
  5218. target.set( data.displayHeight, data.displayWidth, 0 );
  5219. } else if ( data !== null ) {
  5220. target.set( data.width, data.height, data.depth || 0 );
  5221. } else {
  5222. target.set( 0, 0, 0 );
  5223. }
  5224. return target;
  5225. }
  5226. /**
  5227. * When the property is set to `true`, the engine allocates the memory
  5228. * for the texture (if necessary) and triggers the actual texture upload
  5229. * to the GPU next time the source is used.
  5230. *
  5231. * @type {boolean}
  5232. * @default false
  5233. * @param {boolean} value
  5234. */
  5235. set needsUpdate( value ) {
  5236. if ( value === true ) this.version ++;
  5237. }
  5238. /**
  5239. * Serializes the source into JSON.
  5240. *
  5241. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5242. * @return {Object} A JSON object representing the serialized source.
  5243. * @see {@link ObjectLoader#parse}
  5244. */
  5245. toJSON( meta ) {
  5246. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5247. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5248. return meta.images[ this.uuid ];
  5249. }
  5250. const output = {
  5251. uuid: this.uuid,
  5252. url: ''
  5253. };
  5254. const data = this.data;
  5255. if ( data !== null ) {
  5256. let url;
  5257. if ( Array.isArray( data ) ) {
  5258. // cube texture
  5259. url = [];
  5260. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5261. if ( data[ i ].isDataTexture ) {
  5262. url.push( serializeImage( data[ i ].image ) );
  5263. } else {
  5264. url.push( serializeImage( data[ i ] ) );
  5265. }
  5266. }
  5267. } else {
  5268. // texture
  5269. url = serializeImage( data );
  5270. }
  5271. output.url = url;
  5272. }
  5273. if ( ! isRootObject ) {
  5274. meta.images[ this.uuid ] = output;
  5275. }
  5276. return output;
  5277. }
  5278. }
  5279. function serializeImage( image ) {
  5280. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5281. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5282. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5283. // default images
  5284. return ImageUtils.getDataURL( image );
  5285. } else {
  5286. if ( image.data ) {
  5287. // images of DataTexture
  5288. return {
  5289. data: Array.from( image.data ),
  5290. width: image.width,
  5291. height: image.height,
  5292. type: image.data.constructor.name
  5293. };
  5294. } else {
  5295. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5296. return {};
  5297. }
  5298. }
  5299. }
  5300. let _textureId = 0;
  5301. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5302. /**
  5303. * Base class for all textures.
  5304. *
  5305. * Note: After the initial use of a texture, its dimensions, format, and type
  5306. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5307. *
  5308. * @augments EventDispatcher
  5309. */
  5310. class Texture extends EventDispatcher {
  5311. /**
  5312. * Constructs a new texture.
  5313. *
  5314. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5315. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5316. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5317. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5318. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5319. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5320. * @param {number} [format=RGBAFormat] - The texture format.
  5321. * @param {number} [type=UnsignedByteType] - The texture type.
  5322. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5323. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5324. */
  5325. 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 ) {
  5326. super();
  5327. /**
  5328. * This flag can be used for type testing.
  5329. *
  5330. * @type {boolean}
  5331. * @readonly
  5332. * @default true
  5333. */
  5334. this.isTexture = true;
  5335. /**
  5336. * The ID of the texture.
  5337. *
  5338. * @name Texture#id
  5339. * @type {number}
  5340. * @readonly
  5341. */
  5342. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5343. /**
  5344. * The UUID of the material.
  5345. *
  5346. * @type {string}
  5347. * @readonly
  5348. */
  5349. this.uuid = generateUUID();
  5350. /**
  5351. * The name of the material.
  5352. *
  5353. * @type {string}
  5354. */
  5355. this.name = '';
  5356. /**
  5357. * The data definition of a texture. A reference to the data source can be
  5358. * shared across textures. This is often useful in context of spritesheets
  5359. * where multiple textures render the same data but with different texture
  5360. * transformations.
  5361. *
  5362. * @type {Source}
  5363. */
  5364. this.source = new Source( image );
  5365. /**
  5366. * An array holding user-defined mipmaps.
  5367. *
  5368. * @type {Array<Object>}
  5369. */
  5370. this.mipmaps = [];
  5371. /**
  5372. * How the texture is applied to the object. The value `UVMapping`
  5373. * is the default, where texture or uv coordinates are used to apply the map.
  5374. *
  5375. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5376. * @default UVMapping
  5377. */
  5378. this.mapping = mapping;
  5379. /**
  5380. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5381. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5382. *
  5383. * @type {number}
  5384. * @default 0
  5385. */
  5386. this.channel = 0;
  5387. /**
  5388. * This defines how the texture is wrapped horizontally and corresponds to
  5389. * *U* in UV mapping.
  5390. *
  5391. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5392. * @default ClampToEdgeWrapping
  5393. */
  5394. this.wrapS = wrapS;
  5395. /**
  5396. * This defines how the texture is wrapped horizontally and corresponds to
  5397. * *V* in UV mapping.
  5398. *
  5399. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5400. * @default ClampToEdgeWrapping
  5401. */
  5402. this.wrapT = wrapT;
  5403. /**
  5404. * How the texture is sampled when a texel covers more than one pixel.
  5405. *
  5406. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5407. * @default LinearFilter
  5408. */
  5409. this.magFilter = magFilter;
  5410. /**
  5411. * How the texture is sampled when a texel covers less than one pixel.
  5412. *
  5413. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5414. * @default LinearMipmapLinearFilter
  5415. */
  5416. this.minFilter = minFilter;
  5417. /**
  5418. * The number of samples taken along the axis through the pixel that has the
  5419. * highest density of texels. By default, this value is `1`. A higher value
  5420. * gives a less blurry result than a basic mipmap, at the cost of more
  5421. * texture samples being used.
  5422. *
  5423. * @type {number}
  5424. * @default 0
  5425. */
  5426. this.anisotropy = anisotropy;
  5427. /**
  5428. * The format of the texture.
  5429. *
  5430. * @type {number}
  5431. * @default RGBAFormat
  5432. */
  5433. this.format = format;
  5434. /**
  5435. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5436. * defines how the texture data is going to be stored on the GPU.
  5437. *
  5438. * This property allows to overwrite the default format.
  5439. *
  5440. * @type {?string}
  5441. * @default null
  5442. */
  5443. this.internalFormat = null;
  5444. /**
  5445. * The data type of the texture.
  5446. *
  5447. * @type {number}
  5448. * @default UnsignedByteType
  5449. */
  5450. this.type = type;
  5451. /**
  5452. * How much a single repetition of the texture is offset from the beginning,
  5453. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5454. *
  5455. * @type {Vector2}
  5456. * @default (0,0)
  5457. */
  5458. this.offset = new Vector2( 0, 0 );
  5459. /**
  5460. * How many times the texture is repeated across the surface, in each
  5461. * direction U and V. If repeat is set greater than `1` in either direction,
  5462. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5463. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5464. *
  5465. * @type {Vector2}
  5466. * @default (1,1)
  5467. */
  5468. this.repeat = new Vector2( 1, 1 );
  5469. /**
  5470. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5471. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5472. *
  5473. * @type {Vector2}
  5474. * @default (0,0)
  5475. */
  5476. this.center = new Vector2( 0, 0 );
  5477. /**
  5478. * How much the texture is rotated around the center point, in radians.
  5479. * Positive values are counter-clockwise.
  5480. *
  5481. * @type {number}
  5482. * @default 0
  5483. */
  5484. this.rotation = 0;
  5485. /**
  5486. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5487. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5488. * {@link Texture#rotation}, and {@link Texture#center}.
  5489. *
  5490. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5491. *
  5492. * @type {boolean}
  5493. * @default true
  5494. */
  5495. this.matrixAutoUpdate = true;
  5496. /**
  5497. * The uv-transformation matrix of the texture.
  5498. *
  5499. * @type {Matrix3}
  5500. */
  5501. this.matrix = new Matrix3();
  5502. /**
  5503. * Whether to generate mipmaps (if possible) for a texture.
  5504. *
  5505. * Set this to `false` if you are creating mipmaps manually.
  5506. *
  5507. * @type {boolean}
  5508. * @default true
  5509. */
  5510. this.generateMipmaps = true;
  5511. /**
  5512. * If set to `true`, the alpha channel, if present, is multiplied into the
  5513. * color channels when the texture is uploaded to the GPU.
  5514. *
  5515. * Note that this property has no effect when using `ImageBitmap`. You need to
  5516. * configure premultiply alpha on bitmap creation instead.
  5517. *
  5518. * @type {boolean}
  5519. * @default false
  5520. */
  5521. this.premultiplyAlpha = false;
  5522. /**
  5523. * If set to `true`, the texture is flipped along the vertical axis when
  5524. * uploaded to the GPU.
  5525. *
  5526. * Note that this property has no effect when using `ImageBitmap`. You need to
  5527. * configure the flip on bitmap creation instead.
  5528. *
  5529. * @type {boolean}
  5530. * @default true
  5531. */
  5532. this.flipY = true;
  5533. /**
  5534. * Specifies the alignment requirements for the start of each pixel row in memory.
  5535. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5536. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5537. *
  5538. * @type {number}
  5539. * @default 4
  5540. */
  5541. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5542. /**
  5543. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5544. *
  5545. * @type {string}
  5546. * @default NoColorSpace
  5547. */
  5548. this.colorSpace = colorSpace;
  5549. /**
  5550. * An object that can be used to store custom data about the texture. It
  5551. * should not hold references to functions as these will not be cloned.
  5552. *
  5553. * @type {Object}
  5554. */
  5555. this.userData = {};
  5556. /**
  5557. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5558. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5559. *
  5560. * @type {Array<Object>}
  5561. */
  5562. this.updateRanges = [];
  5563. /**
  5564. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5565. *
  5566. * @type {number}
  5567. * @readonly
  5568. * @default 0
  5569. */
  5570. this.version = 0;
  5571. /**
  5572. * A callback function, called when the texture is updated (e.g., when
  5573. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5574. *
  5575. * @type {?Function}
  5576. * @default null
  5577. */
  5578. this.onUpdate = null;
  5579. /**
  5580. * An optional back reference to the textures render target.
  5581. *
  5582. * @type {?(RenderTarget|WebGLRenderTarget)}
  5583. * @default null
  5584. */
  5585. this.renderTarget = null;
  5586. /**
  5587. * Indicates whether a texture belongs to a render target or not.
  5588. *
  5589. * @type {boolean}
  5590. * @readonly
  5591. * @default false
  5592. */
  5593. this.isRenderTargetTexture = false;
  5594. /**
  5595. * Indicates if a texture should be handled like a texture array.
  5596. *
  5597. * @type {boolean}
  5598. * @readonly
  5599. * @default false
  5600. */
  5601. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5602. /**
  5603. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5604. * (only relevant for render target textures).
  5605. *
  5606. * @type {number}
  5607. * @readonly
  5608. * @default 0
  5609. */
  5610. this.pmremVersion = 0;
  5611. }
  5612. /**
  5613. * The width of the texture in pixels.
  5614. */
  5615. get width() {
  5616. return this.source.getSize( _tempVec3 ).x;
  5617. }
  5618. /**
  5619. * The height of the texture in pixels.
  5620. */
  5621. get height() {
  5622. return this.source.getSize( _tempVec3 ).y;
  5623. }
  5624. /**
  5625. * The depth of the texture in pixels.
  5626. */
  5627. get depth() {
  5628. return this.source.getSize( _tempVec3 ).z;
  5629. }
  5630. /**
  5631. * The image object holding the texture data.
  5632. *
  5633. * @type {?Object}
  5634. */
  5635. get image() {
  5636. return this.source.data;
  5637. }
  5638. set image( value = null ) {
  5639. this.source.data = value;
  5640. }
  5641. /**
  5642. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5643. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5644. */
  5645. updateMatrix() {
  5646. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5647. }
  5648. /**
  5649. * Adds a range of data in the data texture to be updated on the GPU.
  5650. *
  5651. * @param {number} start - Position at which to start update.
  5652. * @param {number} count - The number of components to update.
  5653. */
  5654. addUpdateRange( start, count ) {
  5655. this.updateRanges.push( { start, count } );
  5656. }
  5657. /**
  5658. * Clears the update ranges.
  5659. */
  5660. clearUpdateRanges() {
  5661. this.updateRanges.length = 0;
  5662. }
  5663. /**
  5664. * Returns a new texture with copied values from this instance.
  5665. *
  5666. * @return {Texture} A clone of this instance.
  5667. */
  5668. clone() {
  5669. return new this.constructor().copy( this );
  5670. }
  5671. /**
  5672. * Copies the values of the given texture to this instance.
  5673. *
  5674. * @param {Texture} source - The texture to copy.
  5675. * @return {Texture} A reference to this instance.
  5676. */
  5677. copy( source ) {
  5678. this.name = source.name;
  5679. this.source = source.source;
  5680. this.mipmaps = source.mipmaps.slice( 0 );
  5681. this.mapping = source.mapping;
  5682. this.channel = source.channel;
  5683. this.wrapS = source.wrapS;
  5684. this.wrapT = source.wrapT;
  5685. this.magFilter = source.magFilter;
  5686. this.minFilter = source.minFilter;
  5687. this.anisotropy = source.anisotropy;
  5688. this.format = source.format;
  5689. this.internalFormat = source.internalFormat;
  5690. this.type = source.type;
  5691. this.offset.copy( source.offset );
  5692. this.repeat.copy( source.repeat );
  5693. this.center.copy( source.center );
  5694. this.rotation = source.rotation;
  5695. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5696. this.matrix.copy( source.matrix );
  5697. this.generateMipmaps = source.generateMipmaps;
  5698. this.premultiplyAlpha = source.premultiplyAlpha;
  5699. this.flipY = source.flipY;
  5700. this.unpackAlignment = source.unpackAlignment;
  5701. this.colorSpace = source.colorSpace;
  5702. this.renderTarget = source.renderTarget;
  5703. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5704. this.isArrayTexture = source.isArrayTexture;
  5705. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5706. this.needsUpdate = true;
  5707. return this;
  5708. }
  5709. /**
  5710. * Sets this texture's properties based on `values`.
  5711. * @param {Object} values - A container with texture parameters.
  5712. */
  5713. setValues( values ) {
  5714. for ( const key in values ) {
  5715. const newValue = values[ key ];
  5716. if ( newValue === undefined ) {
  5717. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5718. continue;
  5719. }
  5720. const currentValue = this[ key ];
  5721. if ( currentValue === undefined ) {
  5722. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5723. continue;
  5724. }
  5725. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5726. currentValue.copy( newValue );
  5727. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5728. currentValue.copy( newValue );
  5729. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5730. currentValue.copy( newValue );
  5731. } else {
  5732. this[ key ] = newValue;
  5733. }
  5734. }
  5735. }
  5736. /**
  5737. * Serializes the texture into JSON.
  5738. *
  5739. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5740. * @return {Object} A JSON object representing the serialized texture.
  5741. * @see {@link ObjectLoader#parse}
  5742. */
  5743. toJSON( meta ) {
  5744. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5745. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5746. return meta.textures[ this.uuid ];
  5747. }
  5748. const output = {
  5749. metadata: {
  5750. version: 4.7,
  5751. type: 'Texture',
  5752. generator: 'Texture.toJSON'
  5753. },
  5754. uuid: this.uuid,
  5755. name: this.name,
  5756. image: this.source.toJSON( meta ).uuid,
  5757. mapping: this.mapping,
  5758. channel: this.channel,
  5759. repeat: [ this.repeat.x, this.repeat.y ],
  5760. offset: [ this.offset.x, this.offset.y ],
  5761. center: [ this.center.x, this.center.y ],
  5762. rotation: this.rotation,
  5763. wrap: [ this.wrapS, this.wrapT ],
  5764. format: this.format,
  5765. internalFormat: this.internalFormat,
  5766. type: this.type,
  5767. colorSpace: this.colorSpace,
  5768. minFilter: this.minFilter,
  5769. magFilter: this.magFilter,
  5770. anisotropy: this.anisotropy,
  5771. flipY: this.flipY,
  5772. generateMipmaps: this.generateMipmaps,
  5773. premultiplyAlpha: this.premultiplyAlpha,
  5774. unpackAlignment: this.unpackAlignment
  5775. };
  5776. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5777. if ( ! isRootObject ) {
  5778. meta.textures[ this.uuid ] = output;
  5779. }
  5780. return output;
  5781. }
  5782. /**
  5783. * Frees the GPU-related resources allocated by this instance. Call this
  5784. * method whenever this instance is no longer used in your app.
  5785. *
  5786. * @fires Texture#dispose
  5787. */
  5788. dispose() {
  5789. /**
  5790. * Fires when the texture has been disposed of.
  5791. *
  5792. * @event Texture#dispose
  5793. * @type {Object}
  5794. */
  5795. this.dispatchEvent( { type: 'dispose' } );
  5796. }
  5797. /**
  5798. * Transforms the given uv vector with the textures uv transformation matrix.
  5799. *
  5800. * @param {Vector2} uv - The uv vector.
  5801. * @return {Vector2} The transformed uv vector.
  5802. */
  5803. transformUv( uv ) {
  5804. if ( this.mapping !== UVMapping ) return uv;
  5805. uv.applyMatrix3( this.matrix );
  5806. if ( uv.x < 0 || uv.x > 1 ) {
  5807. switch ( this.wrapS ) {
  5808. case RepeatWrapping:
  5809. uv.x = uv.x - Math.floor( uv.x );
  5810. break;
  5811. case ClampToEdgeWrapping:
  5812. uv.x = uv.x < 0 ? 0 : 1;
  5813. break;
  5814. case MirroredRepeatWrapping:
  5815. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5816. uv.x = Math.ceil( uv.x ) - uv.x;
  5817. } else {
  5818. uv.x = uv.x - Math.floor( uv.x );
  5819. }
  5820. break;
  5821. }
  5822. }
  5823. if ( uv.y < 0 || uv.y > 1 ) {
  5824. switch ( this.wrapT ) {
  5825. case RepeatWrapping:
  5826. uv.y = uv.y - Math.floor( uv.y );
  5827. break;
  5828. case ClampToEdgeWrapping:
  5829. uv.y = uv.y < 0 ? 0 : 1;
  5830. break;
  5831. case MirroredRepeatWrapping:
  5832. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5833. uv.y = Math.ceil( uv.y ) - uv.y;
  5834. } else {
  5835. uv.y = uv.y - Math.floor( uv.y );
  5836. }
  5837. break;
  5838. }
  5839. }
  5840. if ( this.flipY ) {
  5841. uv.y = 1 - uv.y;
  5842. }
  5843. return uv;
  5844. }
  5845. /**
  5846. * Setting this property to `true` indicates the engine the texture
  5847. * must be updated in the next render. This triggers a texture upload
  5848. * to the GPU and ensures correct texture parameter configuration.
  5849. *
  5850. * @type {boolean}
  5851. * @default false
  5852. * @param {boolean} value
  5853. */
  5854. set needsUpdate( value ) {
  5855. if ( value === true ) {
  5856. this.version ++;
  5857. this.source.needsUpdate = true;
  5858. }
  5859. }
  5860. /**
  5861. * Setting this property to `true` indicates the engine the PMREM
  5862. * must be regenerated.
  5863. *
  5864. * @type {boolean}
  5865. * @default false
  5866. * @param {boolean} value
  5867. */
  5868. set needsPMREMUpdate( value ) {
  5869. if ( value === true ) {
  5870. this.pmremVersion ++;
  5871. }
  5872. }
  5873. }
  5874. /**
  5875. * The default image for all textures.
  5876. *
  5877. * @static
  5878. * @type {?Image}
  5879. * @default null
  5880. */
  5881. Texture.DEFAULT_IMAGE = null;
  5882. /**
  5883. * The default mapping for all textures.
  5884. *
  5885. * @static
  5886. * @type {number}
  5887. * @default UVMapping
  5888. */
  5889. Texture.DEFAULT_MAPPING = UVMapping;
  5890. /**
  5891. * The default anisotropy value for all textures.
  5892. *
  5893. * @static
  5894. * @type {number}
  5895. * @default 1
  5896. */
  5897. Texture.DEFAULT_ANISOTROPY = 1;
  5898. /**
  5899. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5900. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5901. *
  5902. * - A point in 4D space.
  5903. * - A direction and length in 4D space. In three.js the length will
  5904. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5905. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5906. * - Any arbitrary ordered quadruplet of numbers.
  5907. *
  5908. * There are other things a 4D vector can be used to represent, however these
  5909. * are the most common uses in *three.js*.
  5910. *
  5911. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5912. * the corresponding order.
  5913. * ```js
  5914. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5915. *
  5916. * //no arguments; will be initialised to (0, 0, 0, 1)
  5917. * const b = new THREE.Vector4( );
  5918. *
  5919. * const d = a.dot( b );
  5920. * ```
  5921. */
  5922. class Vector4 {
  5923. /**
  5924. * Constructs a new 4D vector.
  5925. *
  5926. * @param {number} [x=0] - The x value of this vector.
  5927. * @param {number} [y=0] - The y value of this vector.
  5928. * @param {number} [z=0] - The z value of this vector.
  5929. * @param {number} [w=1] - The w value of this vector.
  5930. */
  5931. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5932. /**
  5933. * This flag can be used for type testing.
  5934. *
  5935. * @type {boolean}
  5936. * @readonly
  5937. * @default true
  5938. */
  5939. Vector4.prototype.isVector4 = true;
  5940. /**
  5941. * The x value of this vector.
  5942. *
  5943. * @type {number}
  5944. */
  5945. this.x = x;
  5946. /**
  5947. * The y value of this vector.
  5948. *
  5949. * @type {number}
  5950. */
  5951. this.y = y;
  5952. /**
  5953. * The z value of this vector.
  5954. *
  5955. * @type {number}
  5956. */
  5957. this.z = z;
  5958. /**
  5959. * The w value of this vector.
  5960. *
  5961. * @type {number}
  5962. */
  5963. this.w = w;
  5964. }
  5965. /**
  5966. * Alias for {@link Vector4#z}.
  5967. *
  5968. * @type {number}
  5969. */
  5970. get width() {
  5971. return this.z;
  5972. }
  5973. set width( value ) {
  5974. this.z = value;
  5975. }
  5976. /**
  5977. * Alias for {@link Vector4#w}.
  5978. *
  5979. * @type {number}
  5980. */
  5981. get height() {
  5982. return this.w;
  5983. }
  5984. set height( value ) {
  5985. this.w = value;
  5986. }
  5987. /**
  5988. * Sets the vector components.
  5989. *
  5990. * @param {number} x - The value of the x component.
  5991. * @param {number} y - The value of the y component.
  5992. * @param {number} z - The value of the z component.
  5993. * @param {number} w - The value of the w component.
  5994. * @return {Vector4} A reference to this vector.
  5995. */
  5996. set( x, y, z, w ) {
  5997. this.x = x;
  5998. this.y = y;
  5999. this.z = z;
  6000. this.w = w;
  6001. return this;
  6002. }
  6003. /**
  6004. * Sets the vector components to the same value.
  6005. *
  6006. * @param {number} scalar - The value to set for all vector components.
  6007. * @return {Vector4} A reference to this vector.
  6008. */
  6009. setScalar( scalar ) {
  6010. this.x = scalar;
  6011. this.y = scalar;
  6012. this.z = scalar;
  6013. this.w = scalar;
  6014. return this;
  6015. }
  6016. /**
  6017. * Sets the vector's x component to the given value
  6018. *
  6019. * @param {number} x - The value to set.
  6020. * @return {Vector4} A reference to this vector.
  6021. */
  6022. setX( x ) {
  6023. this.x = x;
  6024. return this;
  6025. }
  6026. /**
  6027. * Sets the vector's y component to the given value
  6028. *
  6029. * @param {number} y - The value to set.
  6030. * @return {Vector4} A reference to this vector.
  6031. */
  6032. setY( y ) {
  6033. this.y = y;
  6034. return this;
  6035. }
  6036. /**
  6037. * Sets the vector's z component to the given value
  6038. *
  6039. * @param {number} z - The value to set.
  6040. * @return {Vector4} A reference to this vector.
  6041. */
  6042. setZ( z ) {
  6043. this.z = z;
  6044. return this;
  6045. }
  6046. /**
  6047. * Sets the vector's w component to the given value
  6048. *
  6049. * @param {number} w - The value to set.
  6050. * @return {Vector4} A reference to this vector.
  6051. */
  6052. setW( w ) {
  6053. this.w = w;
  6054. return this;
  6055. }
  6056. /**
  6057. * Allows to set a vector component with an index.
  6058. *
  6059. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6060. * `2` equals to z, `3` equals to w.
  6061. * @param {number} value - The value to set.
  6062. * @return {Vector4} A reference to this vector.
  6063. */
  6064. setComponent( index, value ) {
  6065. switch ( index ) {
  6066. case 0: this.x = value; break;
  6067. case 1: this.y = value; break;
  6068. case 2: this.z = value; break;
  6069. case 3: this.w = value; break;
  6070. default: throw new Error( 'index is out of range: ' + index );
  6071. }
  6072. return this;
  6073. }
  6074. /**
  6075. * Returns the value of the vector component which matches the given index.
  6076. *
  6077. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6078. * `2` equals to z, `3` equals to w.
  6079. * @return {number} A vector component value.
  6080. */
  6081. getComponent( index ) {
  6082. switch ( index ) {
  6083. case 0: return this.x;
  6084. case 1: return this.y;
  6085. case 2: return this.z;
  6086. case 3: return this.w;
  6087. default: throw new Error( 'index is out of range: ' + index );
  6088. }
  6089. }
  6090. /**
  6091. * Returns a new vector with copied values from this instance.
  6092. *
  6093. * @return {Vector4} A clone of this instance.
  6094. */
  6095. clone() {
  6096. return new this.constructor( this.x, this.y, this.z, this.w );
  6097. }
  6098. /**
  6099. * Copies the values of the given vector to this instance.
  6100. *
  6101. * @param {Vector3|Vector4} v - The vector to copy.
  6102. * @return {Vector4} A reference to this vector.
  6103. */
  6104. copy( v ) {
  6105. this.x = v.x;
  6106. this.y = v.y;
  6107. this.z = v.z;
  6108. this.w = ( v.w !== undefined ) ? v.w : 1;
  6109. return this;
  6110. }
  6111. /**
  6112. * Adds the given vector to this instance.
  6113. *
  6114. * @param {Vector4} v - The vector to add.
  6115. * @return {Vector4} A reference to this vector.
  6116. */
  6117. add( v ) {
  6118. this.x += v.x;
  6119. this.y += v.y;
  6120. this.z += v.z;
  6121. this.w += v.w;
  6122. return this;
  6123. }
  6124. /**
  6125. * Adds the given scalar value to all components of this instance.
  6126. *
  6127. * @param {number} s - The scalar to add.
  6128. * @return {Vector4} A reference to this vector.
  6129. */
  6130. addScalar( s ) {
  6131. this.x += s;
  6132. this.y += s;
  6133. this.z += s;
  6134. this.w += s;
  6135. return this;
  6136. }
  6137. /**
  6138. * Adds the given vectors and stores the result in this instance.
  6139. *
  6140. * @param {Vector4} a - The first vector.
  6141. * @param {Vector4} b - The second vector.
  6142. * @return {Vector4} A reference to this vector.
  6143. */
  6144. addVectors( a, b ) {
  6145. this.x = a.x + b.x;
  6146. this.y = a.y + b.y;
  6147. this.z = a.z + b.z;
  6148. this.w = a.w + b.w;
  6149. return this;
  6150. }
  6151. /**
  6152. * Adds the given vector scaled by the given factor to this instance.
  6153. *
  6154. * @param {Vector4} v - The vector.
  6155. * @param {number} s - The factor that scales `v`.
  6156. * @return {Vector4} A reference to this vector.
  6157. */
  6158. addScaledVector( v, s ) {
  6159. this.x += v.x * s;
  6160. this.y += v.y * s;
  6161. this.z += v.z * s;
  6162. this.w += v.w * s;
  6163. return this;
  6164. }
  6165. /**
  6166. * Subtracts the given vector from this instance.
  6167. *
  6168. * @param {Vector4} v - The vector to subtract.
  6169. * @return {Vector4} A reference to this vector.
  6170. */
  6171. sub( v ) {
  6172. this.x -= v.x;
  6173. this.y -= v.y;
  6174. this.z -= v.z;
  6175. this.w -= v.w;
  6176. return this;
  6177. }
  6178. /**
  6179. * Subtracts the given scalar value from all components of this instance.
  6180. *
  6181. * @param {number} s - The scalar to subtract.
  6182. * @return {Vector4} A reference to this vector.
  6183. */
  6184. subScalar( s ) {
  6185. this.x -= s;
  6186. this.y -= s;
  6187. this.z -= s;
  6188. this.w -= s;
  6189. return this;
  6190. }
  6191. /**
  6192. * Subtracts the given vectors and stores the result in this instance.
  6193. *
  6194. * @param {Vector4} a - The first vector.
  6195. * @param {Vector4} b - The second vector.
  6196. * @return {Vector4} A reference to this vector.
  6197. */
  6198. subVectors( a, b ) {
  6199. this.x = a.x - b.x;
  6200. this.y = a.y - b.y;
  6201. this.z = a.z - b.z;
  6202. this.w = a.w - b.w;
  6203. return this;
  6204. }
  6205. /**
  6206. * Multiplies the given vector with this instance.
  6207. *
  6208. * @param {Vector4} v - The vector to multiply.
  6209. * @return {Vector4} A reference to this vector.
  6210. */
  6211. multiply( v ) {
  6212. this.x *= v.x;
  6213. this.y *= v.y;
  6214. this.z *= v.z;
  6215. this.w *= v.w;
  6216. return this;
  6217. }
  6218. /**
  6219. * Multiplies the given scalar value with all components of this instance.
  6220. *
  6221. * @param {number} scalar - The scalar to multiply.
  6222. * @return {Vector4} A reference to this vector.
  6223. */
  6224. multiplyScalar( scalar ) {
  6225. this.x *= scalar;
  6226. this.y *= scalar;
  6227. this.z *= scalar;
  6228. this.w *= scalar;
  6229. return this;
  6230. }
  6231. /**
  6232. * Multiplies this vector with the given 4x4 matrix.
  6233. *
  6234. * @param {Matrix4} m - The 4x4 matrix.
  6235. * @return {Vector4} A reference to this vector.
  6236. */
  6237. applyMatrix4( m ) {
  6238. const x = this.x, y = this.y, z = this.z, w = this.w;
  6239. const e = m.elements;
  6240. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6241. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6242. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6243. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6244. return this;
  6245. }
  6246. /**
  6247. * Divides this instance by the given vector.
  6248. *
  6249. * @param {Vector4} v - The vector to divide.
  6250. * @return {Vector4} A reference to this vector.
  6251. */
  6252. divide( v ) {
  6253. this.x /= v.x;
  6254. this.y /= v.y;
  6255. this.z /= v.z;
  6256. this.w /= v.w;
  6257. return this;
  6258. }
  6259. /**
  6260. * Divides this vector by the given scalar.
  6261. *
  6262. * @param {number} scalar - The scalar to divide.
  6263. * @return {Vector4} A reference to this vector.
  6264. */
  6265. divideScalar( scalar ) {
  6266. return this.multiplyScalar( 1 / scalar );
  6267. }
  6268. /**
  6269. * Sets the x, y and z components of this
  6270. * vector to the quaternion's axis and w to the angle.
  6271. *
  6272. * @param {Quaternion} q - The Quaternion to set.
  6273. * @return {Vector4} A reference to this vector.
  6274. */
  6275. setAxisAngleFromQuaternion( q ) {
  6276. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6277. // q is assumed to be normalized
  6278. this.w = 2 * Math.acos( q.w );
  6279. const s = Math.sqrt( 1 - q.w * q.w );
  6280. if ( s < 0.0001 ) {
  6281. this.x = 1;
  6282. this.y = 0;
  6283. this.z = 0;
  6284. } else {
  6285. this.x = q.x / s;
  6286. this.y = q.y / s;
  6287. this.z = q.z / s;
  6288. }
  6289. return this;
  6290. }
  6291. /**
  6292. * Sets the x, y and z components of this
  6293. * vector to the axis of rotation and w to the angle.
  6294. *
  6295. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6296. * @return {Vector4} A reference to this vector.
  6297. */
  6298. setAxisAngleFromRotationMatrix( m ) {
  6299. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6300. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6301. let angle, x, y, z; // variables for result
  6302. const epsilon = 0.01, // margin to allow for rounding errors
  6303. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6304. te = m.elements,
  6305. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6306. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6307. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6308. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6309. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6310. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6311. // singularity found
  6312. // first check for identity matrix which must have +1 for all terms
  6313. // in leading diagonal and zero in other terms
  6314. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6315. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6316. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6317. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6318. // this singularity is identity matrix so angle = 0
  6319. this.set( 1, 0, 0, 0 );
  6320. return this; // zero angle, arbitrary axis
  6321. }
  6322. // otherwise this singularity is angle = 180
  6323. angle = Math.PI;
  6324. const xx = ( m11 + 1 ) / 2;
  6325. const yy = ( m22 + 1 ) / 2;
  6326. const zz = ( m33 + 1 ) / 2;
  6327. const xy = ( m12 + m21 ) / 4;
  6328. const xz = ( m13 + m31 ) / 4;
  6329. const yz = ( m23 + m32 ) / 4;
  6330. if ( ( xx > yy ) && ( xx > zz ) ) {
  6331. // m11 is the largest diagonal term
  6332. if ( xx < epsilon ) {
  6333. x = 0;
  6334. y = 0.707106781;
  6335. z = 0.707106781;
  6336. } else {
  6337. x = Math.sqrt( xx );
  6338. y = xy / x;
  6339. z = xz / x;
  6340. }
  6341. } else if ( yy > zz ) {
  6342. // m22 is the largest diagonal term
  6343. if ( yy < epsilon ) {
  6344. x = 0.707106781;
  6345. y = 0;
  6346. z = 0.707106781;
  6347. } else {
  6348. y = Math.sqrt( yy );
  6349. x = xy / y;
  6350. z = yz / y;
  6351. }
  6352. } else {
  6353. // m33 is the largest diagonal term so base result on this
  6354. if ( zz < epsilon ) {
  6355. x = 0.707106781;
  6356. y = 0.707106781;
  6357. z = 0;
  6358. } else {
  6359. z = Math.sqrt( zz );
  6360. x = xz / z;
  6361. y = yz / z;
  6362. }
  6363. }
  6364. this.set( x, y, z, angle );
  6365. return this; // return 180 deg rotation
  6366. }
  6367. // as we have reached here there are no singularities so we can handle normally
  6368. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6369. ( m13 - m31 ) * ( m13 - m31 ) +
  6370. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6371. if ( Math.abs( s ) < 0.001 ) s = 1;
  6372. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6373. // caught by singularity test above, but I've left it in just in case
  6374. this.x = ( m32 - m23 ) / s;
  6375. this.y = ( m13 - m31 ) / s;
  6376. this.z = ( m21 - m12 ) / s;
  6377. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6378. return this;
  6379. }
  6380. /**
  6381. * Sets the vector components to the position elements of the
  6382. * given transformation matrix.
  6383. *
  6384. * @param {Matrix4} m - The 4x4 matrix.
  6385. * @return {Vector4} A reference to this vector.
  6386. */
  6387. setFromMatrixPosition( m ) {
  6388. const e = m.elements;
  6389. this.x = e[ 12 ];
  6390. this.y = e[ 13 ];
  6391. this.z = e[ 14 ];
  6392. this.w = e[ 15 ];
  6393. return this;
  6394. }
  6395. /**
  6396. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6397. * value, replace that value with the corresponding min value.
  6398. *
  6399. * @param {Vector4} v - The vector.
  6400. * @return {Vector4} A reference to this vector.
  6401. */
  6402. min( v ) {
  6403. this.x = Math.min( this.x, v.x );
  6404. this.y = Math.min( this.y, v.y );
  6405. this.z = Math.min( this.z, v.z );
  6406. this.w = Math.min( this.w, v.w );
  6407. return this;
  6408. }
  6409. /**
  6410. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6411. * value, replace that value with the corresponding max value.
  6412. *
  6413. * @param {Vector4} v - The vector.
  6414. * @return {Vector4} A reference to this vector.
  6415. */
  6416. max( v ) {
  6417. this.x = Math.max( this.x, v.x );
  6418. this.y = Math.max( this.y, v.y );
  6419. this.z = Math.max( this.z, v.z );
  6420. this.w = Math.max( this.w, v.w );
  6421. return this;
  6422. }
  6423. /**
  6424. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6425. * value, it is replaced by the corresponding value.
  6426. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6427. * it is replaced by the corresponding value.
  6428. *
  6429. * @param {Vector4} min - The minimum x, y and z values.
  6430. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6431. * @return {Vector4} A reference to this vector.
  6432. */
  6433. clamp( min, max ) {
  6434. // assumes min < max, componentwise
  6435. this.x = clamp( this.x, min.x, max.x );
  6436. this.y = clamp( this.y, min.y, max.y );
  6437. this.z = clamp( this.z, min.z, max.z );
  6438. this.w = clamp( this.w, min.w, max.w );
  6439. return this;
  6440. }
  6441. /**
  6442. * If this vector's x, y, z or w values are greater than the max value, they are
  6443. * replaced by the max value.
  6444. * If this vector's x, y, z or w values are less than the min value, they are
  6445. * replaced by the min value.
  6446. *
  6447. * @param {number} minVal - The minimum value the components will be clamped to.
  6448. * @param {number} maxVal - The maximum value the components will be clamped to.
  6449. * @return {Vector4} A reference to this vector.
  6450. */
  6451. clampScalar( minVal, maxVal ) {
  6452. this.x = clamp( this.x, minVal, maxVal );
  6453. this.y = clamp( this.y, minVal, maxVal );
  6454. this.z = clamp( this.z, minVal, maxVal );
  6455. this.w = clamp( this.w, minVal, maxVal );
  6456. return this;
  6457. }
  6458. /**
  6459. * If this vector's length is greater than the max value, it is replaced by
  6460. * the max value.
  6461. * If this vector's length is less than the min value, it is replaced by the
  6462. * min value.
  6463. *
  6464. * @param {number} min - The minimum value the vector length will be clamped to.
  6465. * @param {number} max - The maximum value the vector length will be clamped to.
  6466. * @return {Vector4} A reference to this vector.
  6467. */
  6468. clampLength( min, max ) {
  6469. const length = this.length();
  6470. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6471. }
  6472. /**
  6473. * The components of this vector are rounded down to the nearest integer value.
  6474. *
  6475. * @return {Vector4} A reference to this vector.
  6476. */
  6477. floor() {
  6478. this.x = Math.floor( this.x );
  6479. this.y = Math.floor( this.y );
  6480. this.z = Math.floor( this.z );
  6481. this.w = Math.floor( this.w );
  6482. return this;
  6483. }
  6484. /**
  6485. * The components of this vector are rounded up to the nearest integer value.
  6486. *
  6487. * @return {Vector4} A reference to this vector.
  6488. */
  6489. ceil() {
  6490. this.x = Math.ceil( this.x );
  6491. this.y = Math.ceil( this.y );
  6492. this.z = Math.ceil( this.z );
  6493. this.w = Math.ceil( this.w );
  6494. return this;
  6495. }
  6496. /**
  6497. * The components of this vector are rounded to the nearest integer value
  6498. *
  6499. * @return {Vector4} A reference to this vector.
  6500. */
  6501. round() {
  6502. this.x = Math.round( this.x );
  6503. this.y = Math.round( this.y );
  6504. this.z = Math.round( this.z );
  6505. this.w = Math.round( this.w );
  6506. return this;
  6507. }
  6508. /**
  6509. * The components of this vector are rounded towards zero (up if negative,
  6510. * down if positive) to an integer value.
  6511. *
  6512. * @return {Vector4} A reference to this vector.
  6513. */
  6514. roundToZero() {
  6515. this.x = Math.trunc( this.x );
  6516. this.y = Math.trunc( this.y );
  6517. this.z = Math.trunc( this.z );
  6518. this.w = Math.trunc( this.w );
  6519. return this;
  6520. }
  6521. /**
  6522. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6523. *
  6524. * @return {Vector4} A reference to this vector.
  6525. */
  6526. negate() {
  6527. this.x = - this.x;
  6528. this.y = - this.y;
  6529. this.z = - this.z;
  6530. this.w = - this.w;
  6531. return this;
  6532. }
  6533. /**
  6534. * Calculates the dot product of the given vector with this instance.
  6535. *
  6536. * @param {Vector4} v - The vector to compute the dot product with.
  6537. * @return {number} The result of the dot product.
  6538. */
  6539. dot( v ) {
  6540. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6541. }
  6542. /**
  6543. * Computes the square of the Euclidean length (straight-line length) from
  6544. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6545. * compare the length squared instead as it is slightly more efficient to calculate.
  6546. *
  6547. * @return {number} The square length of this vector.
  6548. */
  6549. lengthSq() {
  6550. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6551. }
  6552. /**
  6553. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6554. *
  6555. * @return {number} The length of this vector.
  6556. */
  6557. length() {
  6558. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6559. }
  6560. /**
  6561. * Computes the Manhattan length of this vector.
  6562. *
  6563. * @return {number} The length of this vector.
  6564. */
  6565. manhattanLength() {
  6566. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6567. }
  6568. /**
  6569. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6570. * with the same direction as this one, but with a vector length of `1`.
  6571. *
  6572. * @return {Vector4} A reference to this vector.
  6573. */
  6574. normalize() {
  6575. return this.divideScalar( this.length() || 1 );
  6576. }
  6577. /**
  6578. * Sets this vector to a vector with the same direction as this one, but
  6579. * with the specified length.
  6580. *
  6581. * @param {number} length - The new length of this vector.
  6582. * @return {Vector4} A reference to this vector.
  6583. */
  6584. setLength( length ) {
  6585. return this.normalize().multiplyScalar( length );
  6586. }
  6587. /**
  6588. * Linearly interpolates between the given vector and this instance, where
  6589. * alpha is the percent distance along the line - alpha = 0 will be this
  6590. * vector, and alpha = 1 will be the given one.
  6591. *
  6592. * @param {Vector4} v - The vector to interpolate towards.
  6593. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6594. * @return {Vector4} A reference to this vector.
  6595. */
  6596. lerp( v, alpha ) {
  6597. this.x += ( v.x - this.x ) * alpha;
  6598. this.y += ( v.y - this.y ) * alpha;
  6599. this.z += ( v.z - this.z ) * alpha;
  6600. this.w += ( v.w - this.w ) * alpha;
  6601. return this;
  6602. }
  6603. /**
  6604. * Linearly interpolates between the given vectors, where alpha is the percent
  6605. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6606. * be the second one. The result is stored in this instance.
  6607. *
  6608. * @param {Vector4} v1 - The first vector.
  6609. * @param {Vector4} v2 - The second vector.
  6610. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6611. * @return {Vector4} A reference to this vector.
  6612. */
  6613. lerpVectors( v1, v2, alpha ) {
  6614. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6615. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6616. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6617. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6618. return this;
  6619. }
  6620. /**
  6621. * Returns `true` if this vector is equal with the given one.
  6622. *
  6623. * @param {Vector4} v - The vector to test for equality.
  6624. * @return {boolean} Whether this vector is equal with the given one.
  6625. */
  6626. equals( v ) {
  6627. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6628. }
  6629. /**
  6630. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6631. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6632. *
  6633. * @param {Array<number>} array - An array holding the vector component values.
  6634. * @param {number} [offset=0] - The offset into the array.
  6635. * @return {Vector4} A reference to this vector.
  6636. */
  6637. fromArray( array, offset = 0 ) {
  6638. this.x = array[ offset ];
  6639. this.y = array[ offset + 1 ];
  6640. this.z = array[ offset + 2 ];
  6641. this.w = array[ offset + 3 ];
  6642. return this;
  6643. }
  6644. /**
  6645. * Writes the components of this vector to the given array. If no array is provided,
  6646. * the method returns a new instance.
  6647. *
  6648. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6649. * @param {number} [offset=0] - Index of the first element in the array.
  6650. * @return {Array<number>} The vector components.
  6651. */
  6652. toArray( array = [], offset = 0 ) {
  6653. array[ offset ] = this.x;
  6654. array[ offset + 1 ] = this.y;
  6655. array[ offset + 2 ] = this.z;
  6656. array[ offset + 3 ] = this.w;
  6657. return array;
  6658. }
  6659. /**
  6660. * Sets the components of this vector from the given buffer attribute.
  6661. *
  6662. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6663. * @param {number} index - The index into the attribute.
  6664. * @return {Vector4} A reference to this vector.
  6665. */
  6666. fromBufferAttribute( attribute, index ) {
  6667. this.x = attribute.getX( index );
  6668. this.y = attribute.getY( index );
  6669. this.z = attribute.getZ( index );
  6670. this.w = attribute.getW( index );
  6671. return this;
  6672. }
  6673. /**
  6674. * Sets each component of this vector to a pseudo-random value between `0` and
  6675. * `1`, excluding `1`.
  6676. *
  6677. * @return {Vector4} A reference to this vector.
  6678. */
  6679. random() {
  6680. this.x = Math.random();
  6681. this.y = Math.random();
  6682. this.z = Math.random();
  6683. this.w = Math.random();
  6684. return this;
  6685. }
  6686. *[ Symbol.iterator ]() {
  6687. yield this.x;
  6688. yield this.y;
  6689. yield this.z;
  6690. yield this.w;
  6691. }
  6692. }
  6693. /**
  6694. * A render target is a buffer where the video card draws pixels for a scene
  6695. * that is being rendered in the background. It is used in different effects,
  6696. * such as applying postprocessing to a rendered image before displaying it
  6697. * on the screen.
  6698. *
  6699. * @augments EventDispatcher
  6700. */
  6701. class RenderTarget extends EventDispatcher {
  6702. /**
  6703. * Render target options.
  6704. *
  6705. * @typedef {Object} RenderTarget~Options
  6706. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6707. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6708. * @property {number} [minFilter=LinearFilter] - The min filter.
  6709. * @property {number} [format=RGBAFormat] - The texture format.
  6710. * @property {number} [type=UnsignedByteType] - The texture type.
  6711. * @property {?string} [internalFormat=null] - The texture's internal format.
  6712. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6713. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6714. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6715. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6716. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6717. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6718. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6719. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6720. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6721. * @property {number} [samples=0] - The MSAA samples count.
  6722. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6723. * @property {number} [depth=1] - The texture depth.
  6724. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6725. */
  6726. /**
  6727. * Constructs a new render target.
  6728. *
  6729. * @param {number} [width=1] - The width of the render target.
  6730. * @param {number} [height=1] - The height of the render target.
  6731. * @param {RenderTarget~Options} [options] - The configuration object.
  6732. */
  6733. constructor( width = 1, height = 1, options = {} ) {
  6734. super();
  6735. options = Object.assign( {
  6736. generateMipmaps: false,
  6737. internalFormat: null,
  6738. minFilter: LinearFilter,
  6739. depthBuffer: true,
  6740. stencilBuffer: false,
  6741. resolveDepthBuffer: true,
  6742. resolveStencilBuffer: true,
  6743. depthTexture: null,
  6744. samples: 0,
  6745. count: 1,
  6746. depth: 1,
  6747. multiview: false
  6748. }, options );
  6749. /**
  6750. * This flag can be used for type testing.
  6751. *
  6752. * @type {boolean}
  6753. * @readonly
  6754. * @default true
  6755. */
  6756. this.isRenderTarget = true;
  6757. /**
  6758. * The width of the render target.
  6759. *
  6760. * @type {number}
  6761. * @default 1
  6762. */
  6763. this.width = width;
  6764. /**
  6765. * The height of the render target.
  6766. *
  6767. * @type {number}
  6768. * @default 1
  6769. */
  6770. this.height = height;
  6771. /**
  6772. * The depth of the render target.
  6773. *
  6774. * @type {number}
  6775. * @default 1
  6776. */
  6777. this.depth = options.depth;
  6778. /**
  6779. * A rectangular area inside the render target's viewport. Fragments that are
  6780. * outside the area will be discarded.
  6781. *
  6782. * @type {Vector4}
  6783. * @default (0,0,width,height)
  6784. */
  6785. this.scissor = new Vector4( 0, 0, width, height );
  6786. /**
  6787. * Indicates whether the scissor test should be enabled when rendering into
  6788. * this render target or not.
  6789. *
  6790. * @type {boolean}
  6791. * @default false
  6792. */
  6793. this.scissorTest = false;
  6794. /**
  6795. * A rectangular area representing the render target's viewport.
  6796. *
  6797. * @type {Vector4}
  6798. * @default (0,0,width,height)
  6799. */
  6800. this.viewport = new Vector4( 0, 0, width, height );
  6801. const image = { width: width, height: height, depth: options.depth };
  6802. const texture = new Texture( image );
  6803. /**
  6804. * An array of textures. Each color attachment is represented as a separate texture.
  6805. * Has at least a single entry for the default color attachment.
  6806. *
  6807. * @type {Array<Texture>}
  6808. */
  6809. this.textures = [];
  6810. const count = options.count;
  6811. for ( let i = 0; i < count; i ++ ) {
  6812. this.textures[ i ] = texture.clone();
  6813. this.textures[ i ].isRenderTargetTexture = true;
  6814. this.textures[ i ].renderTarget = this;
  6815. }
  6816. this._setTextureOptions( options );
  6817. /**
  6818. * Whether to allocate a depth buffer or not.
  6819. *
  6820. * @type {boolean}
  6821. * @default true
  6822. */
  6823. this.depthBuffer = options.depthBuffer;
  6824. /**
  6825. * Whether to allocate a stencil buffer or not.
  6826. *
  6827. * @type {boolean}
  6828. * @default false
  6829. */
  6830. this.stencilBuffer = options.stencilBuffer;
  6831. /**
  6832. * Whether to resolve the depth buffer or not.
  6833. *
  6834. * @type {boolean}
  6835. * @default true
  6836. */
  6837. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6838. /**
  6839. * Whether to resolve the stencil buffer or not.
  6840. *
  6841. * @type {boolean}
  6842. * @default true
  6843. */
  6844. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6845. this._depthTexture = null;
  6846. this.depthTexture = options.depthTexture;
  6847. /**
  6848. * The number of MSAA samples.
  6849. *
  6850. * A value of `0` disables MSAA.
  6851. *
  6852. * @type {number}
  6853. * @default 0
  6854. */
  6855. this.samples = options.samples;
  6856. /**
  6857. * Whether to this target is used in multiview rendering.
  6858. *
  6859. * @type {boolean}
  6860. * @default false
  6861. */
  6862. this.multiview = options.multiview;
  6863. }
  6864. _setTextureOptions( options = {} ) {
  6865. const values = {
  6866. minFilter: LinearFilter,
  6867. generateMipmaps: false,
  6868. flipY: false,
  6869. internalFormat: null
  6870. };
  6871. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6872. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6873. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6874. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6875. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6876. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6877. if ( options.format !== undefined ) values.format = options.format;
  6878. if ( options.type !== undefined ) values.type = options.type;
  6879. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6880. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6881. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6882. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6883. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6884. for ( let i = 0; i < this.textures.length; i ++ ) {
  6885. const texture = this.textures[ i ];
  6886. texture.setValues( values );
  6887. }
  6888. }
  6889. /**
  6890. * The texture representing the default color attachment.
  6891. *
  6892. * @type {Texture}
  6893. */
  6894. get texture() {
  6895. return this.textures[ 0 ];
  6896. }
  6897. set texture( value ) {
  6898. this.textures[ 0 ] = value;
  6899. }
  6900. set depthTexture( current ) {
  6901. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6902. if ( current !== null ) current.renderTarget = this;
  6903. this._depthTexture = current;
  6904. }
  6905. /**
  6906. * Instead of saving the depth in a renderbuffer, a texture
  6907. * can be used instead which is useful for further processing
  6908. * e.g. in context of post-processing.
  6909. *
  6910. * @type {?DepthTexture}
  6911. * @default null
  6912. */
  6913. get depthTexture() {
  6914. return this._depthTexture;
  6915. }
  6916. /**
  6917. * Sets the size of this render target.
  6918. *
  6919. * @param {number} width - The width.
  6920. * @param {number} height - The height.
  6921. * @param {number} [depth=1] - The depth.
  6922. */
  6923. setSize( width, height, depth = 1 ) {
  6924. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6925. this.width = width;
  6926. this.height = height;
  6927. this.depth = depth;
  6928. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6929. this.textures[ i ].image.width = width;
  6930. this.textures[ i ].image.height = height;
  6931. this.textures[ i ].image.depth = depth;
  6932. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6933. }
  6934. this.dispose();
  6935. }
  6936. this.viewport.set( 0, 0, width, height );
  6937. this.scissor.set( 0, 0, width, height );
  6938. }
  6939. /**
  6940. * Returns a new render target with copied values from this instance.
  6941. *
  6942. * @return {RenderTarget} A clone of this instance.
  6943. */
  6944. clone() {
  6945. return new this.constructor().copy( this );
  6946. }
  6947. /**
  6948. * Copies the settings of the given render target. This is a structural copy so
  6949. * no resources are shared between render targets after the copy. That includes
  6950. * all MRT textures and the depth texture.
  6951. *
  6952. * @param {RenderTarget} source - The render target to copy.
  6953. * @return {RenderTarget} A reference to this instance.
  6954. */
  6955. copy( source ) {
  6956. this.width = source.width;
  6957. this.height = source.height;
  6958. this.depth = source.depth;
  6959. this.scissor.copy( source.scissor );
  6960. this.scissorTest = source.scissorTest;
  6961. this.viewport.copy( source.viewport );
  6962. this.textures.length = 0;
  6963. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6964. this.textures[ i ] = source.textures[ i ].clone();
  6965. this.textures[ i ].isRenderTargetTexture = true;
  6966. this.textures[ i ].renderTarget = this;
  6967. // ensure image object is not shared, see #20328
  6968. const image = Object.assign( {}, source.textures[ i ].image );
  6969. this.textures[ i ].source = new Source( image );
  6970. }
  6971. this.depthBuffer = source.depthBuffer;
  6972. this.stencilBuffer = source.stencilBuffer;
  6973. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6974. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6975. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6976. this.samples = source.samples;
  6977. return this;
  6978. }
  6979. /**
  6980. * Frees the GPU-related resources allocated by this instance. Call this
  6981. * method whenever this instance is no longer used in your app.
  6982. *
  6983. * @fires RenderTarget#dispose
  6984. */
  6985. dispose() {
  6986. this.dispatchEvent( { type: 'dispose' } );
  6987. }
  6988. }
  6989. /**
  6990. * A render target used in context of {@link WebGLRenderer}.
  6991. *
  6992. * @augments RenderTarget
  6993. */
  6994. class WebGLRenderTarget extends RenderTarget {
  6995. /**
  6996. * Constructs a new 3D render target.
  6997. *
  6998. * @param {number} [width=1] - The width of the render target.
  6999. * @param {number} [height=1] - The height of the render target.
  7000. * @param {RenderTarget~Options} [options] - The configuration object.
  7001. */
  7002. constructor( width = 1, height = 1, options = {} ) {
  7003. super( width, height, options );
  7004. /**
  7005. * This flag can be used for type testing.
  7006. *
  7007. * @type {boolean}
  7008. * @readonly
  7009. * @default true
  7010. */
  7011. this.isWebGLRenderTarget = true;
  7012. }
  7013. }
  7014. /**
  7015. * Creates an array of textures directly from raw buffer data.
  7016. *
  7017. * @augments Texture
  7018. */
  7019. class DataArrayTexture extends Texture {
  7020. /**
  7021. * Constructs a new data array texture.
  7022. *
  7023. * @param {?TypedArray} [data=null] - The buffer data.
  7024. * @param {number} [width=1] - The width of the texture.
  7025. * @param {number} [height=1] - The height of the texture.
  7026. * @param {number} [depth=1] - The depth of the texture.
  7027. */
  7028. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7029. super( null );
  7030. /**
  7031. * This flag can be used for type testing.
  7032. *
  7033. * @type {boolean}
  7034. * @readonly
  7035. * @default true
  7036. */
  7037. this.isDataArrayTexture = true;
  7038. /**
  7039. * The image definition of a data texture.
  7040. *
  7041. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7042. */
  7043. this.image = { data, width, height, depth };
  7044. /**
  7045. * How the texture is sampled when a texel covers more than one pixel.
  7046. *
  7047. * Overwritten and set to `NearestFilter` by default.
  7048. *
  7049. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7050. * @default NearestFilter
  7051. */
  7052. this.magFilter = NearestFilter;
  7053. /**
  7054. * How the texture is sampled when a texel covers less than one pixel.
  7055. *
  7056. * Overwritten and set to `NearestFilter` by default.
  7057. *
  7058. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7059. * @default NearestFilter
  7060. */
  7061. this.minFilter = NearestFilter;
  7062. /**
  7063. * This defines how the texture is wrapped in the depth and corresponds to
  7064. * *W* in UVW mapping.
  7065. *
  7066. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7067. * @default ClampToEdgeWrapping
  7068. */
  7069. this.wrapR = ClampToEdgeWrapping;
  7070. /**
  7071. * Whether to generate mipmaps (if possible) for a texture.
  7072. *
  7073. * Overwritten and set to `false` by default.
  7074. *
  7075. * @type {boolean}
  7076. * @default false
  7077. */
  7078. this.generateMipmaps = false;
  7079. /**
  7080. * If set to `true`, the texture is flipped along the vertical axis when
  7081. * uploaded to the GPU.
  7082. *
  7083. * Overwritten and set to `false` by default.
  7084. *
  7085. * @type {boolean}
  7086. * @default false
  7087. */
  7088. this.flipY = false;
  7089. /**
  7090. * Specifies the alignment requirements for the start of each pixel row in memory.
  7091. *
  7092. * Overwritten and set to `1` by default.
  7093. *
  7094. * @type {boolean}
  7095. * @default 1
  7096. */
  7097. this.unpackAlignment = 1;
  7098. /**
  7099. * A set of all layers which need to be updated in the texture.
  7100. *
  7101. * @type {Set<number>}
  7102. */
  7103. this.layerUpdates = new Set();
  7104. }
  7105. /**
  7106. * Describes that a specific layer of the texture needs to be updated.
  7107. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7108. * entire data texture array is sent to the GPU. Marking specific
  7109. * layers will only transmit subsets of all mipmaps associated with a
  7110. * specific depth in the array which is often much more performant.
  7111. *
  7112. * @param {number} layerIndex - The layer index that should be updated.
  7113. */
  7114. addLayerUpdate( layerIndex ) {
  7115. this.layerUpdates.add( layerIndex );
  7116. }
  7117. /**
  7118. * Resets the layer updates registry.
  7119. */
  7120. clearLayerUpdates() {
  7121. this.layerUpdates.clear();
  7122. }
  7123. }
  7124. /**
  7125. * An array render target used in context of {@link WebGLRenderer}.
  7126. *
  7127. * @augments WebGLRenderTarget
  7128. */
  7129. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7130. /**
  7131. * Constructs a new array render target.
  7132. *
  7133. * @param {number} [width=1] - The width of the render target.
  7134. * @param {number} [height=1] - The height of the render target.
  7135. * @param {number} [depth=1] - The height of the render target.
  7136. * @param {RenderTarget~Options} [options] - The configuration object.
  7137. */
  7138. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7139. super( width, height, options );
  7140. /**
  7141. * This flag can be used for type testing.
  7142. *
  7143. * @type {boolean}
  7144. * @readonly
  7145. * @default true
  7146. */
  7147. this.isWebGLArrayRenderTarget = true;
  7148. this.depth = depth;
  7149. /**
  7150. * Overwritten with a different texture type.
  7151. *
  7152. * @type {DataArrayTexture}
  7153. */
  7154. this.texture = new DataArrayTexture( null, width, height, depth );
  7155. this._setTextureOptions( options );
  7156. this.texture.isRenderTargetTexture = true;
  7157. }
  7158. }
  7159. /**
  7160. * Creates a three-dimensional texture from raw data, with parameters to
  7161. * divide it into width, height, and depth.
  7162. *
  7163. * @augments Texture
  7164. */
  7165. class Data3DTexture extends Texture {
  7166. /**
  7167. * Constructs a new data array texture.
  7168. *
  7169. * @param {?TypedArray} [data=null] - The buffer data.
  7170. * @param {number} [width=1] - The width of the texture.
  7171. * @param {number} [height=1] - The height of the texture.
  7172. * @param {number} [depth=1] - The depth of the texture.
  7173. */
  7174. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7175. // We're going to add .setXXX() methods for setting properties later.
  7176. // Users can still set in Data3DTexture directly.
  7177. //
  7178. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7179. // texture.anisotropy = 16;
  7180. //
  7181. // See #14839
  7182. super( null );
  7183. /**
  7184. * This flag can be used for type testing.
  7185. *
  7186. * @type {boolean}
  7187. * @readonly
  7188. * @default true
  7189. */
  7190. this.isData3DTexture = true;
  7191. /**
  7192. * The image definition of a data texture.
  7193. *
  7194. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7195. */
  7196. this.image = { data, width, height, depth };
  7197. /**
  7198. * How the texture is sampled when a texel covers more than one pixel.
  7199. *
  7200. * Overwritten and set to `NearestFilter` by default.
  7201. *
  7202. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7203. * @default NearestFilter
  7204. */
  7205. this.magFilter = NearestFilter;
  7206. /**
  7207. * How the texture is sampled when a texel covers less than one pixel.
  7208. *
  7209. * Overwritten and set to `NearestFilter` by default.
  7210. *
  7211. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7212. * @default NearestFilter
  7213. */
  7214. this.minFilter = NearestFilter;
  7215. /**
  7216. * This defines how the texture is wrapped in the depth and corresponds to
  7217. * *W* in UVW mapping.
  7218. *
  7219. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7220. * @default ClampToEdgeWrapping
  7221. */
  7222. this.wrapR = ClampToEdgeWrapping;
  7223. /**
  7224. * Whether to generate mipmaps (if possible) for a texture.
  7225. *
  7226. * Overwritten and set to `false` by default.
  7227. *
  7228. * @type {boolean}
  7229. * @default false
  7230. */
  7231. this.generateMipmaps = false;
  7232. /**
  7233. * If set to `true`, the texture is flipped along the vertical axis when
  7234. * uploaded to the GPU.
  7235. *
  7236. * Overwritten and set to `false` by default.
  7237. *
  7238. * @type {boolean}
  7239. * @default false
  7240. */
  7241. this.flipY = false;
  7242. /**
  7243. * Specifies the alignment requirements for the start of each pixel row in memory.
  7244. *
  7245. * Overwritten and set to `1` by default.
  7246. *
  7247. * @type {boolean}
  7248. * @default 1
  7249. */
  7250. this.unpackAlignment = 1;
  7251. }
  7252. }
  7253. /**
  7254. * A 3D render target used in context of {@link WebGLRenderer}.
  7255. *
  7256. * @augments WebGLRenderTarget
  7257. */
  7258. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7259. /**
  7260. * Constructs a new 3D render target.
  7261. *
  7262. * @param {number} [width=1] - The width of the render target.
  7263. * @param {number} [height=1] - The height of the render target.
  7264. * @param {number} [depth=1] - The height of the render target.
  7265. * @param {RenderTarget~Options} [options] - The configuration object.
  7266. */
  7267. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7268. super( width, height, options );
  7269. /**
  7270. * This flag can be used for type testing.
  7271. *
  7272. * @type {boolean}
  7273. * @readonly
  7274. * @default true
  7275. */
  7276. this.isWebGL3DRenderTarget = true;
  7277. this.depth = depth;
  7278. /**
  7279. * Overwritten with a different texture type.
  7280. *
  7281. * @type {Data3DTexture}
  7282. */
  7283. this.texture = new Data3DTexture( null, width, height, depth );
  7284. this._setTextureOptions( options );
  7285. this.texture.isRenderTargetTexture = true;
  7286. }
  7287. }
  7288. /**
  7289. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7290. */
  7291. class Box3 {
  7292. /**
  7293. * Constructs a new bounding box.
  7294. *
  7295. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7296. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7297. */
  7298. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7299. /**
  7300. * This flag can be used for type testing.
  7301. *
  7302. * @type {boolean}
  7303. * @readonly
  7304. * @default true
  7305. */
  7306. this.isBox3 = true;
  7307. /**
  7308. * The lower boundary of the box.
  7309. *
  7310. * @type {Vector3}
  7311. */
  7312. this.min = min;
  7313. /**
  7314. * The upper boundary of the box.
  7315. *
  7316. * @type {Vector3}
  7317. */
  7318. this.max = max;
  7319. }
  7320. /**
  7321. * Sets the lower and upper boundaries of this box.
  7322. * Please note that this method only copies the values from the given objects.
  7323. *
  7324. * @param {Vector3} min - The lower boundary of the box.
  7325. * @param {Vector3} max - The upper boundary of the box.
  7326. * @return {Box3} A reference to this bounding box.
  7327. */
  7328. set( min, max ) {
  7329. this.min.copy( min );
  7330. this.max.copy( max );
  7331. return this;
  7332. }
  7333. /**
  7334. * Sets the upper and lower bounds of this box so it encloses the position data
  7335. * in the given array.
  7336. *
  7337. * @param {Array<number>} array - An array holding 3D position data.
  7338. * @return {Box3} A reference to this bounding box.
  7339. */
  7340. setFromArray( array ) {
  7341. this.makeEmpty();
  7342. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7343. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7344. }
  7345. return this;
  7346. }
  7347. /**
  7348. * Sets the upper and lower bounds of this box so it encloses the position data
  7349. * in the given buffer attribute.
  7350. *
  7351. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7352. * @return {Box3} A reference to this bounding box.
  7353. */
  7354. setFromBufferAttribute( attribute ) {
  7355. this.makeEmpty();
  7356. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7357. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7358. }
  7359. return this;
  7360. }
  7361. /**
  7362. * Sets the upper and lower bounds of this box so it encloses the position data
  7363. * in the given array.
  7364. *
  7365. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7366. * @return {Box3} A reference to this bounding box.
  7367. */
  7368. setFromPoints( points ) {
  7369. this.makeEmpty();
  7370. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7371. this.expandByPoint( points[ i ] );
  7372. }
  7373. return this;
  7374. }
  7375. /**
  7376. * Centers this box on the given center vector and sets this box's width, height and
  7377. * depth to the given size values.
  7378. *
  7379. * @param {Vector3} center - The center of the box.
  7380. * @param {Vector3} size - The x, y and z dimensions of the box.
  7381. * @return {Box3} A reference to this bounding box.
  7382. */
  7383. setFromCenterAndSize( center, size ) {
  7384. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7385. this.min.copy( center ).sub( halfSize );
  7386. this.max.copy( center ).add( halfSize );
  7387. return this;
  7388. }
  7389. /**
  7390. * Computes the world-axis-aligned bounding box for the given 3D object
  7391. * (including its children), accounting for the object's, and children's,
  7392. * world transforms. The function may result in a larger box than strictly necessary.
  7393. *
  7394. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7395. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7396. * world-axis-aligned bounding box at the expense of more computation.
  7397. * @return {Box3} A reference to this bounding box.
  7398. */
  7399. setFromObject( object, precise = false ) {
  7400. this.makeEmpty();
  7401. return this.expandByObject( object, precise );
  7402. }
  7403. /**
  7404. * Returns a new box with copied values from this instance.
  7405. *
  7406. * @return {Box3} A clone of this instance.
  7407. */
  7408. clone() {
  7409. return new this.constructor().copy( this );
  7410. }
  7411. /**
  7412. * Copies the values of the given box to this instance.
  7413. *
  7414. * @param {Box3} box - The box to copy.
  7415. * @return {Box3} A reference to this bounding box.
  7416. */
  7417. copy( box ) {
  7418. this.min.copy( box.min );
  7419. this.max.copy( box.max );
  7420. return this;
  7421. }
  7422. /**
  7423. * Makes this box empty which means in encloses a zero space in 3D.
  7424. *
  7425. * @return {Box3} A reference to this bounding box.
  7426. */
  7427. makeEmpty() {
  7428. this.min.x = this.min.y = this.min.z = + Infinity;
  7429. this.max.x = this.max.y = this.max.z = - Infinity;
  7430. return this;
  7431. }
  7432. /**
  7433. * Returns true if this box includes zero points within its bounds.
  7434. * Note that a box with equal lower and upper bounds still includes one
  7435. * point, the one both bounds share.
  7436. *
  7437. * @return {boolean} Whether this box is empty or not.
  7438. */
  7439. isEmpty() {
  7440. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7441. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7442. }
  7443. /**
  7444. * Returns the center point of this box.
  7445. *
  7446. * @param {Vector3} target - The target vector that is used to store the method's result.
  7447. * @return {Vector3} The center point.
  7448. */
  7449. getCenter( target ) {
  7450. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7451. }
  7452. /**
  7453. * Returns the dimensions of this box.
  7454. *
  7455. * @param {Vector3} target - The target vector that is used to store the method's result.
  7456. * @return {Vector3} The size.
  7457. */
  7458. getSize( target ) {
  7459. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7460. }
  7461. /**
  7462. * Expands the boundaries of this box to include the given point.
  7463. *
  7464. * @param {Vector3} point - The point that should be included by the bounding box.
  7465. * @return {Box3} A reference to this bounding box.
  7466. */
  7467. expandByPoint( point ) {
  7468. this.min.min( point );
  7469. this.max.max( point );
  7470. return this;
  7471. }
  7472. /**
  7473. * Expands this box equilaterally by the given vector. The width of this
  7474. * box will be expanded by the x component of the vector in both
  7475. * directions. The height of this box will be expanded by the y component of
  7476. * the vector in both directions. The depth of this box will be
  7477. * expanded by the z component of the vector in both directions.
  7478. *
  7479. * @param {Vector3} vector - The vector that should expand the bounding box.
  7480. * @return {Box3} A reference to this bounding box.
  7481. */
  7482. expandByVector( vector ) {
  7483. this.min.sub( vector );
  7484. this.max.add( vector );
  7485. return this;
  7486. }
  7487. /**
  7488. * Expands each dimension of the box by the given scalar. If negative, the
  7489. * dimensions of the box will be contracted.
  7490. *
  7491. * @param {number} scalar - The scalar value that should expand the bounding box.
  7492. * @return {Box3} A reference to this bounding box.
  7493. */
  7494. expandByScalar( scalar ) {
  7495. this.min.addScalar( - scalar );
  7496. this.max.addScalar( scalar );
  7497. return this;
  7498. }
  7499. /**
  7500. * Expands the boundaries of this box to include the given 3D object and
  7501. * its children, accounting for the object's, and children's, world
  7502. * transforms. The function may result in a larger box than strictly
  7503. * necessary (unless the precise parameter is set to true).
  7504. *
  7505. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7506. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7507. * as little as necessary at the expense of more computation.
  7508. * @return {Box3} A reference to this bounding box.
  7509. */
  7510. expandByObject( object, precise = false ) {
  7511. // Computes the world-axis-aligned bounding box of an object (including its children),
  7512. // accounting for both the object's, and children's, world transforms
  7513. object.updateWorldMatrix( false, false );
  7514. const geometry = object.geometry;
  7515. if ( geometry !== undefined ) {
  7516. const positionAttribute = geometry.getAttribute( 'position' );
  7517. // precise AABB computation based on vertex data requires at least a position attribute.
  7518. // instancing isn't supported so far and uses the normal (conservative) code path.
  7519. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7520. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7521. if ( object.isMesh === true ) {
  7522. object.getVertexPosition( i, _vector$b );
  7523. } else {
  7524. _vector$b.fromBufferAttribute( positionAttribute, i );
  7525. }
  7526. _vector$b.applyMatrix4( object.matrixWorld );
  7527. this.expandByPoint( _vector$b );
  7528. }
  7529. } else {
  7530. if ( object.boundingBox !== undefined ) {
  7531. // object-level bounding box
  7532. if ( object.boundingBox === null ) {
  7533. object.computeBoundingBox();
  7534. }
  7535. _box$4.copy( object.boundingBox );
  7536. } else {
  7537. // geometry-level bounding box
  7538. if ( geometry.boundingBox === null ) {
  7539. geometry.computeBoundingBox();
  7540. }
  7541. _box$4.copy( geometry.boundingBox );
  7542. }
  7543. _box$4.applyMatrix4( object.matrixWorld );
  7544. this.union( _box$4 );
  7545. }
  7546. }
  7547. const children = object.children;
  7548. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7549. this.expandByObject( children[ i ], precise );
  7550. }
  7551. return this;
  7552. }
  7553. /**
  7554. * Returns `true` if the given point lies within or on the boundaries of this box.
  7555. *
  7556. * @param {Vector3} point - The point to test.
  7557. * @return {boolean} Whether the bounding box contains the given point or not.
  7558. */
  7559. containsPoint( point ) {
  7560. return point.x >= this.min.x && point.x <= this.max.x &&
  7561. point.y >= this.min.y && point.y <= this.max.y &&
  7562. point.z >= this.min.z && point.z <= this.max.z;
  7563. }
  7564. /**
  7565. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7566. * If this box and the given one are identical, this function also returns `true`.
  7567. *
  7568. * @param {Box3} box - The bounding box to test.
  7569. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7570. */
  7571. containsBox( box ) {
  7572. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7573. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7574. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7575. }
  7576. /**
  7577. * Returns a point as a proportion of this box's width, height and depth.
  7578. *
  7579. * @param {Vector3} point - A point in 3D space.
  7580. * @param {Vector3} target - The target vector that is used to store the method's result.
  7581. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7582. */
  7583. getParameter( point, target ) {
  7584. // This can potentially have a divide by zero if the box
  7585. // has a size dimension of 0.
  7586. return target.set(
  7587. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7588. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7589. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7590. );
  7591. }
  7592. /**
  7593. * Returns `true` if the given bounding box intersects with this bounding box.
  7594. *
  7595. * @param {Box3} box - The bounding box to test.
  7596. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7597. */
  7598. intersectsBox( box ) {
  7599. // using 6 splitting planes to rule out intersections.
  7600. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7601. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7602. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7603. }
  7604. /**
  7605. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7606. *
  7607. * @param {Sphere} sphere - The bounding sphere to test.
  7608. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7609. */
  7610. intersectsSphere( sphere ) {
  7611. // Find the point on the AABB closest to the sphere center.
  7612. this.clampPoint( sphere.center, _vector$b );
  7613. // If that point is inside the sphere, the AABB and sphere intersect.
  7614. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7615. }
  7616. /**
  7617. * Returns `true` if the given plane intersects with this bounding box.
  7618. *
  7619. * @param {Plane} plane - The plane to test.
  7620. * @return {boolean} Whether the given plane intersects with this bounding box.
  7621. */
  7622. intersectsPlane( plane ) {
  7623. // We compute the minimum and maximum dot product values. If those values
  7624. // are on the same side (back or front) of the plane, then there is no intersection.
  7625. let min, max;
  7626. if ( plane.normal.x > 0 ) {
  7627. min = plane.normal.x * this.min.x;
  7628. max = plane.normal.x * this.max.x;
  7629. } else {
  7630. min = plane.normal.x * this.max.x;
  7631. max = plane.normal.x * this.min.x;
  7632. }
  7633. if ( plane.normal.y > 0 ) {
  7634. min += plane.normal.y * this.min.y;
  7635. max += plane.normal.y * this.max.y;
  7636. } else {
  7637. min += plane.normal.y * this.max.y;
  7638. max += plane.normal.y * this.min.y;
  7639. }
  7640. if ( plane.normal.z > 0 ) {
  7641. min += plane.normal.z * this.min.z;
  7642. max += plane.normal.z * this.max.z;
  7643. } else {
  7644. min += plane.normal.z * this.max.z;
  7645. max += plane.normal.z * this.min.z;
  7646. }
  7647. return ( min <= - plane.constant && max >= - plane.constant );
  7648. }
  7649. /**
  7650. * Returns `true` if the given triangle intersects with this bounding box.
  7651. *
  7652. * @param {Triangle} triangle - The triangle to test.
  7653. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7654. */
  7655. intersectsTriangle( triangle ) {
  7656. if ( this.isEmpty() ) {
  7657. return false;
  7658. }
  7659. // compute box center and extents
  7660. this.getCenter( _center );
  7661. _extents.subVectors( this.max, _center );
  7662. // translate triangle to aabb origin
  7663. _v0$3.subVectors( triangle.a, _center );
  7664. _v1$7.subVectors( triangle.b, _center );
  7665. _v2$4.subVectors( triangle.c, _center );
  7666. // compute edge vectors for triangle
  7667. _f0.subVectors( _v1$7, _v0$3 );
  7668. _f1.subVectors( _v2$4, _v1$7 );
  7669. _f2.subVectors( _v0$3, _v2$4 );
  7670. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7671. // 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
  7672. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7673. let axes = [
  7674. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7675. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7676. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7677. ];
  7678. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7679. return false;
  7680. }
  7681. // test 3 face normals from the aabb
  7682. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7683. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7684. return false;
  7685. }
  7686. // finally testing the face normal of the triangle
  7687. // use already existing triangle edge vectors here
  7688. _triangleNormal.crossVectors( _f0, _f1 );
  7689. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7690. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7691. }
  7692. /**
  7693. * Clamps the given point within the bounds of this box.
  7694. *
  7695. * @param {Vector3} point - The point to clamp.
  7696. * @param {Vector3} target - The target vector that is used to store the method's result.
  7697. * @return {Vector3} The clamped point.
  7698. */
  7699. clampPoint( point, target ) {
  7700. return target.copy( point ).clamp( this.min, this.max );
  7701. }
  7702. /**
  7703. * Returns the euclidean distance from any edge of this box to the specified point. If
  7704. * the given point lies inside of this box, the distance will be `0`.
  7705. *
  7706. * @param {Vector3} point - The point to compute the distance to.
  7707. * @return {number} The euclidean distance.
  7708. */
  7709. distanceToPoint( point ) {
  7710. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7711. }
  7712. /**
  7713. * Returns a bounding sphere that encloses this bounding box.
  7714. *
  7715. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7716. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7717. */
  7718. getBoundingSphere( target ) {
  7719. if ( this.isEmpty() ) {
  7720. target.makeEmpty();
  7721. } else {
  7722. this.getCenter( target.center );
  7723. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7724. }
  7725. return target;
  7726. }
  7727. /**
  7728. * Computes the intersection of this bounding box and the given one, setting the upper
  7729. * bound of this box to the lesser of the two boxes' upper bounds and the
  7730. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7731. * there's no overlap, makes this box empty.
  7732. *
  7733. * @param {Box3} box - The bounding box to intersect with.
  7734. * @return {Box3} A reference to this bounding box.
  7735. */
  7736. intersect( box ) {
  7737. this.min.max( box.min );
  7738. this.max.min( box.max );
  7739. // 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.
  7740. if ( this.isEmpty() ) this.makeEmpty();
  7741. return this;
  7742. }
  7743. /**
  7744. * Computes the union of this box and another and the given one, setting the upper
  7745. * bound of this box to the greater of the two boxes' upper bounds and the
  7746. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7747. *
  7748. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7749. * @return {Box3} A reference to this bounding box.
  7750. */
  7751. union( box ) {
  7752. this.min.min( box.min );
  7753. this.max.max( box.max );
  7754. return this;
  7755. }
  7756. /**
  7757. * Transforms this bounding box by the given 4x4 transformation matrix.
  7758. *
  7759. * @param {Matrix4} matrix - The transformation matrix.
  7760. * @return {Box3} A reference to this bounding box.
  7761. */
  7762. applyMatrix4( matrix ) {
  7763. // transform of empty box is an empty box.
  7764. if ( this.isEmpty() ) return this;
  7765. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7766. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7767. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7768. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7769. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7770. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7771. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7772. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7773. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7774. this.setFromPoints( _points );
  7775. return this;
  7776. }
  7777. /**
  7778. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7779. * effectively moving it in 3D space.
  7780. *
  7781. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7782. * @return {Box3} A reference to this bounding box.
  7783. */
  7784. translate( offset ) {
  7785. this.min.add( offset );
  7786. this.max.add( offset );
  7787. return this;
  7788. }
  7789. /**
  7790. * Returns `true` if this bounding box is equal with the given one.
  7791. *
  7792. * @param {Box3} box - The box to test for equality.
  7793. * @return {boolean} Whether this bounding box is equal with the given one.
  7794. */
  7795. equals( box ) {
  7796. return box.min.equals( this.min ) && box.max.equals( this.max );
  7797. }
  7798. /**
  7799. * Returns a serialized structure of the bounding box.
  7800. *
  7801. * @return {Object} Serialized structure with fields representing the object state.
  7802. */
  7803. toJSON() {
  7804. return {
  7805. min: this.min.toArray(),
  7806. max: this.max.toArray()
  7807. };
  7808. }
  7809. /**
  7810. * Returns a serialized structure of the bounding box.
  7811. *
  7812. * @param {Object} json - The serialized json to set the box from.
  7813. * @return {Box3} A reference to this bounding box.
  7814. */
  7815. fromJSON( json ) {
  7816. this.min.fromArray( json.min );
  7817. this.max.fromArray( json.max );
  7818. return this;
  7819. }
  7820. }
  7821. const _points = [
  7822. /*@__PURE__*/ new Vector3(),
  7823. /*@__PURE__*/ new Vector3(),
  7824. /*@__PURE__*/ new Vector3(),
  7825. /*@__PURE__*/ new Vector3(),
  7826. /*@__PURE__*/ new Vector3(),
  7827. /*@__PURE__*/ new Vector3(),
  7828. /*@__PURE__*/ new Vector3(),
  7829. /*@__PURE__*/ new Vector3()
  7830. ];
  7831. const _vector$b = /*@__PURE__*/ new Vector3();
  7832. const _box$4 = /*@__PURE__*/ new Box3();
  7833. // triangle centered vertices
  7834. const _v0$3 = /*@__PURE__*/ new Vector3();
  7835. const _v1$7 = /*@__PURE__*/ new Vector3();
  7836. const _v2$4 = /*@__PURE__*/ new Vector3();
  7837. // triangle edge vectors
  7838. const _f0 = /*@__PURE__*/ new Vector3();
  7839. const _f1 = /*@__PURE__*/ new Vector3();
  7840. const _f2 = /*@__PURE__*/ new Vector3();
  7841. const _center = /*@__PURE__*/ new Vector3();
  7842. const _extents = /*@__PURE__*/ new Vector3();
  7843. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7844. const _testAxis = /*@__PURE__*/ new Vector3();
  7845. function satForAxes( axes, v0, v1, v2, extents ) {
  7846. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7847. _testAxis.fromArray( axes, i );
  7848. // project the aabb onto the separating axis
  7849. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7850. // project all 3 vertices of the triangle onto the separating axis
  7851. const p0 = v0.dot( _testAxis );
  7852. const p1 = v1.dot( _testAxis );
  7853. const p2 = v2.dot( _testAxis );
  7854. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7855. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7856. // points of the projected triangle are outside the projected half-length of the aabb
  7857. // the axis is separating and we can exit
  7858. return false;
  7859. }
  7860. }
  7861. return true;
  7862. }
  7863. const _box$3 = /*@__PURE__*/ new Box3();
  7864. const _v1$6 = /*@__PURE__*/ new Vector3();
  7865. const _v2$3 = /*@__PURE__*/ new Vector3();
  7866. /**
  7867. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7868. * used as a Bounding Sphere for 3D objects.
  7869. */
  7870. class Sphere {
  7871. /**
  7872. * Constructs a new sphere.
  7873. *
  7874. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7875. * @param {number} [radius=-1] - The radius of the sphere.
  7876. */
  7877. constructor( center = new Vector3(), radius = -1 ) {
  7878. /**
  7879. * This flag can be used for type testing.
  7880. *
  7881. * @type {boolean}
  7882. * @readonly
  7883. * @default true
  7884. */
  7885. this.isSphere = true;
  7886. /**
  7887. * The center of the sphere
  7888. *
  7889. * @type {Vector3}
  7890. */
  7891. this.center = center;
  7892. /**
  7893. * The radius of the sphere.
  7894. *
  7895. * @type {number}
  7896. */
  7897. this.radius = radius;
  7898. }
  7899. /**
  7900. * Sets the sphere's components by copying the given values.
  7901. *
  7902. * @param {Vector3} center - The center.
  7903. * @param {number} radius - The radius.
  7904. * @return {Sphere} A reference to this sphere.
  7905. */
  7906. set( center, radius ) {
  7907. this.center.copy( center );
  7908. this.radius = radius;
  7909. return this;
  7910. }
  7911. /**
  7912. * Computes the minimum bounding sphere for list of points.
  7913. * If the optional center point is given, it is used as the sphere's
  7914. * center. Otherwise, the center of the axis-aligned bounding box
  7915. * encompassing the points is calculated.
  7916. *
  7917. * @param {Array<Vector3>} points - A list of points in 3D space.
  7918. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7919. * @return {Sphere} A reference to this sphere.
  7920. */
  7921. setFromPoints( points, optionalCenter ) {
  7922. const center = this.center;
  7923. if ( optionalCenter !== undefined ) {
  7924. center.copy( optionalCenter );
  7925. } else {
  7926. _box$3.setFromPoints( points ).getCenter( center );
  7927. }
  7928. let maxRadiusSq = 0;
  7929. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7930. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7931. }
  7932. this.radius = Math.sqrt( maxRadiusSq );
  7933. return this;
  7934. }
  7935. /**
  7936. * Copies the values of the given sphere to this instance.
  7937. *
  7938. * @param {Sphere} sphere - The sphere to copy.
  7939. * @return {Sphere} A reference to this sphere.
  7940. */
  7941. copy( sphere ) {
  7942. this.center.copy( sphere.center );
  7943. this.radius = sphere.radius;
  7944. return this;
  7945. }
  7946. /**
  7947. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7948. *
  7949. * Spheres with a radius of `0` contain only their center point and are not
  7950. * considered to be empty.
  7951. *
  7952. * @return {boolean} Whether this sphere is empty or not.
  7953. */
  7954. isEmpty() {
  7955. return ( this.radius < 0 );
  7956. }
  7957. /**
  7958. * Makes this sphere empty which means in encloses a zero space in 3D.
  7959. *
  7960. * @return {Sphere} A reference to this sphere.
  7961. */
  7962. makeEmpty() {
  7963. this.center.set( 0, 0, 0 );
  7964. this.radius = -1;
  7965. return this;
  7966. }
  7967. /**
  7968. * Returns `true` if this sphere contains the given point inclusive of
  7969. * the surface of the sphere.
  7970. *
  7971. * @param {Vector3} point - The point to check.
  7972. * @return {boolean} Whether this sphere contains the given point or not.
  7973. */
  7974. containsPoint( point ) {
  7975. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7976. }
  7977. /**
  7978. * Returns the closest distance from the boundary of the sphere to the
  7979. * given point. If the sphere contains the point, the distance will
  7980. * be negative.
  7981. *
  7982. * @param {Vector3} point - The point to compute the distance to.
  7983. * @return {number} The distance to the point.
  7984. */
  7985. distanceToPoint( point ) {
  7986. return ( point.distanceTo( this.center ) - this.radius );
  7987. }
  7988. /**
  7989. * Returns `true` if this sphere intersects with the given one.
  7990. *
  7991. * @param {Sphere} sphere - The sphere to test.
  7992. * @return {boolean} Whether this sphere intersects with the given one or not.
  7993. */
  7994. intersectsSphere( sphere ) {
  7995. const radiusSum = this.radius + sphere.radius;
  7996. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7997. }
  7998. /**
  7999. * Returns `true` if this sphere intersects with the given box.
  8000. *
  8001. * @param {Box3} box - The box to test.
  8002. * @return {boolean} Whether this sphere intersects with the given box or not.
  8003. */
  8004. intersectsBox( box ) {
  8005. return box.intersectsSphere( this );
  8006. }
  8007. /**
  8008. * Returns `true` if this sphere intersects with the given plane.
  8009. *
  8010. * @param {Plane} plane - The plane to test.
  8011. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8012. */
  8013. intersectsPlane( plane ) {
  8014. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8015. }
  8016. /**
  8017. * Clamps a point within the sphere. If the point is outside the sphere, it
  8018. * will clamp it to the closest point on the edge of the sphere. Points
  8019. * already inside the sphere will not be affected.
  8020. *
  8021. * @param {Vector3} point - The plane to clamp.
  8022. * @param {Vector3} target - The target vector that is used to store the method's result.
  8023. * @return {Vector3} The clamped point.
  8024. */
  8025. clampPoint( point, target ) {
  8026. const deltaLengthSq = this.center.distanceToSquared( point );
  8027. target.copy( point );
  8028. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8029. target.sub( this.center ).normalize();
  8030. target.multiplyScalar( this.radius ).add( this.center );
  8031. }
  8032. return target;
  8033. }
  8034. /**
  8035. * Returns a bounding box that encloses this sphere.
  8036. *
  8037. * @param {Box3} target - The target box that is used to store the method's result.
  8038. * @return {Box3} The bounding box that encloses this sphere.
  8039. */
  8040. getBoundingBox( target ) {
  8041. if ( this.isEmpty() ) {
  8042. // Empty sphere produces empty bounding box
  8043. target.makeEmpty();
  8044. return target;
  8045. }
  8046. target.set( this.center, this.center );
  8047. target.expandByScalar( this.radius );
  8048. return target;
  8049. }
  8050. /**
  8051. * Transforms this sphere with the given 4x4 transformation matrix.
  8052. *
  8053. * @param {Matrix4} matrix - The transformation matrix.
  8054. * @return {Sphere} A reference to this sphere.
  8055. */
  8056. applyMatrix4( matrix ) {
  8057. this.center.applyMatrix4( matrix );
  8058. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8059. return this;
  8060. }
  8061. /**
  8062. * Translates the sphere's center by the given offset.
  8063. *
  8064. * @param {Vector3} offset - The offset.
  8065. * @return {Sphere} A reference to this sphere.
  8066. */
  8067. translate( offset ) {
  8068. this.center.add( offset );
  8069. return this;
  8070. }
  8071. /**
  8072. * Expands the boundaries of this sphere to include the given point.
  8073. *
  8074. * @param {Vector3} point - The point to include.
  8075. * @return {Sphere} A reference to this sphere.
  8076. */
  8077. expandByPoint( point ) {
  8078. if ( this.isEmpty() ) {
  8079. this.center.copy( point );
  8080. this.radius = 0;
  8081. return this;
  8082. }
  8083. _v1$6.subVectors( point, this.center );
  8084. const lengthSq = _v1$6.lengthSq();
  8085. if ( lengthSq > ( this.radius * this.radius ) ) {
  8086. // calculate the minimal sphere
  8087. const length = Math.sqrt( lengthSq );
  8088. const delta = ( length - this.radius ) * 0.5;
  8089. this.center.addScaledVector( _v1$6, delta / length );
  8090. this.radius += delta;
  8091. }
  8092. return this;
  8093. }
  8094. /**
  8095. * Expands this sphere to enclose both the original sphere and the given sphere.
  8096. *
  8097. * @param {Sphere} sphere - The sphere to include.
  8098. * @return {Sphere} A reference to this sphere.
  8099. */
  8100. union( sphere ) {
  8101. if ( sphere.isEmpty() ) {
  8102. return this;
  8103. }
  8104. if ( this.isEmpty() ) {
  8105. this.copy( sphere );
  8106. return this;
  8107. }
  8108. if ( this.center.equals( sphere.center ) === true ) {
  8109. this.radius = Math.max( this.radius, sphere.radius );
  8110. } else {
  8111. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8112. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8113. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8114. }
  8115. return this;
  8116. }
  8117. /**
  8118. * Returns `true` if this sphere is equal with the given one.
  8119. *
  8120. * @param {Sphere} sphere - The sphere to test for equality.
  8121. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8122. */
  8123. equals( sphere ) {
  8124. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8125. }
  8126. /**
  8127. * Returns a new sphere with copied values from this instance.
  8128. *
  8129. * @return {Sphere} A clone of this instance.
  8130. */
  8131. clone() {
  8132. return new this.constructor().copy( this );
  8133. }
  8134. /**
  8135. * Returns a serialized structure of the bounding sphere.
  8136. *
  8137. * @return {Object} Serialized structure with fields representing the object state.
  8138. */
  8139. toJSON() {
  8140. return {
  8141. radius: this.radius,
  8142. center: this.center.toArray()
  8143. };
  8144. }
  8145. /**
  8146. * Returns a serialized structure of the bounding sphere.
  8147. *
  8148. * @param {Object} json - The serialized json to set the sphere from.
  8149. * @return {Box3} A reference to this bounding sphere.
  8150. */
  8151. fromJSON( json ) {
  8152. this.radius = json.radius;
  8153. this.center.fromArray( json.center );
  8154. return this;
  8155. }
  8156. }
  8157. const _vector$a = /*@__PURE__*/ new Vector3();
  8158. const _segCenter = /*@__PURE__*/ new Vector3();
  8159. const _segDir = /*@__PURE__*/ new Vector3();
  8160. const _diff = /*@__PURE__*/ new Vector3();
  8161. const _edge1 = /*@__PURE__*/ new Vector3();
  8162. const _edge2 = /*@__PURE__*/ new Vector3();
  8163. const _normal$1 = /*@__PURE__*/ new Vector3();
  8164. /**
  8165. * A ray that emits from an origin in a certain direction. The class is used by
  8166. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8167. * mouse picking (working out what objects in the 3D space the mouse is over)
  8168. * amongst other things.
  8169. */
  8170. class Ray {
  8171. /**
  8172. * Constructs a new ray.
  8173. *
  8174. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8175. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8176. */
  8177. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8178. /**
  8179. * The origin of the ray.
  8180. *
  8181. * @type {Vector3}
  8182. */
  8183. this.origin = origin;
  8184. /**
  8185. * The (normalized) direction of the ray.
  8186. *
  8187. * @type {Vector3}
  8188. */
  8189. this.direction = direction;
  8190. }
  8191. /**
  8192. * Sets the ray's components by copying the given values.
  8193. *
  8194. * @param {Vector3} origin - The origin.
  8195. * @param {Vector3} direction - The direction.
  8196. * @return {Ray} A reference to this ray.
  8197. */
  8198. set( origin, direction ) {
  8199. this.origin.copy( origin );
  8200. this.direction.copy( direction );
  8201. return this;
  8202. }
  8203. /**
  8204. * Copies the values of the given ray to this instance.
  8205. *
  8206. * @param {Ray} ray - The ray to copy.
  8207. * @return {Ray} A reference to this ray.
  8208. */
  8209. copy( ray ) {
  8210. this.origin.copy( ray.origin );
  8211. this.direction.copy( ray.direction );
  8212. return this;
  8213. }
  8214. /**
  8215. * Returns a vector that is located at a given distance along this ray.
  8216. *
  8217. * @param {number} t - The distance along the ray to retrieve a position for.
  8218. * @param {Vector3} target - The target vector that is used to store the method's result.
  8219. * @return {Vector3} A position on the ray.
  8220. */
  8221. at( t, target ) {
  8222. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8223. }
  8224. /**
  8225. * Adjusts the direction of the ray to point at the given vector in world space.
  8226. *
  8227. * @param {Vector3} v - The target position.
  8228. * @return {Ray} A reference to this ray.
  8229. */
  8230. lookAt( v ) {
  8231. this.direction.copy( v ).sub( this.origin ).normalize();
  8232. return this;
  8233. }
  8234. /**
  8235. * Shift the origin of this ray along its direction by the given distance.
  8236. *
  8237. * @param {number} t - The distance along the ray to interpolate.
  8238. * @return {Ray} A reference to this ray.
  8239. */
  8240. recast( t ) {
  8241. this.origin.copy( this.at( t, _vector$a ) );
  8242. return this;
  8243. }
  8244. /**
  8245. * Returns the point along this ray that is closest to the given point.
  8246. *
  8247. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8248. * @param {Vector3} target - The target vector that is used to store the method's result.
  8249. * @return {Vector3} The closest point on this ray.
  8250. */
  8251. closestPointToPoint( point, target ) {
  8252. target.subVectors( point, this.origin );
  8253. const directionDistance = target.dot( this.direction );
  8254. if ( directionDistance < 0 ) {
  8255. return target.copy( this.origin );
  8256. }
  8257. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8258. }
  8259. /**
  8260. * Returns the distance of the closest approach between this ray and the given point.
  8261. *
  8262. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8263. * @return {number} The distance.
  8264. */
  8265. distanceToPoint( point ) {
  8266. return Math.sqrt( this.distanceSqToPoint( point ) );
  8267. }
  8268. /**
  8269. * Returns the squared distance of the closest approach between this ray and the given point.
  8270. *
  8271. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8272. * @return {number} The squared distance.
  8273. */
  8274. distanceSqToPoint( point ) {
  8275. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8276. // point behind the ray
  8277. if ( directionDistance < 0 ) {
  8278. return this.origin.distanceToSquared( point );
  8279. }
  8280. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8281. return _vector$a.distanceToSquared( point );
  8282. }
  8283. /**
  8284. * Returns the squared distance between this ray and the given line segment.
  8285. *
  8286. * @param {Vector3} v0 - The start point of the line segment.
  8287. * @param {Vector3} v1 - The end point of the line segment.
  8288. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8289. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8290. * @return {number} The squared distance.
  8291. */
  8292. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8293. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8294. // It returns the min distance between the ray and the segment
  8295. // defined by v0 and v1
  8296. // It can also set two optional targets :
  8297. // - The closest point on the ray
  8298. // - The closest point on the segment
  8299. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8300. _segDir.copy( v1 ).sub( v0 ).normalize();
  8301. _diff.copy( this.origin ).sub( _segCenter );
  8302. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8303. const a01 = - this.direction.dot( _segDir );
  8304. const b0 = _diff.dot( this.direction );
  8305. const b1 = - _diff.dot( _segDir );
  8306. const c = _diff.lengthSq();
  8307. const det = Math.abs( 1 - a01 * a01 );
  8308. let s0, s1, sqrDist, extDet;
  8309. if ( det > 0 ) {
  8310. // The ray and segment are not parallel.
  8311. s0 = a01 * b1 - b0;
  8312. s1 = a01 * b0 - b1;
  8313. extDet = segExtent * det;
  8314. if ( s0 >= 0 ) {
  8315. if ( s1 >= - extDet ) {
  8316. if ( s1 <= extDet ) {
  8317. // region 0
  8318. // Minimum at interior points of ray and segment.
  8319. const invDet = 1 / det;
  8320. s0 *= invDet;
  8321. s1 *= invDet;
  8322. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8323. } else {
  8324. // region 1
  8325. s1 = segExtent;
  8326. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8327. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8328. }
  8329. } else {
  8330. // region 5
  8331. s1 = - segExtent;
  8332. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8333. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8334. }
  8335. } else {
  8336. if ( s1 <= - extDet ) {
  8337. // region 4
  8338. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8339. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8340. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8341. } else if ( s1 <= extDet ) {
  8342. // region 3
  8343. s0 = 0;
  8344. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8345. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8346. } else {
  8347. // region 2
  8348. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8349. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8350. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8351. }
  8352. }
  8353. } else {
  8354. // Ray and segment are parallel.
  8355. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8356. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8357. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8358. }
  8359. if ( optionalPointOnRay ) {
  8360. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8361. }
  8362. if ( optionalPointOnSegment ) {
  8363. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8364. }
  8365. return sqrDist;
  8366. }
  8367. /**
  8368. * Intersects this ray with the given sphere, returning the intersection
  8369. * point or `null` if there is no intersection.
  8370. *
  8371. * @param {Sphere} sphere - The sphere to intersect.
  8372. * @param {Vector3} target - The target vector that is used to store the method's result.
  8373. * @return {?Vector3} The intersection point.
  8374. */
  8375. intersectSphere( sphere, target ) {
  8376. _vector$a.subVectors( sphere.center, this.origin );
  8377. const tca = _vector$a.dot( this.direction );
  8378. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8379. const radius2 = sphere.radius * sphere.radius;
  8380. if ( d2 > radius2 ) return null;
  8381. const thc = Math.sqrt( radius2 - d2 );
  8382. // t0 = first intersect point - entrance on front of sphere
  8383. const t0 = tca - thc;
  8384. // t1 = second intersect point - exit point on back of sphere
  8385. const t1 = tca + thc;
  8386. // test to see if t1 is behind the ray - if so, return null
  8387. if ( t1 < 0 ) return null;
  8388. // test to see if t0 is behind the ray:
  8389. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8390. // in order to always return an intersect point that is in front of the ray.
  8391. if ( t0 < 0 ) return this.at( t1, target );
  8392. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8393. return this.at( t0, target );
  8394. }
  8395. /**
  8396. * Returns `true` if this ray intersects with the given sphere.
  8397. *
  8398. * @param {Sphere} sphere - The sphere to intersect.
  8399. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8400. */
  8401. intersectsSphere( sphere ) {
  8402. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8403. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8404. }
  8405. /**
  8406. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8407. * does not intersect with the plane.
  8408. *
  8409. * @param {Plane} plane - The plane to compute the distance to.
  8410. * @return {?number} Whether this ray intersects with the given sphere or not.
  8411. */
  8412. distanceToPlane( plane ) {
  8413. const denominator = plane.normal.dot( this.direction );
  8414. if ( denominator === 0 ) {
  8415. // line is coplanar, return origin
  8416. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8417. return 0;
  8418. }
  8419. // Null is preferable to undefined since undefined means.... it is undefined
  8420. return null;
  8421. }
  8422. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8423. // Return if the ray never intersects the plane
  8424. return t >= 0 ? t : null;
  8425. }
  8426. /**
  8427. * Intersects this ray with the given plane, returning the intersection
  8428. * point or `null` if there is no intersection.
  8429. *
  8430. * @param {Plane} plane - The plane to intersect.
  8431. * @param {Vector3} target - The target vector that is used to store the method's result.
  8432. * @return {?Vector3} The intersection point.
  8433. */
  8434. intersectPlane( plane, target ) {
  8435. const t = this.distanceToPlane( plane );
  8436. if ( t === null ) {
  8437. return null;
  8438. }
  8439. return this.at( t, target );
  8440. }
  8441. /**
  8442. * Returns `true` if this ray intersects with the given plane.
  8443. *
  8444. * @param {Plane} plane - The plane to intersect.
  8445. * @return {boolean} Whether this ray intersects with the given plane or not.
  8446. */
  8447. intersectsPlane( plane ) {
  8448. // check if the ray lies on the plane first
  8449. const distToPoint = plane.distanceToPoint( this.origin );
  8450. if ( distToPoint === 0 ) {
  8451. return true;
  8452. }
  8453. const denominator = plane.normal.dot( this.direction );
  8454. if ( denominator * distToPoint < 0 ) {
  8455. return true;
  8456. }
  8457. // ray origin is behind the plane (and is pointing behind it)
  8458. return false;
  8459. }
  8460. /**
  8461. * Intersects this ray with the given bounding box, returning the intersection
  8462. * point or `null` if there is no intersection.
  8463. *
  8464. * @param {Box3} box - The box to intersect.
  8465. * @param {Vector3} target - The target vector that is used to store the method's result.
  8466. * @return {?Vector3} The intersection point.
  8467. */
  8468. intersectBox( box, target ) {
  8469. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8470. const invdirx = 1 / this.direction.x,
  8471. invdiry = 1 / this.direction.y,
  8472. invdirz = 1 / this.direction.z;
  8473. const origin = this.origin;
  8474. if ( invdirx >= 0 ) {
  8475. tmin = ( box.min.x - origin.x ) * invdirx;
  8476. tmax = ( box.max.x - origin.x ) * invdirx;
  8477. } else {
  8478. tmin = ( box.max.x - origin.x ) * invdirx;
  8479. tmax = ( box.min.x - origin.x ) * invdirx;
  8480. }
  8481. if ( invdiry >= 0 ) {
  8482. tymin = ( box.min.y - origin.y ) * invdiry;
  8483. tymax = ( box.max.y - origin.y ) * invdiry;
  8484. } else {
  8485. tymin = ( box.max.y - origin.y ) * invdiry;
  8486. tymax = ( box.min.y - origin.y ) * invdiry;
  8487. }
  8488. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8489. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8490. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8491. if ( invdirz >= 0 ) {
  8492. tzmin = ( box.min.z - origin.z ) * invdirz;
  8493. tzmax = ( box.max.z - origin.z ) * invdirz;
  8494. } else {
  8495. tzmin = ( box.max.z - origin.z ) * invdirz;
  8496. tzmax = ( box.min.z - origin.z ) * invdirz;
  8497. }
  8498. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8499. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8500. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8501. //return point closest to the ray (positive side)
  8502. if ( tmax < 0 ) return null;
  8503. return this.at( tmin >= 0 ? tmin : tmax, target );
  8504. }
  8505. /**
  8506. * Returns `true` if this ray intersects with the given box.
  8507. *
  8508. * @param {Box3} box - The box to intersect.
  8509. * @return {boolean} Whether this ray intersects with the given box or not.
  8510. */
  8511. intersectsBox( box ) {
  8512. return this.intersectBox( box, _vector$a ) !== null;
  8513. }
  8514. /**
  8515. * Intersects this ray with the given triangle, returning the intersection
  8516. * point or `null` if there is no intersection.
  8517. *
  8518. * @param {Vector3} a - The first vertex of the triangle.
  8519. * @param {Vector3} b - The second vertex of the triangle.
  8520. * @param {Vector3} c - The third vertex of the triangle.
  8521. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8522. * @param {Vector3} target - The target vector that is used to store the method's result.
  8523. * @return {?Vector3} The intersection point.
  8524. */
  8525. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8526. // Compute the offset origin, edges, and normal.
  8527. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8528. _edge1.subVectors( b, a );
  8529. _edge2.subVectors( c, a );
  8530. _normal$1.crossVectors( _edge1, _edge2 );
  8531. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8532. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8533. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8534. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8535. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8536. let DdN = this.direction.dot( _normal$1 );
  8537. let sign;
  8538. if ( DdN > 0 ) {
  8539. if ( backfaceCulling ) return null;
  8540. sign = 1;
  8541. } else if ( DdN < 0 ) {
  8542. sign = -1;
  8543. DdN = - DdN;
  8544. } else {
  8545. return null;
  8546. }
  8547. _diff.subVectors( this.origin, a );
  8548. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8549. // b1 < 0, no intersection
  8550. if ( DdQxE2 < 0 ) {
  8551. return null;
  8552. }
  8553. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8554. // b2 < 0, no intersection
  8555. if ( DdE1xQ < 0 ) {
  8556. return null;
  8557. }
  8558. // b1+b2 > 1, no intersection
  8559. if ( DdQxE2 + DdE1xQ > DdN ) {
  8560. return null;
  8561. }
  8562. // Line intersects triangle, check if ray does.
  8563. const QdN = - sign * _diff.dot( _normal$1 );
  8564. // t < 0, no intersection
  8565. if ( QdN < 0 ) {
  8566. return null;
  8567. }
  8568. // Ray intersects triangle.
  8569. return this.at( QdN / DdN, target );
  8570. }
  8571. /**
  8572. * Transforms this ray with the given 4x4 transformation matrix.
  8573. *
  8574. * @param {Matrix4} matrix4 - The transformation matrix.
  8575. * @return {Ray} A reference to this ray.
  8576. */
  8577. applyMatrix4( matrix4 ) {
  8578. this.origin.applyMatrix4( matrix4 );
  8579. this.direction.transformDirection( matrix4 );
  8580. return this;
  8581. }
  8582. /**
  8583. * Returns `true` if this ray is equal with the given one.
  8584. *
  8585. * @param {Ray} ray - The ray to test for equality.
  8586. * @return {boolean} Whether this ray is equal with the given one.
  8587. */
  8588. equals( ray ) {
  8589. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8590. }
  8591. /**
  8592. * Returns a new ray with copied values from this instance.
  8593. *
  8594. * @return {Ray} A clone of this instance.
  8595. */
  8596. clone() {
  8597. return new this.constructor().copy( this );
  8598. }
  8599. }
  8600. /**
  8601. * Represents a 4x4 matrix.
  8602. *
  8603. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8604. * 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}
  8605. *
  8606. * This allows a 3D vector representing a point in 3D space to undergo
  8607. * transformations such as translation, rotation, shear, scale, reflection,
  8608. * orthogonal or perspective projection and so on, by being multiplied by the
  8609. * matrix. This is known as `applying` the matrix to the vector.
  8610. *
  8611. * A Note on Row-Major and Column-Major Ordering:
  8612. *
  8613. * The constructor and {@link Matrix3#set} method take arguments in
  8614. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8615. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8616. * This means that calling:
  8617. * ```js
  8618. * const m = new THREE.Matrix4();
  8619. * m.set( 11, 12, 13, 14,
  8620. * 21, 22, 23, 24,
  8621. * 31, 32, 33, 34,
  8622. * 41, 42, 43, 44 );
  8623. * ```
  8624. * will result in the elements array containing:
  8625. * ```js
  8626. * m.elements = [ 11, 21, 31, 41,
  8627. * 12, 22, 32, 42,
  8628. * 13, 23, 33, 43,
  8629. * 14, 24, 34, 44 ];
  8630. * ```
  8631. * and internally all calculations are performed using column-major ordering.
  8632. * However, as the actual ordering makes no difference mathematically and
  8633. * most people are used to thinking about matrices in row-major order, the
  8634. * three.js documentation shows matrices in row-major order. Just bear in
  8635. * mind that if you are reading the source code, you'll have to take the
  8636. * transpose of any matrices outlined here to make sense of the calculations.
  8637. */
  8638. class Matrix4 {
  8639. /**
  8640. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8641. * in row-major order. If no arguments are provided, the constructor
  8642. * initializes the matrix as an identity matrix.
  8643. *
  8644. * @param {number} [n11] - 1-1 matrix element.
  8645. * @param {number} [n12] - 1-2 matrix element.
  8646. * @param {number} [n13] - 1-3 matrix element.
  8647. * @param {number} [n14] - 1-4 matrix element.
  8648. * @param {number} [n21] - 2-1 matrix element.
  8649. * @param {number} [n22] - 2-2 matrix element.
  8650. * @param {number} [n23] - 2-3 matrix element.
  8651. * @param {number} [n24] - 2-4 matrix element.
  8652. * @param {number} [n31] - 3-1 matrix element.
  8653. * @param {number} [n32] - 3-2 matrix element.
  8654. * @param {number} [n33] - 3-3 matrix element.
  8655. * @param {number} [n34] - 3-4 matrix element.
  8656. * @param {number} [n41] - 4-1 matrix element.
  8657. * @param {number} [n42] - 4-2 matrix element.
  8658. * @param {number} [n43] - 4-3 matrix element.
  8659. * @param {number} [n44] - 4-4 matrix element.
  8660. */
  8661. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8662. /**
  8663. * This flag can be used for type testing.
  8664. *
  8665. * @type {boolean}
  8666. * @readonly
  8667. * @default true
  8668. */
  8669. Matrix4.prototype.isMatrix4 = true;
  8670. /**
  8671. * A column-major list of matrix values.
  8672. *
  8673. * @type {Array<number>}
  8674. */
  8675. this.elements = [
  8676. 1, 0, 0, 0,
  8677. 0, 1, 0, 0,
  8678. 0, 0, 1, 0,
  8679. 0, 0, 0, 1
  8680. ];
  8681. if ( n11 !== undefined ) {
  8682. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8683. }
  8684. }
  8685. /**
  8686. * Sets the elements of the matrix.The arguments are supposed to be
  8687. * in row-major order.
  8688. *
  8689. * @param {number} [n11] - 1-1 matrix element.
  8690. * @param {number} [n12] - 1-2 matrix element.
  8691. * @param {number} [n13] - 1-3 matrix element.
  8692. * @param {number} [n14] - 1-4 matrix element.
  8693. * @param {number} [n21] - 2-1 matrix element.
  8694. * @param {number} [n22] - 2-2 matrix element.
  8695. * @param {number} [n23] - 2-3 matrix element.
  8696. * @param {number} [n24] - 2-4 matrix element.
  8697. * @param {number} [n31] - 3-1 matrix element.
  8698. * @param {number} [n32] - 3-2 matrix element.
  8699. * @param {number} [n33] - 3-3 matrix element.
  8700. * @param {number} [n34] - 3-4 matrix element.
  8701. * @param {number} [n41] - 4-1 matrix element.
  8702. * @param {number} [n42] - 4-2 matrix element.
  8703. * @param {number} [n43] - 4-3 matrix element.
  8704. * @param {number} [n44] - 4-4 matrix element.
  8705. * @return {Matrix4} A reference to this matrix.
  8706. */
  8707. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8708. const te = this.elements;
  8709. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8710. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8711. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8712. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8713. return this;
  8714. }
  8715. /**
  8716. * Sets this matrix to the 4x4 identity matrix.
  8717. *
  8718. * @return {Matrix4} A reference to this matrix.
  8719. */
  8720. identity() {
  8721. this.set(
  8722. 1, 0, 0, 0,
  8723. 0, 1, 0, 0,
  8724. 0, 0, 1, 0,
  8725. 0, 0, 0, 1
  8726. );
  8727. return this;
  8728. }
  8729. /**
  8730. * Returns a matrix with copied values from this instance.
  8731. *
  8732. * @return {Matrix4} A clone of this instance.
  8733. */
  8734. clone() {
  8735. return new Matrix4().fromArray( this.elements );
  8736. }
  8737. /**
  8738. * Copies the values of the given matrix to this instance.
  8739. *
  8740. * @param {Matrix4} m - The matrix to copy.
  8741. * @return {Matrix4} A reference to this matrix.
  8742. */
  8743. copy( m ) {
  8744. const te = this.elements;
  8745. const me = m.elements;
  8746. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8747. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8748. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8749. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8750. return this;
  8751. }
  8752. /**
  8753. * Copies the translation component of the given matrix
  8754. * into this matrix's translation component.
  8755. *
  8756. * @param {Matrix4} m - The matrix to copy the translation component.
  8757. * @return {Matrix4} A reference to this matrix.
  8758. */
  8759. copyPosition( m ) {
  8760. const te = this.elements, me = m.elements;
  8761. te[ 12 ] = me[ 12 ];
  8762. te[ 13 ] = me[ 13 ];
  8763. te[ 14 ] = me[ 14 ];
  8764. return this;
  8765. }
  8766. /**
  8767. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8768. *
  8769. * @param {Matrix3} m - The 3x3 matrix.
  8770. * @return {Matrix4} A reference to this matrix.
  8771. */
  8772. setFromMatrix3( m ) {
  8773. const me = m.elements;
  8774. this.set(
  8775. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8776. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8777. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8778. 0, 0, 0, 1
  8779. );
  8780. return this;
  8781. }
  8782. /**
  8783. * Extracts the basis of this matrix into the three axis vectors provided.
  8784. *
  8785. * @param {Vector3} xAxis - The basis's x axis.
  8786. * @param {Vector3} yAxis - The basis's y axis.
  8787. * @param {Vector3} zAxis - The basis's z axis.
  8788. * @return {Matrix4} A reference to this matrix.
  8789. */
  8790. extractBasis( xAxis, yAxis, zAxis ) {
  8791. xAxis.setFromMatrixColumn( this, 0 );
  8792. yAxis.setFromMatrixColumn( this, 1 );
  8793. zAxis.setFromMatrixColumn( this, 2 );
  8794. return this;
  8795. }
  8796. /**
  8797. * Sets the given basis vectors to this matrix.
  8798. *
  8799. * @param {Vector3} xAxis - The basis's x axis.
  8800. * @param {Vector3} yAxis - The basis's y axis.
  8801. * @param {Vector3} zAxis - The basis's z axis.
  8802. * @return {Matrix4} A reference to this matrix.
  8803. */
  8804. makeBasis( xAxis, yAxis, zAxis ) {
  8805. this.set(
  8806. xAxis.x, yAxis.x, zAxis.x, 0,
  8807. xAxis.y, yAxis.y, zAxis.y, 0,
  8808. xAxis.z, yAxis.z, zAxis.z, 0,
  8809. 0, 0, 0, 1
  8810. );
  8811. return this;
  8812. }
  8813. /**
  8814. * Extracts the rotation component of the given matrix
  8815. * into this matrix's rotation component.
  8816. *
  8817. * Note: This method does not support reflection matrices.
  8818. *
  8819. * @param {Matrix4} m - The matrix.
  8820. * @return {Matrix4} A reference to this matrix.
  8821. */
  8822. extractRotation( m ) {
  8823. const te = this.elements;
  8824. const me = m.elements;
  8825. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8826. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8827. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8828. te[ 0 ] = me[ 0 ] * scaleX;
  8829. te[ 1 ] = me[ 1 ] * scaleX;
  8830. te[ 2 ] = me[ 2 ] * scaleX;
  8831. te[ 3 ] = 0;
  8832. te[ 4 ] = me[ 4 ] * scaleY;
  8833. te[ 5 ] = me[ 5 ] * scaleY;
  8834. te[ 6 ] = me[ 6 ] * scaleY;
  8835. te[ 7 ] = 0;
  8836. te[ 8 ] = me[ 8 ] * scaleZ;
  8837. te[ 9 ] = me[ 9 ] * scaleZ;
  8838. te[ 10 ] = me[ 10 ] * scaleZ;
  8839. te[ 11 ] = 0;
  8840. te[ 12 ] = 0;
  8841. te[ 13 ] = 0;
  8842. te[ 14 ] = 0;
  8843. te[ 15 ] = 1;
  8844. return this;
  8845. }
  8846. /**
  8847. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8848. * the rotation specified by the given Euler angles. The rest of
  8849. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8850. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8851. * for a complete list.
  8852. *
  8853. * @param {Euler} euler - The Euler angles.
  8854. * @return {Matrix4} A reference to this matrix.
  8855. */
  8856. makeRotationFromEuler( euler ) {
  8857. const te = this.elements;
  8858. const x = euler.x, y = euler.y, z = euler.z;
  8859. const a = Math.cos( x ), b = Math.sin( x );
  8860. const c = Math.cos( y ), d = Math.sin( y );
  8861. const e = Math.cos( z ), f = Math.sin( z );
  8862. if ( euler.order === 'XYZ' ) {
  8863. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8864. te[ 0 ] = c * e;
  8865. te[ 4 ] = - c * f;
  8866. te[ 8 ] = d;
  8867. te[ 1 ] = af + be * d;
  8868. te[ 5 ] = ae - bf * d;
  8869. te[ 9 ] = - b * c;
  8870. te[ 2 ] = bf - ae * d;
  8871. te[ 6 ] = be + af * d;
  8872. te[ 10 ] = a * c;
  8873. } else if ( euler.order === 'YXZ' ) {
  8874. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8875. te[ 0 ] = ce + df * b;
  8876. te[ 4 ] = de * b - cf;
  8877. te[ 8 ] = a * d;
  8878. te[ 1 ] = a * f;
  8879. te[ 5 ] = a * e;
  8880. te[ 9 ] = - b;
  8881. te[ 2 ] = cf * b - de;
  8882. te[ 6 ] = df + ce * b;
  8883. te[ 10 ] = a * c;
  8884. } else if ( euler.order === 'ZXY' ) {
  8885. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8886. te[ 0 ] = ce - df * b;
  8887. te[ 4 ] = - a * f;
  8888. te[ 8 ] = de + cf * b;
  8889. te[ 1 ] = cf + de * b;
  8890. te[ 5 ] = a * e;
  8891. te[ 9 ] = df - ce * b;
  8892. te[ 2 ] = - a * d;
  8893. te[ 6 ] = b;
  8894. te[ 10 ] = a * c;
  8895. } else if ( euler.order === 'ZYX' ) {
  8896. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8897. te[ 0 ] = c * e;
  8898. te[ 4 ] = be * d - af;
  8899. te[ 8 ] = ae * d + bf;
  8900. te[ 1 ] = c * f;
  8901. te[ 5 ] = bf * d + ae;
  8902. te[ 9 ] = af * d - be;
  8903. te[ 2 ] = - d;
  8904. te[ 6 ] = b * c;
  8905. te[ 10 ] = a * c;
  8906. } else if ( euler.order === 'YZX' ) {
  8907. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8908. te[ 0 ] = c * e;
  8909. te[ 4 ] = bd - ac * f;
  8910. te[ 8 ] = bc * f + ad;
  8911. te[ 1 ] = f;
  8912. te[ 5 ] = a * e;
  8913. te[ 9 ] = - b * e;
  8914. te[ 2 ] = - d * e;
  8915. te[ 6 ] = ad * f + bc;
  8916. te[ 10 ] = ac - bd * f;
  8917. } else if ( euler.order === 'XZY' ) {
  8918. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8919. te[ 0 ] = c * e;
  8920. te[ 4 ] = - f;
  8921. te[ 8 ] = d * e;
  8922. te[ 1 ] = ac * f + bd;
  8923. te[ 5 ] = a * e;
  8924. te[ 9 ] = ad * f - bc;
  8925. te[ 2 ] = bc * f - ad;
  8926. te[ 6 ] = b * e;
  8927. te[ 10 ] = bd * f + ac;
  8928. }
  8929. // bottom row
  8930. te[ 3 ] = 0;
  8931. te[ 7 ] = 0;
  8932. te[ 11 ] = 0;
  8933. // last column
  8934. te[ 12 ] = 0;
  8935. te[ 13 ] = 0;
  8936. te[ 14 ] = 0;
  8937. te[ 15 ] = 1;
  8938. return this;
  8939. }
  8940. /**
  8941. * Sets the rotation component of this matrix to the rotation specified by
  8942. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8943. * The rest of the matrix is set to the identity.
  8944. *
  8945. * @param {Quaternion} q - The Quaternion.
  8946. * @return {Matrix4} A reference to this matrix.
  8947. */
  8948. makeRotationFromQuaternion( q ) {
  8949. return this.compose( _zero, q, _one );
  8950. }
  8951. /**
  8952. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8953. * `target`, and oriented by the up-direction.
  8954. *
  8955. * @param {Vector3} eye - The eye vector.
  8956. * @param {Vector3} target - The target vector.
  8957. * @param {Vector3} up - The up vector.
  8958. * @return {Matrix4} A reference to this matrix.
  8959. */
  8960. lookAt( eye, target, up ) {
  8961. const te = this.elements;
  8962. _z.subVectors( eye, target );
  8963. if ( _z.lengthSq() === 0 ) {
  8964. // eye and target are in the same position
  8965. _z.z = 1;
  8966. }
  8967. _z.normalize();
  8968. _x.crossVectors( up, _z );
  8969. if ( _x.lengthSq() === 0 ) {
  8970. // up and z are parallel
  8971. if ( Math.abs( up.z ) === 1 ) {
  8972. _z.x += 0.0001;
  8973. } else {
  8974. _z.z += 0.0001;
  8975. }
  8976. _z.normalize();
  8977. _x.crossVectors( up, _z );
  8978. }
  8979. _x.normalize();
  8980. _y.crossVectors( _z, _x );
  8981. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8982. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8983. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8984. return this;
  8985. }
  8986. /**
  8987. * Post-multiplies this matrix by the given 4x4 matrix.
  8988. *
  8989. * @param {Matrix4} m - The matrix to multiply with.
  8990. * @return {Matrix4} A reference to this matrix.
  8991. */
  8992. multiply( m ) {
  8993. return this.multiplyMatrices( this, m );
  8994. }
  8995. /**
  8996. * Pre-multiplies this matrix by the given 4x4 matrix.
  8997. *
  8998. * @param {Matrix4} m - The matrix to multiply with.
  8999. * @return {Matrix4} A reference to this matrix.
  9000. */
  9001. premultiply( m ) {
  9002. return this.multiplyMatrices( m, this );
  9003. }
  9004. /**
  9005. * Multiples the given 4x4 matrices and stores the result
  9006. * in this matrix.
  9007. *
  9008. * @param {Matrix4} a - The first matrix.
  9009. * @param {Matrix4} b - The second matrix.
  9010. * @return {Matrix4} A reference to this matrix.
  9011. */
  9012. multiplyMatrices( a, b ) {
  9013. const ae = a.elements;
  9014. const be = b.elements;
  9015. const te = this.elements;
  9016. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9017. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9018. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9019. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9020. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9021. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9022. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9023. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9024. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9025. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9026. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9027. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9028. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9029. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9030. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9031. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9032. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9033. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9034. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9035. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9036. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9037. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9038. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9039. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9040. return this;
  9041. }
  9042. /**
  9043. * Multiplies every component of the matrix by the given scalar.
  9044. *
  9045. * @param {number} s - The scalar.
  9046. * @return {Matrix4} A reference to this matrix.
  9047. */
  9048. multiplyScalar( s ) {
  9049. const te = this.elements;
  9050. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9051. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9052. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9053. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9054. return this;
  9055. }
  9056. /**
  9057. * Computes and returns the determinant of this matrix.
  9058. *
  9059. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9060. *
  9061. * @return {number} The determinant.
  9062. */
  9063. determinant() {
  9064. const te = this.elements;
  9065. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9066. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9067. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9068. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9069. //TODO: make this more efficient
  9070. return (
  9071. n41 * (
  9072. + n14 * n23 * n32
  9073. - n13 * n24 * n32
  9074. - n14 * n22 * n33
  9075. + n12 * n24 * n33
  9076. + n13 * n22 * n34
  9077. - n12 * n23 * n34
  9078. ) +
  9079. n42 * (
  9080. + n11 * n23 * n34
  9081. - n11 * n24 * n33
  9082. + n14 * n21 * n33
  9083. - n13 * n21 * n34
  9084. + n13 * n24 * n31
  9085. - n14 * n23 * n31
  9086. ) +
  9087. n43 * (
  9088. + n11 * n24 * n32
  9089. - n11 * n22 * n34
  9090. - n14 * n21 * n32
  9091. + n12 * n21 * n34
  9092. + n14 * n22 * n31
  9093. - n12 * n24 * n31
  9094. ) +
  9095. n44 * (
  9096. - n13 * n22 * n31
  9097. - n11 * n23 * n32
  9098. + n11 * n22 * n33
  9099. + n13 * n21 * n32
  9100. - n12 * n21 * n33
  9101. + n12 * n23 * n31
  9102. )
  9103. );
  9104. }
  9105. /**
  9106. * Transposes this matrix in place.
  9107. *
  9108. * @return {Matrix4} A reference to this matrix.
  9109. */
  9110. transpose() {
  9111. const te = this.elements;
  9112. let tmp;
  9113. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9114. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9115. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9116. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9117. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9118. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9119. return this;
  9120. }
  9121. /**
  9122. * Sets the position component for this matrix from the given vector,
  9123. * without affecting the rest of the matrix.
  9124. *
  9125. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9126. * @param {number} y - The y component of the vector.
  9127. * @param {number} z - The z component of the vector.
  9128. * @return {Matrix4} A reference to this matrix.
  9129. */
  9130. setPosition( x, y, z ) {
  9131. const te = this.elements;
  9132. if ( x.isVector3 ) {
  9133. te[ 12 ] = x.x;
  9134. te[ 13 ] = x.y;
  9135. te[ 14 ] = x.z;
  9136. } else {
  9137. te[ 12 ] = x;
  9138. te[ 13 ] = y;
  9139. te[ 14 ] = z;
  9140. }
  9141. return this;
  9142. }
  9143. /**
  9144. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9145. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9146. * a zero matrix instead.
  9147. *
  9148. * @return {Matrix4} A reference to this matrix.
  9149. */
  9150. invert() {
  9151. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9152. const te = this.elements,
  9153. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9154. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9155. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9156. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9157. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9158. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9159. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9160. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9161. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9162. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9163. const detInv = 1 / det;
  9164. te[ 0 ] = t11 * detInv;
  9165. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9166. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9167. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9168. te[ 4 ] = t12 * detInv;
  9169. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9170. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9171. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9172. te[ 8 ] = t13 * detInv;
  9173. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9174. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9175. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9176. te[ 12 ] = t14 * detInv;
  9177. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9178. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9179. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9180. return this;
  9181. }
  9182. /**
  9183. * Multiplies the columns of this matrix by the given vector.
  9184. *
  9185. * @param {Vector3} v - The scale vector.
  9186. * @return {Matrix4} A reference to this matrix.
  9187. */
  9188. scale( v ) {
  9189. const te = this.elements;
  9190. const x = v.x, y = v.y, z = v.z;
  9191. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9192. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9193. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9194. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9195. return this;
  9196. }
  9197. /**
  9198. * Gets the maximum scale value of the three axes.
  9199. *
  9200. * @return {number} The maximum scale.
  9201. */
  9202. getMaxScaleOnAxis() {
  9203. const te = this.elements;
  9204. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9205. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9206. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9207. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9208. }
  9209. /**
  9210. * Sets this matrix as a translation transform from the given vector.
  9211. *
  9212. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9213. * @param {number} y - The amount to translate in the Y axis.
  9214. * @param {number} z - The amount to translate in the z axis.
  9215. * @return {Matrix4} A reference to this matrix.
  9216. */
  9217. makeTranslation( x, y, z ) {
  9218. if ( x.isVector3 ) {
  9219. this.set(
  9220. 1, 0, 0, x.x,
  9221. 0, 1, 0, x.y,
  9222. 0, 0, 1, x.z,
  9223. 0, 0, 0, 1
  9224. );
  9225. } else {
  9226. this.set(
  9227. 1, 0, 0, x,
  9228. 0, 1, 0, y,
  9229. 0, 0, 1, z,
  9230. 0, 0, 0, 1
  9231. );
  9232. }
  9233. return this;
  9234. }
  9235. /**
  9236. * Sets this matrix as a rotational transformation around the X axis by
  9237. * the given angle.
  9238. *
  9239. * @param {number} theta - The rotation in radians.
  9240. * @return {Matrix4} A reference to this matrix.
  9241. */
  9242. makeRotationX( theta ) {
  9243. const c = Math.cos( theta ), s = Math.sin( theta );
  9244. this.set(
  9245. 1, 0, 0, 0,
  9246. 0, c, - s, 0,
  9247. 0, s, c, 0,
  9248. 0, 0, 0, 1
  9249. );
  9250. return this;
  9251. }
  9252. /**
  9253. * Sets this matrix as a rotational transformation around the Y axis by
  9254. * the given angle.
  9255. *
  9256. * @param {number} theta - The rotation in radians.
  9257. * @return {Matrix4} A reference to this matrix.
  9258. */
  9259. makeRotationY( theta ) {
  9260. const c = Math.cos( theta ), s = Math.sin( theta );
  9261. this.set(
  9262. c, 0, s, 0,
  9263. 0, 1, 0, 0,
  9264. - s, 0, c, 0,
  9265. 0, 0, 0, 1
  9266. );
  9267. return this;
  9268. }
  9269. /**
  9270. * Sets this matrix as a rotational transformation around the Z axis by
  9271. * the given angle.
  9272. *
  9273. * @param {number} theta - The rotation in radians.
  9274. * @return {Matrix4} A reference to this matrix.
  9275. */
  9276. makeRotationZ( theta ) {
  9277. const c = Math.cos( theta ), s = Math.sin( theta );
  9278. this.set(
  9279. c, - s, 0, 0,
  9280. s, c, 0, 0,
  9281. 0, 0, 1, 0,
  9282. 0, 0, 0, 1
  9283. );
  9284. return this;
  9285. }
  9286. /**
  9287. * Sets this matrix as a rotational transformation around the given axis by
  9288. * the given angle.
  9289. *
  9290. * This is a somewhat controversial but mathematically sound alternative to
  9291. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9292. *
  9293. * @param {Vector3} axis - The normalized rotation axis.
  9294. * @param {number} angle - The rotation in radians.
  9295. * @return {Matrix4} A reference to this matrix.
  9296. */
  9297. makeRotationAxis( axis, angle ) {
  9298. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9299. const c = Math.cos( angle );
  9300. const s = Math.sin( angle );
  9301. const t = 1 - c;
  9302. const x = axis.x, y = axis.y, z = axis.z;
  9303. const tx = t * x, ty = t * y;
  9304. this.set(
  9305. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9306. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9307. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9308. 0, 0, 0, 1
  9309. );
  9310. return this;
  9311. }
  9312. /**
  9313. * Sets this matrix as a scale transformation.
  9314. *
  9315. * @param {number} x - The amount to scale in the X axis.
  9316. * @param {number} y - The amount to scale in the Y axis.
  9317. * @param {number} z - The amount to scale in the Z axis.
  9318. * @return {Matrix4} A reference to this matrix.
  9319. */
  9320. makeScale( x, y, z ) {
  9321. this.set(
  9322. x, 0, 0, 0,
  9323. 0, y, 0, 0,
  9324. 0, 0, z, 0,
  9325. 0, 0, 0, 1
  9326. );
  9327. return this;
  9328. }
  9329. /**
  9330. * Sets this matrix as a shear transformation.
  9331. *
  9332. * @param {number} xy - The amount to shear X by Y.
  9333. * @param {number} xz - The amount to shear X by Z.
  9334. * @param {number} yx - The amount to shear Y by X.
  9335. * @param {number} yz - The amount to shear Y by Z.
  9336. * @param {number} zx - The amount to shear Z by X.
  9337. * @param {number} zy - The amount to shear Z by Y.
  9338. * @return {Matrix4} A reference to this matrix.
  9339. */
  9340. makeShear( xy, xz, yx, yz, zx, zy ) {
  9341. this.set(
  9342. 1, yx, zx, 0,
  9343. xy, 1, zy, 0,
  9344. xz, yz, 1, 0,
  9345. 0, 0, 0, 1
  9346. );
  9347. return this;
  9348. }
  9349. /**
  9350. * Sets this matrix to the transformation composed of the given position,
  9351. * rotation (Quaternion) and scale.
  9352. *
  9353. * @param {Vector3} position - The position vector.
  9354. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9355. * @param {Vector3} scale - The scale vector.
  9356. * @return {Matrix4} A reference to this matrix.
  9357. */
  9358. compose( position, quaternion, scale ) {
  9359. const te = this.elements;
  9360. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9361. const x2 = x + x, y2 = y + y, z2 = z + z;
  9362. const xx = x * x2, xy = x * y2, xz = x * z2;
  9363. const yy = y * y2, yz = y * z2, zz = z * z2;
  9364. const wx = w * x2, wy = w * y2, wz = w * z2;
  9365. const sx = scale.x, sy = scale.y, sz = scale.z;
  9366. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9367. te[ 1 ] = ( xy + wz ) * sx;
  9368. te[ 2 ] = ( xz - wy ) * sx;
  9369. te[ 3 ] = 0;
  9370. te[ 4 ] = ( xy - wz ) * sy;
  9371. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9372. te[ 6 ] = ( yz + wx ) * sy;
  9373. te[ 7 ] = 0;
  9374. te[ 8 ] = ( xz + wy ) * sz;
  9375. te[ 9 ] = ( yz - wx ) * sz;
  9376. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9377. te[ 11 ] = 0;
  9378. te[ 12 ] = position.x;
  9379. te[ 13 ] = position.y;
  9380. te[ 14 ] = position.z;
  9381. te[ 15 ] = 1;
  9382. return this;
  9383. }
  9384. /**
  9385. * Decomposes this matrix into its position, rotation and scale components
  9386. * and provides the result in the given objects.
  9387. *
  9388. * Note: Not all matrices are decomposable in this way. For example, if an
  9389. * object has a non-uniformly scaled parent, then the object's world matrix
  9390. * may not be decomposable, and this method may not be appropriate.
  9391. *
  9392. * @param {Vector3} position - The position vector.
  9393. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9394. * @param {Vector3} scale - The scale vector.
  9395. * @return {Matrix4} A reference to this matrix.
  9396. */
  9397. decompose( position, quaternion, scale ) {
  9398. const te = this.elements;
  9399. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9400. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9401. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9402. // if determine is negative, we need to invert one scale
  9403. const det = this.determinant();
  9404. if ( det < 0 ) sx = - sx;
  9405. position.x = te[ 12 ];
  9406. position.y = te[ 13 ];
  9407. position.z = te[ 14 ];
  9408. // scale the rotation part
  9409. _m1$4.copy( this );
  9410. const invSX = 1 / sx;
  9411. const invSY = 1 / sy;
  9412. const invSZ = 1 / sz;
  9413. _m1$4.elements[ 0 ] *= invSX;
  9414. _m1$4.elements[ 1 ] *= invSX;
  9415. _m1$4.elements[ 2 ] *= invSX;
  9416. _m1$4.elements[ 4 ] *= invSY;
  9417. _m1$4.elements[ 5 ] *= invSY;
  9418. _m1$4.elements[ 6 ] *= invSY;
  9419. _m1$4.elements[ 8 ] *= invSZ;
  9420. _m1$4.elements[ 9 ] *= invSZ;
  9421. _m1$4.elements[ 10 ] *= invSZ;
  9422. quaternion.setFromRotationMatrix( _m1$4 );
  9423. scale.x = sx;
  9424. scale.y = sy;
  9425. scale.z = sz;
  9426. return this;
  9427. }
  9428. /**
  9429. * Creates a perspective projection matrix. This is used internally by
  9430. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9431. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9432. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9433. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9434. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9435. * @param {number} near - The distance from the camera to the near plane.
  9436. * @param {number} far - The distance from the camera to the far plane.
  9437. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9438. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9439. * @return {Matrix4} A reference to this matrix.
  9440. */
  9441. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9442. const te = this.elements;
  9443. const x = 2 * near / ( right - left );
  9444. const y = 2 * near / ( top - bottom );
  9445. const a = ( right + left ) / ( right - left );
  9446. const b = ( top + bottom ) / ( top - bottom );
  9447. let c, d;
  9448. if ( reversedDepth ) {
  9449. c = near / ( far - near );
  9450. d = ( far * near ) / ( far - near );
  9451. } else {
  9452. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9453. c = - ( far + near ) / ( far - near );
  9454. d = ( -2 * far * near ) / ( far - near );
  9455. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9456. c = - far / ( far - near );
  9457. d = ( - far * near ) / ( far - near );
  9458. } else {
  9459. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9460. }
  9461. }
  9462. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9463. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9464. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9465. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9466. return this;
  9467. }
  9468. /**
  9469. * Creates a orthographic projection matrix. This is used internally by
  9470. * {@link OrthographicCamera#updateProjectionMatrix}.
  9471. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9472. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9473. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9474. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9475. * @param {number} near - The distance from the camera to the near plane.
  9476. * @param {number} far - The distance from the camera to the far plane.
  9477. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9478. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9479. * @return {Matrix4} A reference to this matrix.
  9480. */
  9481. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9482. const te = this.elements;
  9483. const x = 2 / ( right - left );
  9484. const y = 2 / ( top - bottom );
  9485. const a = - ( right + left ) / ( right - left );
  9486. const b = - ( top + bottom ) / ( top - bottom );
  9487. let c, d;
  9488. if ( reversedDepth ) {
  9489. c = 1 / ( far - near );
  9490. d = far / ( far - near );
  9491. } else {
  9492. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9493. c = -2 / ( far - near );
  9494. d = - ( far + near ) / ( far - near );
  9495. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9496. c = -1 / ( far - near );
  9497. d = - near / ( far - near );
  9498. } else {
  9499. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9500. }
  9501. }
  9502. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9503. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9504. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9505. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9506. return this;
  9507. }
  9508. /**
  9509. * Returns `true` if this matrix is equal with the given one.
  9510. *
  9511. * @param {Matrix4} matrix - The matrix to test for equality.
  9512. * @return {boolean} Whether this matrix is equal with the given one.
  9513. */
  9514. equals( matrix ) {
  9515. const te = this.elements;
  9516. const me = matrix.elements;
  9517. for ( let i = 0; i < 16; i ++ ) {
  9518. if ( te[ i ] !== me[ i ] ) return false;
  9519. }
  9520. return true;
  9521. }
  9522. /**
  9523. * Sets the elements of the matrix from the given array.
  9524. *
  9525. * @param {Array<number>} array - The matrix elements in column-major order.
  9526. * @param {number} [offset=0] - Index of the first element in the array.
  9527. * @return {Matrix4} A reference to this matrix.
  9528. */
  9529. fromArray( array, offset = 0 ) {
  9530. for ( let i = 0; i < 16; i ++ ) {
  9531. this.elements[ i ] = array[ i + offset ];
  9532. }
  9533. return this;
  9534. }
  9535. /**
  9536. * Writes the elements of this matrix to the given array. If no array is provided,
  9537. * the method returns a new instance.
  9538. *
  9539. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9540. * @param {number} [offset=0] - Index of the first element in the array.
  9541. * @return {Array<number>} The matrix elements in column-major order.
  9542. */
  9543. toArray( array = [], offset = 0 ) {
  9544. const te = this.elements;
  9545. array[ offset ] = te[ 0 ];
  9546. array[ offset + 1 ] = te[ 1 ];
  9547. array[ offset + 2 ] = te[ 2 ];
  9548. array[ offset + 3 ] = te[ 3 ];
  9549. array[ offset + 4 ] = te[ 4 ];
  9550. array[ offset + 5 ] = te[ 5 ];
  9551. array[ offset + 6 ] = te[ 6 ];
  9552. array[ offset + 7 ] = te[ 7 ];
  9553. array[ offset + 8 ] = te[ 8 ];
  9554. array[ offset + 9 ] = te[ 9 ];
  9555. array[ offset + 10 ] = te[ 10 ];
  9556. array[ offset + 11 ] = te[ 11 ];
  9557. array[ offset + 12 ] = te[ 12 ];
  9558. array[ offset + 13 ] = te[ 13 ];
  9559. array[ offset + 14 ] = te[ 14 ];
  9560. array[ offset + 15 ] = te[ 15 ];
  9561. return array;
  9562. }
  9563. }
  9564. const _v1$5 = /*@__PURE__*/ new Vector3();
  9565. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9566. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9567. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9568. const _x = /*@__PURE__*/ new Vector3();
  9569. const _y = /*@__PURE__*/ new Vector3();
  9570. const _z = /*@__PURE__*/ new Vector3();
  9571. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9572. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9573. /**
  9574. * A class representing Euler angles.
  9575. *
  9576. * Euler angles describe a rotational transformation by rotating an object on
  9577. * its various axes in specified amounts per axis, and a specified axis
  9578. * order.
  9579. *
  9580. * Iterating through an instance will yield its components (x, y, z,
  9581. * order) in the corresponding order.
  9582. *
  9583. * ```js
  9584. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9585. * const b = new THREE.Vector3( 1, 0, 1 );
  9586. * b.applyEuler(a);
  9587. * ```
  9588. */
  9589. class Euler {
  9590. /**
  9591. * Constructs a new euler instance.
  9592. *
  9593. * @param {number} [x=0] - The angle of the x axis in radians.
  9594. * @param {number} [y=0] - The angle of the y axis in radians.
  9595. * @param {number} [z=0] - The angle of the z axis in radians.
  9596. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9597. */
  9598. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9599. /**
  9600. * This flag can be used for type testing.
  9601. *
  9602. * @type {boolean}
  9603. * @readonly
  9604. * @default true
  9605. */
  9606. this.isEuler = true;
  9607. this._x = x;
  9608. this._y = y;
  9609. this._z = z;
  9610. this._order = order;
  9611. }
  9612. /**
  9613. * The angle of the x axis in radians.
  9614. *
  9615. * @type {number}
  9616. * @default 0
  9617. */
  9618. get x() {
  9619. return this._x;
  9620. }
  9621. set x( value ) {
  9622. this._x = value;
  9623. this._onChangeCallback();
  9624. }
  9625. /**
  9626. * The angle of the y axis in radians.
  9627. *
  9628. * @type {number}
  9629. * @default 0
  9630. */
  9631. get y() {
  9632. return this._y;
  9633. }
  9634. set y( value ) {
  9635. this._y = value;
  9636. this._onChangeCallback();
  9637. }
  9638. /**
  9639. * The angle of the z axis in radians.
  9640. *
  9641. * @type {number}
  9642. * @default 0
  9643. */
  9644. get z() {
  9645. return this._z;
  9646. }
  9647. set z( value ) {
  9648. this._z = value;
  9649. this._onChangeCallback();
  9650. }
  9651. /**
  9652. * A string representing the order that the rotations are applied.
  9653. *
  9654. * @type {string}
  9655. * @default 'XYZ'
  9656. */
  9657. get order() {
  9658. return this._order;
  9659. }
  9660. set order( value ) {
  9661. this._order = value;
  9662. this._onChangeCallback();
  9663. }
  9664. /**
  9665. * Sets the Euler components.
  9666. *
  9667. * @param {number} x - The angle of the x axis in radians.
  9668. * @param {number} y - The angle of the y axis in radians.
  9669. * @param {number} z - The angle of the z axis in radians.
  9670. * @param {string} [order] - A string representing the order that the rotations are applied.
  9671. * @return {Euler} A reference to this Euler instance.
  9672. */
  9673. set( x, y, z, order = this._order ) {
  9674. this._x = x;
  9675. this._y = y;
  9676. this._z = z;
  9677. this._order = order;
  9678. this._onChangeCallback();
  9679. return this;
  9680. }
  9681. /**
  9682. * Returns a new Euler instance with copied values from this instance.
  9683. *
  9684. * @return {Euler} A clone of this instance.
  9685. */
  9686. clone() {
  9687. return new this.constructor( this._x, this._y, this._z, this._order );
  9688. }
  9689. /**
  9690. * Copies the values of the given Euler instance to this instance.
  9691. *
  9692. * @param {Euler} euler - The Euler instance to copy.
  9693. * @return {Euler} A reference to this Euler instance.
  9694. */
  9695. copy( euler ) {
  9696. this._x = euler._x;
  9697. this._y = euler._y;
  9698. this._z = euler._z;
  9699. this._order = euler._order;
  9700. this._onChangeCallback();
  9701. return this;
  9702. }
  9703. /**
  9704. * Sets the angles of this Euler instance from a pure rotation matrix.
  9705. *
  9706. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9707. * @param {string} [order] - A string representing the order that the rotations are applied.
  9708. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9709. * @return {Euler} A reference to this Euler instance.
  9710. */
  9711. setFromRotationMatrix( m, order = this._order, update = true ) {
  9712. const te = m.elements;
  9713. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9714. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9715. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9716. switch ( order ) {
  9717. case 'XYZ':
  9718. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9719. if ( Math.abs( m13 ) < 0.9999999 ) {
  9720. this._x = Math.atan2( - m23, m33 );
  9721. this._z = Math.atan2( - m12, m11 );
  9722. } else {
  9723. this._x = Math.atan2( m32, m22 );
  9724. this._z = 0;
  9725. }
  9726. break;
  9727. case 'YXZ':
  9728. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9729. if ( Math.abs( m23 ) < 0.9999999 ) {
  9730. this._y = Math.atan2( m13, m33 );
  9731. this._z = Math.atan2( m21, m22 );
  9732. } else {
  9733. this._y = Math.atan2( - m31, m11 );
  9734. this._z = 0;
  9735. }
  9736. break;
  9737. case 'ZXY':
  9738. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9739. if ( Math.abs( m32 ) < 0.9999999 ) {
  9740. this._y = Math.atan2( - m31, m33 );
  9741. this._z = Math.atan2( - m12, m22 );
  9742. } else {
  9743. this._y = 0;
  9744. this._z = Math.atan2( m21, m11 );
  9745. }
  9746. break;
  9747. case 'ZYX':
  9748. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9749. if ( Math.abs( m31 ) < 0.9999999 ) {
  9750. this._x = Math.atan2( m32, m33 );
  9751. this._z = Math.atan2( m21, m11 );
  9752. } else {
  9753. this._x = 0;
  9754. this._z = Math.atan2( - m12, m22 );
  9755. }
  9756. break;
  9757. case 'YZX':
  9758. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9759. if ( Math.abs( m21 ) < 0.9999999 ) {
  9760. this._x = Math.atan2( - m23, m22 );
  9761. this._y = Math.atan2( - m31, m11 );
  9762. } else {
  9763. this._x = 0;
  9764. this._y = Math.atan2( m13, m33 );
  9765. }
  9766. break;
  9767. case 'XZY':
  9768. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9769. if ( Math.abs( m12 ) < 0.9999999 ) {
  9770. this._x = Math.atan2( m32, m22 );
  9771. this._y = Math.atan2( m13, m11 );
  9772. } else {
  9773. this._x = Math.atan2( - m23, m33 );
  9774. this._y = 0;
  9775. }
  9776. break;
  9777. default:
  9778. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9779. }
  9780. this._order = order;
  9781. if ( update === true ) this._onChangeCallback();
  9782. return this;
  9783. }
  9784. /**
  9785. * Sets the angles of this Euler instance from a normalized quaternion.
  9786. *
  9787. * @param {Quaternion} q - A normalized Quaternion.
  9788. * @param {string} [order] - A string representing the order that the rotations are applied.
  9789. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9790. * @return {Euler} A reference to this Euler instance.
  9791. */
  9792. setFromQuaternion( q, order, update ) {
  9793. _matrix$2.makeRotationFromQuaternion( q );
  9794. return this.setFromRotationMatrix( _matrix$2, order, update );
  9795. }
  9796. /**
  9797. * Sets the angles of this Euler instance from the given vector.
  9798. *
  9799. * @param {Vector3} v - The vector.
  9800. * @param {string} [order] - A string representing the order that the rotations are applied.
  9801. * @return {Euler} A reference to this Euler instance.
  9802. */
  9803. setFromVector3( v, order = this._order ) {
  9804. return this.set( v.x, v.y, v.z, order );
  9805. }
  9806. /**
  9807. * Resets the euler angle with a new order by creating a quaternion from this
  9808. * euler angle and then setting this euler angle with the quaternion and the
  9809. * new order.
  9810. *
  9811. * Warning: This discards revolution information.
  9812. *
  9813. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9814. * @return {Euler} A reference to this Euler instance.
  9815. */
  9816. reorder( newOrder ) {
  9817. _quaternion$3.setFromEuler( this );
  9818. return this.setFromQuaternion( _quaternion$3, newOrder );
  9819. }
  9820. /**
  9821. * Returns `true` if this Euler instance is equal with the given one.
  9822. *
  9823. * @param {Euler} euler - The Euler instance to test for equality.
  9824. * @return {boolean} Whether this Euler instance is equal with the given one.
  9825. */
  9826. equals( euler ) {
  9827. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9828. }
  9829. /**
  9830. * Sets this Euler instance's components to values from the given array. The first three
  9831. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9832. * defines the Euler order.
  9833. *
  9834. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9835. * @return {Euler} A reference to this Euler instance.
  9836. */
  9837. fromArray( array ) {
  9838. this._x = array[ 0 ];
  9839. this._y = array[ 1 ];
  9840. this._z = array[ 2 ];
  9841. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9842. this._onChangeCallback();
  9843. return this;
  9844. }
  9845. /**
  9846. * Writes the components of this Euler instance to the given array. If no array is provided,
  9847. * the method returns a new instance.
  9848. *
  9849. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9850. * @param {number} [offset=0] - Index of the first element in the array.
  9851. * @return {Array<number,number,number,string>} The Euler components.
  9852. */
  9853. toArray( array = [], offset = 0 ) {
  9854. array[ offset ] = this._x;
  9855. array[ offset + 1 ] = this._y;
  9856. array[ offset + 2 ] = this._z;
  9857. array[ offset + 3 ] = this._order;
  9858. return array;
  9859. }
  9860. _onChange( callback ) {
  9861. this._onChangeCallback = callback;
  9862. return this;
  9863. }
  9864. _onChangeCallback() {}
  9865. *[ Symbol.iterator ]() {
  9866. yield this._x;
  9867. yield this._y;
  9868. yield this._z;
  9869. yield this._order;
  9870. }
  9871. }
  9872. /**
  9873. * The default Euler angle order.
  9874. *
  9875. * @static
  9876. * @type {string}
  9877. * @default 'XYZ'
  9878. */
  9879. Euler.DEFAULT_ORDER = 'XYZ';
  9880. /**
  9881. * A layers object assigns an 3D object to 1 or more of 32
  9882. * layers numbered `0` to `31` - internally the layers are stored as a
  9883. * bit mask], and by default all 3D objects are a member of layer `0`.
  9884. *
  9885. * This can be used to control visibility - an object must share a layer with
  9886. * a camera to be visible when that camera's view is
  9887. * rendered.
  9888. *
  9889. * All classes that inherit from {@link Object3D} have an `layers` property which
  9890. * is an instance of this class.
  9891. */
  9892. class Layers {
  9893. /**
  9894. * Constructs a new layers instance, with membership
  9895. * initially set to layer `0`.
  9896. */
  9897. constructor() {
  9898. /**
  9899. * A bit mask storing which of the 32 layers this layers object is currently
  9900. * a member of.
  9901. *
  9902. * @type {number}
  9903. */
  9904. this.mask = 1 | 0;
  9905. }
  9906. /**
  9907. * Sets membership to the given layer, and remove membership all other layers.
  9908. *
  9909. * @param {number} layer - The layer to set.
  9910. */
  9911. set( layer ) {
  9912. this.mask = ( 1 << layer | 0 ) >>> 0;
  9913. }
  9914. /**
  9915. * Adds membership of the given layer.
  9916. *
  9917. * @param {number} layer - The layer to enable.
  9918. */
  9919. enable( layer ) {
  9920. this.mask |= 1 << layer | 0;
  9921. }
  9922. /**
  9923. * Adds membership to all layers.
  9924. */
  9925. enableAll() {
  9926. this.mask = 0xffffffff | 0;
  9927. }
  9928. /**
  9929. * Toggles the membership of the given layer.
  9930. *
  9931. * @param {number} layer - The layer to toggle.
  9932. */
  9933. toggle( layer ) {
  9934. this.mask ^= 1 << layer | 0;
  9935. }
  9936. /**
  9937. * Removes membership of the given layer.
  9938. *
  9939. * @param {number} layer - The layer to enable.
  9940. */
  9941. disable( layer ) {
  9942. this.mask &= ~ ( 1 << layer | 0 );
  9943. }
  9944. /**
  9945. * Removes the membership from all layers.
  9946. */
  9947. disableAll() {
  9948. this.mask = 0;
  9949. }
  9950. /**
  9951. * Returns `true` if this and the given layers object have at least one
  9952. * layer in common.
  9953. *
  9954. * @param {Layers} layers - The layers to test.
  9955. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9956. */
  9957. test( layers ) {
  9958. return ( this.mask & layers.mask ) !== 0;
  9959. }
  9960. /**
  9961. * Returns `true` if the given layer is enabled.
  9962. *
  9963. * @param {number} layer - The layer to test.
  9964. * @return {boolean } Whether the given layer is enabled or not.
  9965. */
  9966. isEnabled( layer ) {
  9967. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9968. }
  9969. }
  9970. let _object3DId = 0;
  9971. const _v1$4 = /*@__PURE__*/ new Vector3();
  9972. const _q1 = /*@__PURE__*/ new Quaternion();
  9973. const _m1$3 = /*@__PURE__*/ new Matrix4();
  9974. const _target = /*@__PURE__*/ new Vector3();
  9975. const _position$3 = /*@__PURE__*/ new Vector3();
  9976. const _scale$2 = /*@__PURE__*/ new Vector3();
  9977. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9978. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9979. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9980. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9981. /**
  9982. * Fires when the object has been added to its parent object.
  9983. *
  9984. * @event Object3D#added
  9985. * @type {Object}
  9986. */
  9987. const _addedEvent = { type: 'added' };
  9988. /**
  9989. * Fires when the object has been removed from its parent object.
  9990. *
  9991. * @event Object3D#removed
  9992. * @type {Object}
  9993. */
  9994. const _removedEvent = { type: 'removed' };
  9995. /**
  9996. * Fires when a new child object has been added.
  9997. *
  9998. * @event Object3D#childadded
  9999. * @type {Object}
  10000. */
  10001. const _childaddedEvent = { type: 'childadded', child: null };
  10002. /**
  10003. * Fires when a child object has been removed.
  10004. *
  10005. * @event Object3D#childremoved
  10006. * @type {Object}
  10007. */
  10008. const _childremovedEvent = { type: 'childremoved', child: null };
  10009. /**
  10010. * This is the base class for most objects in three.js and provides a set of
  10011. * properties and methods for manipulating objects in 3D space.
  10012. *
  10013. * @augments EventDispatcher
  10014. */
  10015. class Object3D extends EventDispatcher {
  10016. /**
  10017. * Constructs a new 3D object.
  10018. */
  10019. constructor() {
  10020. super();
  10021. /**
  10022. * This flag can be used for type testing.
  10023. *
  10024. * @type {boolean}
  10025. * @readonly
  10026. * @default true
  10027. */
  10028. this.isObject3D = true;
  10029. /**
  10030. * The ID of the 3D object.
  10031. *
  10032. * @name Object3D#id
  10033. * @type {number}
  10034. * @readonly
  10035. */
  10036. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10037. /**
  10038. * The UUID of the 3D object.
  10039. *
  10040. * @type {string}
  10041. * @readonly
  10042. */
  10043. this.uuid = generateUUID();
  10044. /**
  10045. * The name of the 3D object.
  10046. *
  10047. * @type {string}
  10048. */
  10049. this.name = '';
  10050. /**
  10051. * The type property is used for detecting the object type
  10052. * in context of serialization/deserialization.
  10053. *
  10054. * @type {string}
  10055. * @readonly
  10056. */
  10057. this.type = 'Object3D';
  10058. /**
  10059. * A reference to the parent object.
  10060. *
  10061. * @type {?Object3D}
  10062. * @default null
  10063. */
  10064. this.parent = null;
  10065. /**
  10066. * An array holding the child 3D objects of this instance.
  10067. *
  10068. * @type {Array<Object3D>}
  10069. */
  10070. this.children = [];
  10071. /**
  10072. * Defines the `up` direction of the 3D object which influences
  10073. * the orientation via methods like {@link Object3D#lookAt}.
  10074. *
  10075. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10076. *
  10077. * @type {Vector3}
  10078. */
  10079. this.up = Object3D.DEFAULT_UP.clone();
  10080. const position = new Vector3();
  10081. const rotation = new Euler();
  10082. const quaternion = new Quaternion();
  10083. const scale = new Vector3( 1, 1, 1 );
  10084. function onRotationChange() {
  10085. quaternion.setFromEuler( rotation, false );
  10086. }
  10087. function onQuaternionChange() {
  10088. rotation.setFromQuaternion( quaternion, undefined, false );
  10089. }
  10090. rotation._onChange( onRotationChange );
  10091. quaternion._onChange( onQuaternionChange );
  10092. Object.defineProperties( this, {
  10093. /**
  10094. * Represents the object's local position.
  10095. *
  10096. * @name Object3D#position
  10097. * @type {Vector3}
  10098. * @default (0,0,0)
  10099. */
  10100. position: {
  10101. configurable: true,
  10102. enumerable: true,
  10103. value: position
  10104. },
  10105. /**
  10106. * Represents the object's local rotation as Euler angles, in radians.
  10107. *
  10108. * @name Object3D#rotation
  10109. * @type {Euler}
  10110. * @default (0,0,0)
  10111. */
  10112. rotation: {
  10113. configurable: true,
  10114. enumerable: true,
  10115. value: rotation
  10116. },
  10117. /**
  10118. * Represents the object's local rotation as Quaternions.
  10119. *
  10120. * @name Object3D#quaternion
  10121. * @type {Quaternion}
  10122. */
  10123. quaternion: {
  10124. configurable: true,
  10125. enumerable: true,
  10126. value: quaternion
  10127. },
  10128. /**
  10129. * Represents the object's local scale.
  10130. *
  10131. * @name Object3D#scale
  10132. * @type {Vector3}
  10133. * @default (1,1,1)
  10134. */
  10135. scale: {
  10136. configurable: true,
  10137. enumerable: true,
  10138. value: scale
  10139. },
  10140. /**
  10141. * Represents the object's model-view matrix.
  10142. *
  10143. * @name Object3D#modelViewMatrix
  10144. * @type {Matrix4}
  10145. */
  10146. modelViewMatrix: {
  10147. value: new Matrix4()
  10148. },
  10149. /**
  10150. * Represents the object's normal matrix.
  10151. *
  10152. * @name Object3D#normalMatrix
  10153. * @type {Matrix3}
  10154. */
  10155. normalMatrix: {
  10156. value: new Matrix3()
  10157. }
  10158. } );
  10159. /**
  10160. * Represents the object's transformation matrix in local space.
  10161. *
  10162. * @type {Matrix4}
  10163. */
  10164. this.matrix = new Matrix4();
  10165. /**
  10166. * Represents the object's transformation matrix in world space.
  10167. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10168. *
  10169. * @type {Matrix4}
  10170. */
  10171. this.matrixWorld = new Matrix4();
  10172. /**
  10173. * When set to `true`, the engine automatically computes the local matrix from position,
  10174. * rotation and scale every frame.
  10175. *
  10176. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10177. *
  10178. * @type {boolean}
  10179. * @default true
  10180. */
  10181. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10182. /**
  10183. * When set to `true`, the engine automatically computes the world matrix from the current local
  10184. * matrix and the object's transformation hierarchy.
  10185. *
  10186. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10187. *
  10188. * @type {boolean}
  10189. * @default true
  10190. */
  10191. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10192. /**
  10193. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10194. * to `false`.
  10195. *
  10196. * @type {boolean}
  10197. * @default false
  10198. */
  10199. this.matrixWorldNeedsUpdate = false;
  10200. /**
  10201. * The layer membership of the 3D object. The 3D object is only visible if it has
  10202. * at least one layer in common with the camera in use. This property can also be
  10203. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10204. *
  10205. * @type {Layers}
  10206. */
  10207. this.layers = new Layers();
  10208. /**
  10209. * When set to `true`, the 3D object gets rendered.
  10210. *
  10211. * @type {boolean}
  10212. * @default true
  10213. */
  10214. this.visible = true;
  10215. /**
  10216. * When set to `true`, the 3D object gets rendered into shadow maps.
  10217. *
  10218. * @type {boolean}
  10219. * @default false
  10220. */
  10221. this.castShadow = false;
  10222. /**
  10223. * When set to `true`, the 3D object is affected by shadows in the scene.
  10224. *
  10225. * @type {boolean}
  10226. * @default false
  10227. */
  10228. this.receiveShadow = false;
  10229. /**
  10230. * When set to `true`, the 3D object is honored by view frustum culling.
  10231. *
  10232. * @type {boolean}
  10233. * @default true
  10234. */
  10235. this.frustumCulled = true;
  10236. /**
  10237. * This value allows the default rendering order of scene graph objects to be
  10238. * overridden although opaque and transparent objects remain sorted independently.
  10239. * When this property is set for an instance of {@link Group},all descendants
  10240. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10241. * render order.
  10242. *
  10243. * @type {number}
  10244. * @default 0
  10245. */
  10246. this.renderOrder = 0;
  10247. /**
  10248. * An array holding the animation clips of the 3D object.
  10249. *
  10250. * @type {Array<AnimationClip>}
  10251. */
  10252. this.animations = [];
  10253. /**
  10254. * Custom depth material to be used when rendering to the depth map. Can only be used
  10255. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10256. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10257. * material for proper shadows.
  10258. *
  10259. * Only relevant in context of {@link WebGLRenderer}.
  10260. *
  10261. * @type {(Material|undefined)}
  10262. * @default undefined
  10263. */
  10264. this.customDepthMaterial = undefined;
  10265. /**
  10266. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10267. *
  10268. * Only relevant in context of {@link WebGLRenderer}.
  10269. *
  10270. * @type {(Material|undefined)}
  10271. * @default undefined
  10272. */
  10273. this.customDistanceMaterial = undefined;
  10274. /**
  10275. * An object that can be used to store custom data about the 3D object. It
  10276. * should not hold references to functions as these will not be cloned.
  10277. *
  10278. * @type {Object}
  10279. */
  10280. this.userData = {};
  10281. }
  10282. /**
  10283. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10284. *
  10285. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10286. * @param {Object3D} object - The 3D object.
  10287. * @param {Camera} camera - The camera that is used to render the scene.
  10288. * @param {Camera} shadowCamera - The shadow camera.
  10289. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10290. * @param {Material} depthMaterial - The depth material.
  10291. * @param {Object} group - The geometry group data.
  10292. */
  10293. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10294. /**
  10295. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10296. *
  10297. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10298. * @param {Object3D} object - The 3D object.
  10299. * @param {Camera} camera - The camera that is used to render the scene.
  10300. * @param {Camera} shadowCamera - The shadow camera.
  10301. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10302. * @param {Material} depthMaterial - The depth material.
  10303. * @param {Object} group - The geometry group data.
  10304. */
  10305. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10306. /**
  10307. * A callback that is executed immediately before a 3D object is rendered.
  10308. *
  10309. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10310. * @param {Object3D} object - The 3D object.
  10311. * @param {Camera} camera - The camera that is used to render the scene.
  10312. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10313. * @param {Material} material - The 3D object's material.
  10314. * @param {Object} group - The geometry group data.
  10315. */
  10316. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10317. /**
  10318. * A callback that is executed immediately after a 3D object is rendered.
  10319. *
  10320. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10321. * @param {Object3D} object - The 3D object.
  10322. * @param {Camera} camera - The camera that is used to render the scene.
  10323. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10324. * @param {Material} material - The 3D object's material.
  10325. * @param {Object} group - The geometry group data.
  10326. */
  10327. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10328. /**
  10329. * Applies the given transformation matrix to the object and updates the object's position,
  10330. * rotation and scale.
  10331. *
  10332. * @param {Matrix4} matrix - The transformation matrix.
  10333. */
  10334. applyMatrix4( matrix ) {
  10335. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10336. this.matrix.premultiply( matrix );
  10337. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10338. }
  10339. /**
  10340. * Applies a rotation represented by given the quaternion to the 3D object.
  10341. *
  10342. * @param {Quaternion} q - The quaternion.
  10343. * @return {Object3D} A reference to this instance.
  10344. */
  10345. applyQuaternion( q ) {
  10346. this.quaternion.premultiply( q );
  10347. return this;
  10348. }
  10349. /**
  10350. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10351. *
  10352. * @param {Vector3} axis - The (normalized) axis vector.
  10353. * @param {number} angle - The angle in radians.
  10354. */
  10355. setRotationFromAxisAngle( axis, angle ) {
  10356. // assumes axis is normalized
  10357. this.quaternion.setFromAxisAngle( axis, angle );
  10358. }
  10359. /**
  10360. * Sets the given rotation represented as Euler angles to the 3D object.
  10361. *
  10362. * @param {Euler} euler - The Euler angles.
  10363. */
  10364. setRotationFromEuler( euler ) {
  10365. this.quaternion.setFromEuler( euler, true );
  10366. }
  10367. /**
  10368. * Sets the given rotation represented as rotation matrix to the 3D object.
  10369. *
  10370. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10371. * a pure rotation matrix (i.e, unscaled).
  10372. */
  10373. setRotationFromMatrix( m ) {
  10374. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10375. this.quaternion.setFromRotationMatrix( m );
  10376. }
  10377. /**
  10378. * Sets the given rotation represented as a Quaternion to the 3D object.
  10379. *
  10380. * @param {Quaternion} q - The Quaternion
  10381. */
  10382. setRotationFromQuaternion( q ) {
  10383. // assumes q is normalized
  10384. this.quaternion.copy( q );
  10385. }
  10386. /**
  10387. * Rotates the 3D object along an axis in local space.
  10388. *
  10389. * @param {Vector3} axis - The (normalized) axis vector.
  10390. * @param {number} angle - The angle in radians.
  10391. * @return {Object3D} A reference to this instance.
  10392. */
  10393. rotateOnAxis( axis, angle ) {
  10394. // rotate object on axis in object space
  10395. // axis is assumed to be normalized
  10396. _q1.setFromAxisAngle( axis, angle );
  10397. this.quaternion.multiply( _q1 );
  10398. return this;
  10399. }
  10400. /**
  10401. * Rotates the 3D object along an axis in world space.
  10402. *
  10403. * @param {Vector3} axis - The (normalized) axis vector.
  10404. * @param {number} angle - The angle in radians.
  10405. * @return {Object3D} A reference to this instance.
  10406. */
  10407. rotateOnWorldAxis( axis, angle ) {
  10408. // rotate object on axis in world space
  10409. // axis is assumed to be normalized
  10410. // method assumes no rotated parent
  10411. _q1.setFromAxisAngle( axis, angle );
  10412. this.quaternion.premultiply( _q1 );
  10413. return this;
  10414. }
  10415. /**
  10416. * Rotates the 3D object around its X axis in local space.
  10417. *
  10418. * @param {number} angle - The angle in radians.
  10419. * @return {Object3D} A reference to this instance.
  10420. */
  10421. rotateX( angle ) {
  10422. return this.rotateOnAxis( _xAxis, angle );
  10423. }
  10424. /**
  10425. * Rotates the 3D object around its Y axis in local space.
  10426. *
  10427. * @param {number} angle - The angle in radians.
  10428. * @return {Object3D} A reference to this instance.
  10429. */
  10430. rotateY( angle ) {
  10431. return this.rotateOnAxis( _yAxis, angle );
  10432. }
  10433. /**
  10434. * Rotates the 3D object around its Z axis in local space.
  10435. *
  10436. * @param {number} angle - The angle in radians.
  10437. * @return {Object3D} A reference to this instance.
  10438. */
  10439. rotateZ( angle ) {
  10440. return this.rotateOnAxis( _zAxis, angle );
  10441. }
  10442. /**
  10443. * Translate the 3D object by a distance along the given axis in local space.
  10444. *
  10445. * @param {Vector3} axis - The (normalized) axis vector.
  10446. * @param {number} distance - The distance in world units.
  10447. * @return {Object3D} A reference to this instance.
  10448. */
  10449. translateOnAxis( axis, distance ) {
  10450. // translate object by distance along axis in object space
  10451. // axis is assumed to be normalized
  10452. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10453. this.position.add( _v1$4.multiplyScalar( distance ) );
  10454. return this;
  10455. }
  10456. /**
  10457. * Translate the 3D object by a distance along its X-axis in local space.
  10458. *
  10459. * @param {number} distance - The distance in world units.
  10460. * @return {Object3D} A reference to this instance.
  10461. */
  10462. translateX( distance ) {
  10463. return this.translateOnAxis( _xAxis, distance );
  10464. }
  10465. /**
  10466. * Translate the 3D object by a distance along its Y-axis in local space.
  10467. *
  10468. * @param {number} distance - The distance in world units.
  10469. * @return {Object3D} A reference to this instance.
  10470. */
  10471. translateY( distance ) {
  10472. return this.translateOnAxis( _yAxis, distance );
  10473. }
  10474. /**
  10475. * Translate the 3D object by a distance along its Z-axis in local space.
  10476. *
  10477. * @param {number} distance - The distance in world units.
  10478. * @return {Object3D} A reference to this instance.
  10479. */
  10480. translateZ( distance ) {
  10481. return this.translateOnAxis( _zAxis, distance );
  10482. }
  10483. /**
  10484. * Converts the given vector from this 3D object's local space to world space.
  10485. *
  10486. * @param {Vector3} vector - The vector to convert.
  10487. * @return {Vector3} The converted vector.
  10488. */
  10489. localToWorld( vector ) {
  10490. this.updateWorldMatrix( true, false );
  10491. return vector.applyMatrix4( this.matrixWorld );
  10492. }
  10493. /**
  10494. * Converts the given vector from this 3D object's word space to local space.
  10495. *
  10496. * @param {Vector3} vector - The vector to convert.
  10497. * @return {Vector3} The converted vector.
  10498. */
  10499. worldToLocal( vector ) {
  10500. this.updateWorldMatrix( true, false );
  10501. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10502. }
  10503. /**
  10504. * Rotates the object to face a point in world space.
  10505. *
  10506. * This method does not support objects having non-uniformly-scaled parent(s).
  10507. *
  10508. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10509. * @param {number} [y] - The y coordinate in world space.
  10510. * @param {number} [z] - The z coordinate in world space.
  10511. */
  10512. lookAt( x, y, z ) {
  10513. // This method does not support objects having non-uniformly-scaled parent(s)
  10514. if ( x.isVector3 ) {
  10515. _target.copy( x );
  10516. } else {
  10517. _target.set( x, y, z );
  10518. }
  10519. const parent = this.parent;
  10520. this.updateWorldMatrix( true, false );
  10521. _position$3.setFromMatrixPosition( this.matrixWorld );
  10522. if ( this.isCamera || this.isLight ) {
  10523. _m1$3.lookAt( _position$3, _target, this.up );
  10524. } else {
  10525. _m1$3.lookAt( _target, _position$3, this.up );
  10526. }
  10527. this.quaternion.setFromRotationMatrix( _m1$3 );
  10528. if ( parent ) {
  10529. _m1$3.extractRotation( parent.matrixWorld );
  10530. _q1.setFromRotationMatrix( _m1$3 );
  10531. this.quaternion.premultiply( _q1.invert() );
  10532. }
  10533. }
  10534. /**
  10535. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10536. * objects may be added. Any current parent on an object passed in here will be
  10537. * removed, since an object can have at most one parent.
  10538. *
  10539. * @fires Object3D#added
  10540. * @fires Object3D#childadded
  10541. * @param {Object3D} object - The 3D object to add.
  10542. * @return {Object3D} A reference to this instance.
  10543. */
  10544. add( object ) {
  10545. if ( arguments.length > 1 ) {
  10546. for ( let i = 0; i < arguments.length; i ++ ) {
  10547. this.add( arguments[ i ] );
  10548. }
  10549. return this;
  10550. }
  10551. if ( object === this ) {
  10552. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10553. return this;
  10554. }
  10555. if ( object && object.isObject3D ) {
  10556. object.removeFromParent();
  10557. object.parent = this;
  10558. this.children.push( object );
  10559. object.dispatchEvent( _addedEvent );
  10560. _childaddedEvent.child = object;
  10561. this.dispatchEvent( _childaddedEvent );
  10562. _childaddedEvent.child = null;
  10563. } else {
  10564. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10565. }
  10566. return this;
  10567. }
  10568. /**
  10569. * Removes the given 3D object as child from this 3D object.
  10570. * An arbitrary number of objects may be removed.
  10571. *
  10572. * @fires Object3D#removed
  10573. * @fires Object3D#childremoved
  10574. * @param {Object3D} object - The 3D object to remove.
  10575. * @return {Object3D} A reference to this instance.
  10576. */
  10577. remove( object ) {
  10578. if ( arguments.length > 1 ) {
  10579. for ( let i = 0; i < arguments.length; i ++ ) {
  10580. this.remove( arguments[ i ] );
  10581. }
  10582. return this;
  10583. }
  10584. const index = this.children.indexOf( object );
  10585. if ( index !== -1 ) {
  10586. object.parent = null;
  10587. this.children.splice( index, 1 );
  10588. object.dispatchEvent( _removedEvent );
  10589. _childremovedEvent.child = object;
  10590. this.dispatchEvent( _childremovedEvent );
  10591. _childremovedEvent.child = null;
  10592. }
  10593. return this;
  10594. }
  10595. /**
  10596. * Removes this 3D object from its current parent.
  10597. *
  10598. * @fires Object3D#removed
  10599. * @fires Object3D#childremoved
  10600. * @return {Object3D} A reference to this instance.
  10601. */
  10602. removeFromParent() {
  10603. const parent = this.parent;
  10604. if ( parent !== null ) {
  10605. parent.remove( this );
  10606. }
  10607. return this;
  10608. }
  10609. /**
  10610. * Removes all child objects.
  10611. *
  10612. * @fires Object3D#removed
  10613. * @fires Object3D#childremoved
  10614. * @return {Object3D} A reference to this instance.
  10615. */
  10616. clear() {
  10617. return this.remove( ... this.children );
  10618. }
  10619. /**
  10620. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10621. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10622. *
  10623. * @fires Object3D#added
  10624. * @fires Object3D#childadded
  10625. * @param {Object3D} object - The 3D object to attach.
  10626. * @return {Object3D} A reference to this instance.
  10627. */
  10628. attach( object ) {
  10629. // adds object as a child of this, while maintaining the object's world transform
  10630. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10631. this.updateWorldMatrix( true, false );
  10632. _m1$3.copy( this.matrixWorld ).invert();
  10633. if ( object.parent !== null ) {
  10634. object.parent.updateWorldMatrix( true, false );
  10635. _m1$3.multiply( object.parent.matrixWorld );
  10636. }
  10637. object.applyMatrix4( _m1$3 );
  10638. object.removeFromParent();
  10639. object.parent = this;
  10640. this.children.push( object );
  10641. object.updateWorldMatrix( false, true );
  10642. object.dispatchEvent( _addedEvent );
  10643. _childaddedEvent.child = object;
  10644. this.dispatchEvent( _childaddedEvent );
  10645. _childaddedEvent.child = null;
  10646. return this;
  10647. }
  10648. /**
  10649. * Searches through the 3D object and its children, starting with the 3D object
  10650. * itself, and returns the first with a matching ID.
  10651. *
  10652. * @param {number} id - The id.
  10653. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10654. */
  10655. getObjectById( id ) {
  10656. return this.getObjectByProperty( 'id', id );
  10657. }
  10658. /**
  10659. * Searches through the 3D object and its children, starting with the 3D object
  10660. * itself, and returns the first with a matching name.
  10661. *
  10662. * @param {string} name - The name.
  10663. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10664. */
  10665. getObjectByName( name ) {
  10666. return this.getObjectByProperty( 'name', name );
  10667. }
  10668. /**
  10669. * Searches through the 3D object and its children, starting with the 3D object
  10670. * itself, and returns the first with a matching property value.
  10671. *
  10672. * @param {string} name - The name of the property.
  10673. * @param {any} value - The value.
  10674. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10675. */
  10676. getObjectByProperty( name, value ) {
  10677. if ( this[ name ] === value ) return this;
  10678. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10679. const child = this.children[ i ];
  10680. const object = child.getObjectByProperty( name, value );
  10681. if ( object !== undefined ) {
  10682. return object;
  10683. }
  10684. }
  10685. return undefined;
  10686. }
  10687. /**
  10688. * Searches through the 3D object and its children, starting with the 3D object
  10689. * itself, and returns all 3D objects with a matching property value.
  10690. *
  10691. * @param {string} name - The name of the property.
  10692. * @param {any} value - The value.
  10693. * @param {Array<Object3D>} result - The method stores the result in this array.
  10694. * @return {Array<Object3D>} The found 3D objects.
  10695. */
  10696. getObjectsByProperty( name, value, result = [] ) {
  10697. if ( this[ name ] === value ) result.push( this );
  10698. const children = this.children;
  10699. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10700. children[ i ].getObjectsByProperty( name, value, result );
  10701. }
  10702. return result;
  10703. }
  10704. /**
  10705. * Returns a vector representing the position of the 3D object in world space.
  10706. *
  10707. * @param {Vector3} target - The target vector the result is stored to.
  10708. * @return {Vector3} The 3D object's position in world space.
  10709. */
  10710. getWorldPosition( target ) {
  10711. this.updateWorldMatrix( true, false );
  10712. return target.setFromMatrixPosition( this.matrixWorld );
  10713. }
  10714. /**
  10715. * Returns a Quaternion representing the position of the 3D object in world space.
  10716. *
  10717. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10718. * @return {Quaternion} The 3D object's rotation in world space.
  10719. */
  10720. getWorldQuaternion( target ) {
  10721. this.updateWorldMatrix( true, false );
  10722. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10723. return target;
  10724. }
  10725. /**
  10726. * Returns a vector representing the scale of the 3D object in world space.
  10727. *
  10728. * @param {Vector3} target - The target vector the result is stored to.
  10729. * @return {Vector3} The 3D object's scale in world space.
  10730. */
  10731. getWorldScale( target ) {
  10732. this.updateWorldMatrix( true, false );
  10733. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10734. return target;
  10735. }
  10736. /**
  10737. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10738. *
  10739. * @param {Vector3} target - The target vector the result is stored to.
  10740. * @return {Vector3} The 3D object's direction in world space.
  10741. */
  10742. getWorldDirection( target ) {
  10743. this.updateWorldMatrix( true, false );
  10744. const e = this.matrixWorld.elements;
  10745. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10746. }
  10747. /**
  10748. * Abstract method to get intersections between a casted ray and this
  10749. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10750. * implement this method in order to use raycasting.
  10751. *
  10752. * @abstract
  10753. * @param {Raycaster} raycaster - The raycaster.
  10754. * @param {Array<Object>} intersects - An array holding the result of the method.
  10755. */
  10756. raycast( /* raycaster, intersects */ ) {}
  10757. /**
  10758. * Executes the callback on this 3D object and all descendants.
  10759. *
  10760. * Note: Modifying the scene graph inside the callback is discouraged.
  10761. *
  10762. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10763. */
  10764. traverse( callback ) {
  10765. callback( this );
  10766. const children = this.children;
  10767. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10768. children[ i ].traverse( callback );
  10769. }
  10770. }
  10771. /**
  10772. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10773. * Descendants of invisible 3D objects are not traversed.
  10774. *
  10775. * Note: Modifying the scene graph inside the callback is discouraged.
  10776. *
  10777. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10778. */
  10779. traverseVisible( callback ) {
  10780. if ( this.visible === false ) return;
  10781. callback( this );
  10782. const children = this.children;
  10783. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10784. children[ i ].traverseVisible( callback );
  10785. }
  10786. }
  10787. /**
  10788. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10789. *
  10790. * Note: Modifying the scene graph inside the callback is discouraged.
  10791. *
  10792. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10793. */
  10794. traverseAncestors( callback ) {
  10795. const parent = this.parent;
  10796. if ( parent !== null ) {
  10797. callback( parent );
  10798. parent.traverseAncestors( callback );
  10799. }
  10800. }
  10801. /**
  10802. * Updates the transformation matrix in local space by computing it from the current
  10803. * position, rotation and scale values.
  10804. */
  10805. updateMatrix() {
  10806. this.matrix.compose( this.position, this.quaternion, this.scale );
  10807. this.matrixWorldNeedsUpdate = true;
  10808. }
  10809. /**
  10810. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10811. *
  10812. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10813. * local space. The computation of the local and world matrix can be controlled with the
  10814. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10815. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10816. *
  10817. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10818. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10819. */
  10820. updateMatrixWorld( force ) {
  10821. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10822. if ( this.matrixWorldNeedsUpdate || force ) {
  10823. if ( this.matrixWorldAutoUpdate === true ) {
  10824. if ( this.parent === null ) {
  10825. this.matrixWorld.copy( this.matrix );
  10826. } else {
  10827. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10828. }
  10829. }
  10830. this.matrixWorldNeedsUpdate = false;
  10831. force = true;
  10832. }
  10833. // make sure descendants are updated if required
  10834. const children = this.children;
  10835. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10836. const child = children[ i ];
  10837. child.updateMatrixWorld( force );
  10838. }
  10839. }
  10840. /**
  10841. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10842. * update of ancestor and descendant nodes.
  10843. *
  10844. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10845. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10846. */
  10847. updateWorldMatrix( updateParents, updateChildren ) {
  10848. const parent = this.parent;
  10849. if ( updateParents === true && parent !== null ) {
  10850. parent.updateWorldMatrix( true, false );
  10851. }
  10852. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10853. if ( this.matrixWorldAutoUpdate === true ) {
  10854. if ( this.parent === null ) {
  10855. this.matrixWorld.copy( this.matrix );
  10856. } else {
  10857. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10858. }
  10859. }
  10860. // make sure descendants are updated
  10861. if ( updateChildren === true ) {
  10862. const children = this.children;
  10863. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10864. const child = children[ i ];
  10865. child.updateWorldMatrix( false, true );
  10866. }
  10867. }
  10868. }
  10869. /**
  10870. * Serializes the 3D object into JSON.
  10871. *
  10872. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10873. * @return {Object} A JSON object representing the serialized 3D object.
  10874. * @see {@link ObjectLoader#parse}
  10875. */
  10876. toJSON( meta ) {
  10877. // meta is a string when called from JSON.stringify
  10878. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10879. const output = {};
  10880. // meta is a hash used to collect geometries, materials.
  10881. // not providing it implies that this is the root object
  10882. // being serialized.
  10883. if ( isRootObject ) {
  10884. // initialize meta obj
  10885. meta = {
  10886. geometries: {},
  10887. materials: {},
  10888. textures: {},
  10889. images: {},
  10890. shapes: {},
  10891. skeletons: {},
  10892. animations: {},
  10893. nodes: {}
  10894. };
  10895. output.metadata = {
  10896. version: 4.7,
  10897. type: 'Object',
  10898. generator: 'Object3D.toJSON'
  10899. };
  10900. }
  10901. // standard Object3D serialization
  10902. const object = {};
  10903. object.uuid = this.uuid;
  10904. object.type = this.type;
  10905. if ( this.name !== '' ) object.name = this.name;
  10906. if ( this.castShadow === true ) object.castShadow = true;
  10907. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10908. if ( this.visible === false ) object.visible = false;
  10909. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10910. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10911. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10912. object.layers = this.layers.mask;
  10913. object.matrix = this.matrix.toArray();
  10914. object.up = this.up.toArray();
  10915. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10916. // object specific properties
  10917. if ( this.isInstancedMesh ) {
  10918. object.type = 'InstancedMesh';
  10919. object.count = this.count;
  10920. object.instanceMatrix = this.instanceMatrix.toJSON();
  10921. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10922. }
  10923. if ( this.isBatchedMesh ) {
  10924. object.type = 'BatchedMesh';
  10925. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10926. object.sortObjects = this.sortObjects;
  10927. object.drawRanges = this._drawRanges;
  10928. object.reservedRanges = this._reservedRanges;
  10929. object.geometryInfo = this._geometryInfo.map( info => ( {
  10930. ...info,
  10931. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10932. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10933. } ) );
  10934. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10935. object.availableInstanceIds = this._availableInstanceIds.slice();
  10936. object.availableGeometryIds = this._availableGeometryIds.slice();
  10937. object.nextIndexStart = this._nextIndexStart;
  10938. object.nextVertexStart = this._nextVertexStart;
  10939. object.geometryCount = this._geometryCount;
  10940. object.maxInstanceCount = this._maxInstanceCount;
  10941. object.maxVertexCount = this._maxVertexCount;
  10942. object.maxIndexCount = this._maxIndexCount;
  10943. object.geometryInitialized = this._geometryInitialized;
  10944. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10945. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10946. if ( this._colorsTexture !== null ) {
  10947. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10948. }
  10949. if ( this.boundingSphere !== null ) {
  10950. object.boundingSphere = this.boundingSphere.toJSON();
  10951. }
  10952. if ( this.boundingBox !== null ) {
  10953. object.boundingBox = this.boundingBox.toJSON();
  10954. }
  10955. }
  10956. //
  10957. function serialize( library, element ) {
  10958. if ( library[ element.uuid ] === undefined ) {
  10959. library[ element.uuid ] = element.toJSON( meta );
  10960. }
  10961. return element.uuid;
  10962. }
  10963. if ( this.isScene ) {
  10964. if ( this.background ) {
  10965. if ( this.background.isColor ) {
  10966. object.background = this.background.toJSON();
  10967. } else if ( this.background.isTexture ) {
  10968. object.background = this.background.toJSON( meta ).uuid;
  10969. }
  10970. }
  10971. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10972. object.environment = this.environment.toJSON( meta ).uuid;
  10973. }
  10974. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10975. object.geometry = serialize( meta.geometries, this.geometry );
  10976. const parameters = this.geometry.parameters;
  10977. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10978. const shapes = parameters.shapes;
  10979. if ( Array.isArray( shapes ) ) {
  10980. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10981. const shape = shapes[ i ];
  10982. serialize( meta.shapes, shape );
  10983. }
  10984. } else {
  10985. serialize( meta.shapes, shapes );
  10986. }
  10987. }
  10988. }
  10989. if ( this.isSkinnedMesh ) {
  10990. object.bindMode = this.bindMode;
  10991. object.bindMatrix = this.bindMatrix.toArray();
  10992. if ( this.skeleton !== undefined ) {
  10993. serialize( meta.skeletons, this.skeleton );
  10994. object.skeleton = this.skeleton.uuid;
  10995. }
  10996. }
  10997. if ( this.material !== undefined ) {
  10998. if ( Array.isArray( this.material ) ) {
  10999. const uuids = [];
  11000. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11001. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11002. }
  11003. object.material = uuids;
  11004. } else {
  11005. object.material = serialize( meta.materials, this.material );
  11006. }
  11007. }
  11008. //
  11009. if ( this.children.length > 0 ) {
  11010. object.children = [];
  11011. for ( let i = 0; i < this.children.length; i ++ ) {
  11012. object.children.push( this.children[ i ].toJSON( meta ).object );
  11013. }
  11014. }
  11015. //
  11016. if ( this.animations.length > 0 ) {
  11017. object.animations = [];
  11018. for ( let i = 0; i < this.animations.length; i ++ ) {
  11019. const animation = this.animations[ i ];
  11020. object.animations.push( serialize( meta.animations, animation ) );
  11021. }
  11022. }
  11023. if ( isRootObject ) {
  11024. const geometries = extractFromCache( meta.geometries );
  11025. const materials = extractFromCache( meta.materials );
  11026. const textures = extractFromCache( meta.textures );
  11027. const images = extractFromCache( meta.images );
  11028. const shapes = extractFromCache( meta.shapes );
  11029. const skeletons = extractFromCache( meta.skeletons );
  11030. const animations = extractFromCache( meta.animations );
  11031. const nodes = extractFromCache( meta.nodes );
  11032. if ( geometries.length > 0 ) output.geometries = geometries;
  11033. if ( materials.length > 0 ) output.materials = materials;
  11034. if ( textures.length > 0 ) output.textures = textures;
  11035. if ( images.length > 0 ) output.images = images;
  11036. if ( shapes.length > 0 ) output.shapes = shapes;
  11037. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11038. if ( animations.length > 0 ) output.animations = animations;
  11039. if ( nodes.length > 0 ) output.nodes = nodes;
  11040. }
  11041. output.object = object;
  11042. return output;
  11043. // extract data from the cache hash
  11044. // remove metadata on each item
  11045. // and return as array
  11046. function extractFromCache( cache ) {
  11047. const values = [];
  11048. for ( const key in cache ) {
  11049. const data = cache[ key ];
  11050. delete data.metadata;
  11051. values.push( data );
  11052. }
  11053. return values;
  11054. }
  11055. }
  11056. /**
  11057. * Returns a new 3D object with copied values from this instance.
  11058. *
  11059. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11060. * @return {Object3D} A clone of this instance.
  11061. */
  11062. clone( recursive ) {
  11063. return new this.constructor().copy( this, recursive );
  11064. }
  11065. /**
  11066. * Copies the values of the given 3D object to this instance.
  11067. *
  11068. * @param {Object3D} source - The 3D object to copy.
  11069. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11070. * @return {Object3D} A reference to this instance.
  11071. */
  11072. copy( source, recursive = true ) {
  11073. this.name = source.name;
  11074. this.up.copy( source.up );
  11075. this.position.copy( source.position );
  11076. this.rotation.order = source.rotation.order;
  11077. this.quaternion.copy( source.quaternion );
  11078. this.scale.copy( source.scale );
  11079. this.matrix.copy( source.matrix );
  11080. this.matrixWorld.copy( source.matrixWorld );
  11081. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11082. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11083. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11084. this.layers.mask = source.layers.mask;
  11085. this.visible = source.visible;
  11086. this.castShadow = source.castShadow;
  11087. this.receiveShadow = source.receiveShadow;
  11088. this.frustumCulled = source.frustumCulled;
  11089. this.renderOrder = source.renderOrder;
  11090. this.animations = source.animations.slice();
  11091. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11092. if ( recursive === true ) {
  11093. for ( let i = 0; i < source.children.length; i ++ ) {
  11094. const child = source.children[ i ];
  11095. this.add( child.clone() );
  11096. }
  11097. }
  11098. return this;
  11099. }
  11100. }
  11101. /**
  11102. * The default up direction for objects, also used as the default
  11103. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11104. *
  11105. * @static
  11106. * @type {Vector3}
  11107. * @default (0,1,0)
  11108. */
  11109. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11110. /**
  11111. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11112. * newly created 3D objects.
  11113. *
  11114. * @static
  11115. * @type {boolean}
  11116. * @default true
  11117. */
  11118. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11119. /**
  11120. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11121. * newly created 3D objects.
  11122. *
  11123. * @static
  11124. * @type {boolean}
  11125. * @default true
  11126. */
  11127. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11128. const _v0$2 = /*@__PURE__*/ new Vector3();
  11129. const _v1$3 = /*@__PURE__*/ new Vector3();
  11130. const _v2$2 = /*@__PURE__*/ new Vector3();
  11131. const _v3$2 = /*@__PURE__*/ new Vector3();
  11132. const _vab = /*@__PURE__*/ new Vector3();
  11133. const _vac = /*@__PURE__*/ new Vector3();
  11134. const _vbc = /*@__PURE__*/ new Vector3();
  11135. const _vap = /*@__PURE__*/ new Vector3();
  11136. const _vbp = /*@__PURE__*/ new Vector3();
  11137. const _vcp = /*@__PURE__*/ new Vector3();
  11138. const _v40 = /*@__PURE__*/ new Vector4();
  11139. const _v41 = /*@__PURE__*/ new Vector4();
  11140. const _v42 = /*@__PURE__*/ new Vector4();
  11141. /**
  11142. * A geometric triangle as defined by three vectors representing its three corners.
  11143. */
  11144. class Triangle {
  11145. /**
  11146. * Constructs a new triangle.
  11147. *
  11148. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11149. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11150. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11151. */
  11152. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11153. /**
  11154. * The first corner of the triangle.
  11155. *
  11156. * @type {Vector3}
  11157. */
  11158. this.a = a;
  11159. /**
  11160. * The second corner of the triangle.
  11161. *
  11162. * @type {Vector3}
  11163. */
  11164. this.b = b;
  11165. /**
  11166. * The third corner of the triangle.
  11167. *
  11168. * @type {Vector3}
  11169. */
  11170. this.c = c;
  11171. }
  11172. /**
  11173. * Computes the normal vector of a triangle.
  11174. *
  11175. * @param {Vector3} a - The first corner of the triangle.
  11176. * @param {Vector3} b - The second corner of the triangle.
  11177. * @param {Vector3} c - The third corner of the triangle.
  11178. * @param {Vector3} target - The target vector that is used to store the method's result.
  11179. * @return {Vector3} The triangle's normal.
  11180. */
  11181. static getNormal( a, b, c, target ) {
  11182. target.subVectors( c, b );
  11183. _v0$2.subVectors( a, b );
  11184. target.cross( _v0$2 );
  11185. const targetLengthSq = target.lengthSq();
  11186. if ( targetLengthSq > 0 ) {
  11187. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11188. }
  11189. return target.set( 0, 0, 0 );
  11190. }
  11191. /**
  11192. * Computes a barycentric coordinates from the given vector.
  11193. * Returns `null` if the triangle is degenerate.
  11194. *
  11195. * @param {Vector3} point - A point in 3D space.
  11196. * @param {Vector3} a - The first corner of the triangle.
  11197. * @param {Vector3} b - The second corner of the triangle.
  11198. * @param {Vector3} c - The third corner of the triangle.
  11199. * @param {Vector3} target - The target vector that is used to store the method's result.
  11200. * @return {?Vector3} The barycentric coordinates for the given point
  11201. */
  11202. static getBarycoord( point, a, b, c, target ) {
  11203. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11204. _v0$2.subVectors( c, a );
  11205. _v1$3.subVectors( b, a );
  11206. _v2$2.subVectors( point, a );
  11207. const dot00 = _v0$2.dot( _v0$2 );
  11208. const dot01 = _v0$2.dot( _v1$3 );
  11209. const dot02 = _v0$2.dot( _v2$2 );
  11210. const dot11 = _v1$3.dot( _v1$3 );
  11211. const dot12 = _v1$3.dot( _v2$2 );
  11212. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11213. // collinear or singular triangle
  11214. if ( denom === 0 ) {
  11215. target.set( 0, 0, 0 );
  11216. return null;
  11217. }
  11218. const invDenom = 1 / denom;
  11219. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11220. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11221. // barycentric coordinates must always sum to 1
  11222. return target.set( 1 - u - v, v, u );
  11223. }
  11224. /**
  11225. * Returns `true` if the given point, when projected onto the plane of the
  11226. * triangle, lies within the triangle.
  11227. *
  11228. * @param {Vector3} point - The point in 3D space to test.
  11229. * @param {Vector3} a - The first corner of the triangle.
  11230. * @param {Vector3} b - The second corner of the triangle.
  11231. * @param {Vector3} c - The third corner of the triangle.
  11232. * @return {boolean} Whether the given point, when projected onto the plane of the
  11233. * triangle, lies within the triangle or not.
  11234. */
  11235. static containsPoint( point, a, b, c ) {
  11236. // if the triangle is degenerate then we can't contain a point
  11237. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11238. return false;
  11239. }
  11240. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11241. }
  11242. /**
  11243. * Computes the value barycentrically interpolated for the given point on the
  11244. * triangle. Returns `null` if the triangle is degenerate.
  11245. *
  11246. * @param {Vector3} point - Position of interpolated point.
  11247. * @param {Vector3} p1 - The first corner of the triangle.
  11248. * @param {Vector3} p2 - The second corner of the triangle.
  11249. * @param {Vector3} p3 - The third corner of the triangle.
  11250. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11251. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11252. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11253. * @param {Vector3} target - The target vector that is used to store the method's result.
  11254. * @return {?Vector3} The interpolated value.
  11255. */
  11256. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11257. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11258. target.x = 0;
  11259. target.y = 0;
  11260. if ( 'z' in target ) target.z = 0;
  11261. if ( 'w' in target ) target.w = 0;
  11262. return null;
  11263. }
  11264. target.setScalar( 0 );
  11265. target.addScaledVector( v1, _v3$2.x );
  11266. target.addScaledVector( v2, _v3$2.y );
  11267. target.addScaledVector( v3, _v3$2.z );
  11268. return target;
  11269. }
  11270. /**
  11271. * Computes the value barycentrically interpolated for the given attribute and indices.
  11272. *
  11273. * @param {BufferAttribute} attr - The attribute to interpolate.
  11274. * @param {number} i1 - Index of first vertex.
  11275. * @param {number} i2 - Index of second vertex.
  11276. * @param {number} i3 - Index of third vertex.
  11277. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11278. * @param {Vector3} target - The target vector that is used to store the method's result.
  11279. * @return {Vector3} The interpolated attribute value.
  11280. */
  11281. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11282. _v40.setScalar( 0 );
  11283. _v41.setScalar( 0 );
  11284. _v42.setScalar( 0 );
  11285. _v40.fromBufferAttribute( attr, i1 );
  11286. _v41.fromBufferAttribute( attr, i2 );
  11287. _v42.fromBufferAttribute( attr, i3 );
  11288. target.setScalar( 0 );
  11289. target.addScaledVector( _v40, barycoord.x );
  11290. target.addScaledVector( _v41, barycoord.y );
  11291. target.addScaledVector( _v42, barycoord.z );
  11292. return target;
  11293. }
  11294. /**
  11295. * Returns `true` if the triangle is oriented towards the given direction.
  11296. *
  11297. * @param {Vector3} a - The first corner of the triangle.
  11298. * @param {Vector3} b - The second corner of the triangle.
  11299. * @param {Vector3} c - The third corner of the triangle.
  11300. * @param {Vector3} direction - The (normalized) direction vector.
  11301. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11302. */
  11303. static isFrontFacing( a, b, c, direction ) {
  11304. _v0$2.subVectors( c, b );
  11305. _v1$3.subVectors( a, b );
  11306. // strictly front facing
  11307. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11308. }
  11309. /**
  11310. * Sets the triangle's vertices by copying the given values.
  11311. *
  11312. * @param {Vector3} a - The first corner of the triangle.
  11313. * @param {Vector3} b - The second corner of the triangle.
  11314. * @param {Vector3} c - The third corner of the triangle.
  11315. * @return {Triangle} A reference to this triangle.
  11316. */
  11317. set( a, b, c ) {
  11318. this.a.copy( a );
  11319. this.b.copy( b );
  11320. this.c.copy( c );
  11321. return this;
  11322. }
  11323. /**
  11324. * Sets the triangle's vertices by copying the given array values.
  11325. *
  11326. * @param {Array<Vector3>} points - An array with 3D points.
  11327. * @param {number} i0 - The array index representing the first corner of the triangle.
  11328. * @param {number} i1 - The array index representing the second corner of the triangle.
  11329. * @param {number} i2 - The array index representing the third corner of the triangle.
  11330. * @return {Triangle} A reference to this triangle.
  11331. */
  11332. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11333. this.a.copy( points[ i0 ] );
  11334. this.b.copy( points[ i1 ] );
  11335. this.c.copy( points[ i2 ] );
  11336. return this;
  11337. }
  11338. /**
  11339. * Sets the triangle's vertices by copying the given attribute values.
  11340. *
  11341. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11342. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11343. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11344. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11345. * @return {Triangle} A reference to this triangle.
  11346. */
  11347. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11348. this.a.fromBufferAttribute( attribute, i0 );
  11349. this.b.fromBufferAttribute( attribute, i1 );
  11350. this.c.fromBufferAttribute( attribute, i2 );
  11351. return this;
  11352. }
  11353. /**
  11354. * Returns a new triangle with copied values from this instance.
  11355. *
  11356. * @return {Triangle} A clone of this instance.
  11357. */
  11358. clone() {
  11359. return new this.constructor().copy( this );
  11360. }
  11361. /**
  11362. * Copies the values of the given triangle to this instance.
  11363. *
  11364. * @param {Triangle} triangle - The triangle to copy.
  11365. * @return {Triangle} A reference to this triangle.
  11366. */
  11367. copy( triangle ) {
  11368. this.a.copy( triangle.a );
  11369. this.b.copy( triangle.b );
  11370. this.c.copy( triangle.c );
  11371. return this;
  11372. }
  11373. /**
  11374. * Computes the area of the triangle.
  11375. *
  11376. * @return {number} The triangle's area.
  11377. */
  11378. getArea() {
  11379. _v0$2.subVectors( this.c, this.b );
  11380. _v1$3.subVectors( this.a, this.b );
  11381. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11382. }
  11383. /**
  11384. * Computes the midpoint of the triangle.
  11385. *
  11386. * @param {Vector3} target - The target vector that is used to store the method's result.
  11387. * @return {Vector3} The triangle's midpoint.
  11388. */
  11389. getMidpoint( target ) {
  11390. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11391. }
  11392. /**
  11393. * Computes the normal of the triangle.
  11394. *
  11395. * @param {Vector3} target - The target vector that is used to store the method's result.
  11396. * @return {Vector3} The triangle's normal.
  11397. */
  11398. getNormal( target ) {
  11399. return Triangle.getNormal( this.a, this.b, this.c, target );
  11400. }
  11401. /**
  11402. * Computes a plane the triangle lies within.
  11403. *
  11404. * @param {Plane} target - The target vector that is used to store the method's result.
  11405. * @return {Plane} The plane the triangle lies within.
  11406. */
  11407. getPlane( target ) {
  11408. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11409. }
  11410. /**
  11411. * Computes a barycentric coordinates from the given vector.
  11412. * Returns `null` if the triangle is degenerate.
  11413. *
  11414. * @param {Vector3} point - A point in 3D space.
  11415. * @param {Vector3} target - The target vector that is used to store the method's result.
  11416. * @return {?Vector3} The barycentric coordinates for the given point
  11417. */
  11418. getBarycoord( point, target ) {
  11419. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11420. }
  11421. /**
  11422. * Computes the value barycentrically interpolated for the given point on the
  11423. * triangle. Returns `null` if the triangle is degenerate.
  11424. *
  11425. * @param {Vector3} point - Position of interpolated point.
  11426. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11427. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11428. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11429. * @param {Vector3} target - The target vector that is used to store the method's result.
  11430. * @return {?Vector3} The interpolated value.
  11431. */
  11432. getInterpolation( point, v1, v2, v3, target ) {
  11433. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11434. }
  11435. /**
  11436. * Returns `true` if the given point, when projected onto the plane of the
  11437. * triangle, lies within the triangle.
  11438. *
  11439. * @param {Vector3} point - The point in 3D space to test.
  11440. * @return {boolean} Whether the given point, when projected onto the plane of the
  11441. * triangle, lies within the triangle or not.
  11442. */
  11443. containsPoint( point ) {
  11444. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11445. }
  11446. /**
  11447. * Returns `true` if the triangle is oriented towards the given direction.
  11448. *
  11449. * @param {Vector3} direction - The (normalized) direction vector.
  11450. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11451. */
  11452. isFrontFacing( direction ) {
  11453. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11454. }
  11455. /**
  11456. * Returns `true` if this triangle intersects with the given box.
  11457. *
  11458. * @param {Box3} box - The box to intersect.
  11459. * @return {boolean} Whether this triangle intersects with the given box or not.
  11460. */
  11461. intersectsBox( box ) {
  11462. return box.intersectsTriangle( this );
  11463. }
  11464. /**
  11465. * Returns the closest point on the triangle to the given point.
  11466. *
  11467. * @param {Vector3} p - The point to compute the closest point for.
  11468. * @param {Vector3} target - The target vector that is used to store the method's result.
  11469. * @return {Vector3} The closest point on the triangle.
  11470. */
  11471. closestPointToPoint( p, target ) {
  11472. const a = this.a, b = this.b, c = this.c;
  11473. let v, w;
  11474. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11475. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11476. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11477. // basically, we're distinguishing which of the voronoi regions of the triangle
  11478. // the point lies in with the minimum amount of redundant computation.
  11479. _vab.subVectors( b, a );
  11480. _vac.subVectors( c, a );
  11481. _vap.subVectors( p, a );
  11482. const d1 = _vab.dot( _vap );
  11483. const d2 = _vac.dot( _vap );
  11484. if ( d1 <= 0 && d2 <= 0 ) {
  11485. // vertex region of A; barycentric coords (1, 0, 0)
  11486. return target.copy( a );
  11487. }
  11488. _vbp.subVectors( p, b );
  11489. const d3 = _vab.dot( _vbp );
  11490. const d4 = _vac.dot( _vbp );
  11491. if ( d3 >= 0 && d4 <= d3 ) {
  11492. // vertex region of B; barycentric coords (0, 1, 0)
  11493. return target.copy( b );
  11494. }
  11495. const vc = d1 * d4 - d3 * d2;
  11496. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11497. v = d1 / ( d1 - d3 );
  11498. // edge region of AB; barycentric coords (1-v, v, 0)
  11499. return target.copy( a ).addScaledVector( _vab, v );
  11500. }
  11501. _vcp.subVectors( p, c );
  11502. const d5 = _vab.dot( _vcp );
  11503. const d6 = _vac.dot( _vcp );
  11504. if ( d6 >= 0 && d5 <= d6 ) {
  11505. // vertex region of C; barycentric coords (0, 0, 1)
  11506. return target.copy( c );
  11507. }
  11508. const vb = d5 * d2 - d1 * d6;
  11509. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11510. w = d2 / ( d2 - d6 );
  11511. // edge region of AC; barycentric coords (1-w, 0, w)
  11512. return target.copy( a ).addScaledVector( _vac, w );
  11513. }
  11514. const va = d3 * d6 - d5 * d4;
  11515. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11516. _vbc.subVectors( c, b );
  11517. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11518. // edge region of BC; barycentric coords (0, 1-w, w)
  11519. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11520. }
  11521. // face region
  11522. const denom = 1 / ( va + vb + vc );
  11523. // u = va * denom
  11524. v = vb * denom;
  11525. w = vc * denom;
  11526. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11527. }
  11528. /**
  11529. * Returns `true` if this triangle is equal with the given one.
  11530. *
  11531. * @param {Triangle} triangle - The triangle to test for equality.
  11532. * @return {boolean} Whether this triangle is equal with the given one.
  11533. */
  11534. equals( triangle ) {
  11535. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11536. }
  11537. }
  11538. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11539. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11540. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11541. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11542. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11543. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11544. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11545. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11546. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11547. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11548. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11549. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11550. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11551. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11552. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11553. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11554. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11555. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11556. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11557. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11558. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11559. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11560. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11561. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11562. const _hslA = { h: 0, s: 0, l: 0 };
  11563. const _hslB = { h: 0, s: 0, l: 0 };
  11564. function hue2rgb( p, q, t ) {
  11565. if ( t < 0 ) t += 1;
  11566. if ( t > 1 ) t -= 1;
  11567. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11568. if ( t < 1 / 2 ) return q;
  11569. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11570. return p;
  11571. }
  11572. /**
  11573. * A Color instance is represented by RGB components in the linear <i>working
  11574. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11575. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11576. * strings) are converted to the working color space automatically.
  11577. *
  11578. * ```js
  11579. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11580. * const color = new THREE.Color().setHex( 0x112233 );
  11581. * ```
  11582. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11583. * ```js
  11584. * // assumed already LinearSRGBColorSpace; no conversion
  11585. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11586. *
  11587. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11588. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11589. * ```
  11590. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11591. * see <i>Color management</i>. Iterating through a Color instance will yield
  11592. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11593. * in any of the following ways:
  11594. * ```js
  11595. * //empty constructor - will default white
  11596. * const color1 = new THREE.Color();
  11597. *
  11598. * //Hexadecimal color (recommended)
  11599. * const color2 = new THREE.Color( 0xff0000 );
  11600. *
  11601. * //RGB string
  11602. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11603. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11604. *
  11605. * //X11 color name - all 140 color names are supported.
  11606. * //Note the lack of CamelCase in the name
  11607. * const color5 = new THREE.Color( 'skyblue' );
  11608. * //HSL string
  11609. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11610. *
  11611. * //Separate RGB values between 0 and 1
  11612. * const color7 = new THREE.Color( 1, 0, 0 );
  11613. * ```
  11614. */
  11615. class Color {
  11616. /**
  11617. * Constructs a new color.
  11618. *
  11619. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11620. * and that method is used throughout the rest of the documentation.
  11621. *
  11622. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11623. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11624. * @param {number} [g] - The green component.
  11625. * @param {number} [b] - The blue component.
  11626. */
  11627. constructor( r, g, b ) {
  11628. /**
  11629. * This flag can be used for type testing.
  11630. *
  11631. * @type {boolean}
  11632. * @readonly
  11633. * @default true
  11634. */
  11635. this.isColor = true;
  11636. /**
  11637. * The red component.
  11638. *
  11639. * @type {number}
  11640. * @default 1
  11641. */
  11642. this.r = 1;
  11643. /**
  11644. * The green component.
  11645. *
  11646. * @type {number}
  11647. * @default 1
  11648. */
  11649. this.g = 1;
  11650. /**
  11651. * The blue component.
  11652. *
  11653. * @type {number}
  11654. * @default 1
  11655. */
  11656. this.b = 1;
  11657. return this.set( r, g, b );
  11658. }
  11659. /**
  11660. * Sets the colors's components from the given values.
  11661. *
  11662. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11663. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11664. * @param {number} [g] - The green component.
  11665. * @param {number} [b] - The blue component.
  11666. * @return {Color} A reference to this color.
  11667. */
  11668. set( r, g, b ) {
  11669. if ( g === undefined && b === undefined ) {
  11670. // r is THREE.Color, hex or string
  11671. const value = r;
  11672. if ( value && value.isColor ) {
  11673. this.copy( value );
  11674. } else if ( typeof value === 'number' ) {
  11675. this.setHex( value );
  11676. } else if ( typeof value === 'string' ) {
  11677. this.setStyle( value );
  11678. }
  11679. } else {
  11680. this.setRGB( r, g, b );
  11681. }
  11682. return this;
  11683. }
  11684. /**
  11685. * Sets the colors's components to the given scalar value.
  11686. *
  11687. * @param {number} scalar - The scalar value.
  11688. * @return {Color} A reference to this color.
  11689. */
  11690. setScalar( scalar ) {
  11691. this.r = scalar;
  11692. this.g = scalar;
  11693. this.b = scalar;
  11694. return this;
  11695. }
  11696. /**
  11697. * Sets this color from a hexadecimal value.
  11698. *
  11699. * @param {number} hex - The hexadecimal value.
  11700. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11701. * @return {Color} A reference to this color.
  11702. */
  11703. setHex( hex, colorSpace = SRGBColorSpace ) {
  11704. hex = Math.floor( hex );
  11705. this.r = ( hex >> 16 & 255 ) / 255;
  11706. this.g = ( hex >> 8 & 255 ) / 255;
  11707. this.b = ( hex & 255 ) / 255;
  11708. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11709. return this;
  11710. }
  11711. /**
  11712. * Sets this color from RGB values.
  11713. *
  11714. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11715. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11716. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11717. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11718. * @return {Color} A reference to this color.
  11719. */
  11720. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11721. this.r = r;
  11722. this.g = g;
  11723. this.b = b;
  11724. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11725. return this;
  11726. }
  11727. /**
  11728. * Sets this color from RGB values.
  11729. *
  11730. * @param {number} h - Hue value between `0.0` and `1.0`.
  11731. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11732. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11733. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11734. * @return {Color} A reference to this color.
  11735. */
  11736. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11737. // h,s,l ranges are in 0.0 - 1.0
  11738. h = euclideanModulo( h, 1 );
  11739. s = clamp( s, 0, 1 );
  11740. l = clamp( l, 0, 1 );
  11741. if ( s === 0 ) {
  11742. this.r = this.g = this.b = l;
  11743. } else {
  11744. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11745. const q = ( 2 * l ) - p;
  11746. this.r = hue2rgb( q, p, h + 1 / 3 );
  11747. this.g = hue2rgb( q, p, h );
  11748. this.b = hue2rgb( q, p, h - 1 / 3 );
  11749. }
  11750. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11751. return this;
  11752. }
  11753. /**
  11754. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11755. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11756. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11757. * all 140 color names are supported).
  11758. *
  11759. * @param {string} style - Color as a CSS-style string.
  11760. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11761. * @return {Color} A reference to this color.
  11762. */
  11763. setStyle( style, colorSpace = SRGBColorSpace ) {
  11764. function handleAlpha( string ) {
  11765. if ( string === undefined ) return;
  11766. if ( parseFloat( string ) < 1 ) {
  11767. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11768. }
  11769. }
  11770. let m;
  11771. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11772. // rgb / hsl
  11773. let color;
  11774. const name = m[ 1 ];
  11775. const components = m[ 2 ];
  11776. switch ( name ) {
  11777. case 'rgb':
  11778. case 'rgba':
  11779. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11780. // rgb(255,0,0) rgba(255,0,0,0.5)
  11781. handleAlpha( color[ 4 ] );
  11782. return this.setRGB(
  11783. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11784. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11785. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11786. colorSpace
  11787. );
  11788. }
  11789. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11790. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11791. handleAlpha( color[ 4 ] );
  11792. return this.setRGB(
  11793. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11794. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11795. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11796. colorSpace
  11797. );
  11798. }
  11799. break;
  11800. case 'hsl':
  11801. case 'hsla':
  11802. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11803. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11804. handleAlpha( color[ 4 ] );
  11805. return this.setHSL(
  11806. parseFloat( color[ 1 ] ) / 360,
  11807. parseFloat( color[ 2 ] ) / 100,
  11808. parseFloat( color[ 3 ] ) / 100,
  11809. colorSpace
  11810. );
  11811. }
  11812. break;
  11813. default:
  11814. console.warn( 'THREE.Color: Unknown color model ' + style );
  11815. }
  11816. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11817. // hex color
  11818. const hex = m[ 1 ];
  11819. const size = hex.length;
  11820. if ( size === 3 ) {
  11821. // #ff0
  11822. return this.setRGB(
  11823. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11824. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11825. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11826. colorSpace
  11827. );
  11828. } else if ( size === 6 ) {
  11829. // #ff0000
  11830. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11831. } else {
  11832. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11833. }
  11834. } else if ( style && style.length > 0 ) {
  11835. return this.setColorName( style, colorSpace );
  11836. }
  11837. return this;
  11838. }
  11839. /**
  11840. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11841. * you don't need the other CSS-style formats.
  11842. *
  11843. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11844. * ```js
  11845. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11846. * ```
  11847. *
  11848. * @param {string} style - The color name.
  11849. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11850. * @return {Color} A reference to this color.
  11851. */
  11852. setColorName( style, colorSpace = SRGBColorSpace ) {
  11853. // color keywords
  11854. const hex = _colorKeywords[ style.toLowerCase() ];
  11855. if ( hex !== undefined ) {
  11856. // red
  11857. this.setHex( hex, colorSpace );
  11858. } else {
  11859. // unknown color
  11860. console.warn( 'THREE.Color: Unknown color ' + style );
  11861. }
  11862. return this;
  11863. }
  11864. /**
  11865. * Returns a new color with copied values from this instance.
  11866. *
  11867. * @return {Color} A clone of this instance.
  11868. */
  11869. clone() {
  11870. return new this.constructor( this.r, this.g, this.b );
  11871. }
  11872. /**
  11873. * Copies the values of the given color to this instance.
  11874. *
  11875. * @param {Color} color - The color to copy.
  11876. * @return {Color} A reference to this color.
  11877. */
  11878. copy( color ) {
  11879. this.r = color.r;
  11880. this.g = color.g;
  11881. this.b = color.b;
  11882. return this;
  11883. }
  11884. /**
  11885. * Copies the given color into this color, and then converts this color from
  11886. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11887. *
  11888. * @param {Color} color - The color to copy/convert.
  11889. * @return {Color} A reference to this color.
  11890. */
  11891. copySRGBToLinear( color ) {
  11892. this.r = SRGBToLinear( color.r );
  11893. this.g = SRGBToLinear( color.g );
  11894. this.b = SRGBToLinear( color.b );
  11895. return this;
  11896. }
  11897. /**
  11898. * Copies the given color into this color, and then converts this color from
  11899. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11900. *
  11901. * @param {Color} color - The color to copy/convert.
  11902. * @return {Color} A reference to this color.
  11903. */
  11904. copyLinearToSRGB( color ) {
  11905. this.r = LinearToSRGB( color.r );
  11906. this.g = LinearToSRGB( color.g );
  11907. this.b = LinearToSRGB( color.b );
  11908. return this;
  11909. }
  11910. /**
  11911. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11912. *
  11913. * @return {Color} A reference to this color.
  11914. */
  11915. convertSRGBToLinear() {
  11916. this.copySRGBToLinear( this );
  11917. return this;
  11918. }
  11919. /**
  11920. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11921. *
  11922. * @return {Color} A reference to this color.
  11923. */
  11924. convertLinearToSRGB() {
  11925. this.copyLinearToSRGB( this );
  11926. return this;
  11927. }
  11928. /**
  11929. * Returns the hexadecimal value of this color.
  11930. *
  11931. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11932. * @return {number} The hexadecimal value.
  11933. */
  11934. getHex( colorSpace = SRGBColorSpace ) {
  11935. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11936. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  11937. }
  11938. /**
  11939. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11940. *
  11941. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11942. * @return {string} The hexadecimal value as a string.
  11943. */
  11944. getHexString( colorSpace = SRGBColorSpace ) {
  11945. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11946. }
  11947. /**
  11948. * Converts the colors RGB values into the HSL format and stores them into the
  11949. * given target object.
  11950. *
  11951. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11952. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11953. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11954. */
  11955. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11956. // h,s,l ranges are in 0.0 - 1.0
  11957. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11958. const r = _color.r, g = _color.g, b = _color.b;
  11959. const max = Math.max( r, g, b );
  11960. const min = Math.min( r, g, b );
  11961. let hue, saturation;
  11962. const lightness = ( min + max ) / 2.0;
  11963. if ( min === max ) {
  11964. hue = 0;
  11965. saturation = 0;
  11966. } else {
  11967. const delta = max - min;
  11968. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11969. switch ( max ) {
  11970. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11971. case g: hue = ( b - r ) / delta + 2; break;
  11972. case b: hue = ( r - g ) / delta + 4; break;
  11973. }
  11974. hue /= 6;
  11975. }
  11976. target.h = hue;
  11977. target.s = saturation;
  11978. target.l = lightness;
  11979. return target;
  11980. }
  11981. /**
  11982. * Returns the RGB values of this color and stores them into the given target object.
  11983. *
  11984. * @param {Color} target - The target color that is used to store the method's result.
  11985. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11986. * @return {Color} The RGB representation of this color.
  11987. */
  11988. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11989. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11990. target.r = _color.r;
  11991. target.g = _color.g;
  11992. target.b = _color.b;
  11993. return target;
  11994. }
  11995. /**
  11996. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11997. *
  11998. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11999. * @return {string} The CSS representation of this color.
  12000. */
  12001. getStyle( colorSpace = SRGBColorSpace ) {
  12002. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12003. const r = _color.r, g = _color.g, b = _color.b;
  12004. if ( colorSpace !== SRGBColorSpace ) {
  12005. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12006. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12007. }
  12008. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12009. }
  12010. /**
  12011. * Adds the given HSL values to this color's values.
  12012. * Internally, this converts the color's RGB values to HSL, adds HSL
  12013. * and then converts the color back to RGB.
  12014. *
  12015. * @param {number} h - Hue value between `0.0` and `1.0`.
  12016. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12017. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12018. * @return {Color} A reference to this color.
  12019. */
  12020. offsetHSL( h, s, l ) {
  12021. this.getHSL( _hslA );
  12022. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12023. }
  12024. /**
  12025. * Adds the RGB values of the given color to the RGB values of this color.
  12026. *
  12027. * @param {Color} color - The color to add.
  12028. * @return {Color} A reference to this color.
  12029. */
  12030. add( color ) {
  12031. this.r += color.r;
  12032. this.g += color.g;
  12033. this.b += color.b;
  12034. return this;
  12035. }
  12036. /**
  12037. * Adds the RGB values of the given colors and stores the result in this instance.
  12038. *
  12039. * @param {Color} color1 - The first color.
  12040. * @param {Color} color2 - The second color.
  12041. * @return {Color} A reference to this color.
  12042. */
  12043. addColors( color1, color2 ) {
  12044. this.r = color1.r + color2.r;
  12045. this.g = color1.g + color2.g;
  12046. this.b = color1.b + color2.b;
  12047. return this;
  12048. }
  12049. /**
  12050. * Adds the given scalar value to the RGB values of this color.
  12051. *
  12052. * @param {number} s - The scalar to add.
  12053. * @return {Color} A reference to this color.
  12054. */
  12055. addScalar( s ) {
  12056. this.r += s;
  12057. this.g += s;
  12058. this.b += s;
  12059. return this;
  12060. }
  12061. /**
  12062. * Subtracts the RGB values of the given color from the RGB values of this color.
  12063. *
  12064. * @param {Color} color - The color to subtract.
  12065. * @return {Color} A reference to this color.
  12066. */
  12067. sub( color ) {
  12068. this.r = Math.max( 0, this.r - color.r );
  12069. this.g = Math.max( 0, this.g - color.g );
  12070. this.b = Math.max( 0, this.b - color.b );
  12071. return this;
  12072. }
  12073. /**
  12074. * Multiplies the RGB values of the given color with the RGB values of this color.
  12075. *
  12076. * @param {Color} color - The color to multiply.
  12077. * @return {Color} A reference to this color.
  12078. */
  12079. multiply( color ) {
  12080. this.r *= color.r;
  12081. this.g *= color.g;
  12082. this.b *= color.b;
  12083. return this;
  12084. }
  12085. /**
  12086. * Multiplies the given scalar value with the RGB values of this color.
  12087. *
  12088. * @param {number} s - The scalar to multiply.
  12089. * @return {Color} A reference to this color.
  12090. */
  12091. multiplyScalar( s ) {
  12092. this.r *= s;
  12093. this.g *= s;
  12094. this.b *= s;
  12095. return this;
  12096. }
  12097. /**
  12098. * Linearly interpolates this color's RGB values toward the RGB values of the
  12099. * given color. The alpha argument can be thought of as the ratio between
  12100. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12101. *
  12102. * @param {Color} color - The color to converge on.
  12103. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12104. * @return {Color} A reference to this color.
  12105. */
  12106. lerp( color, alpha ) {
  12107. this.r += ( color.r - this.r ) * alpha;
  12108. this.g += ( color.g - this.g ) * alpha;
  12109. this.b += ( color.b - this.b ) * alpha;
  12110. return this;
  12111. }
  12112. /**
  12113. * Linearly interpolates between the given colors and stores the result in this instance.
  12114. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12115. * is the first and `1.0` is the second color.
  12116. *
  12117. * @param {Color} color1 - The first color.
  12118. * @param {Color} color2 - The second color.
  12119. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12120. * @return {Color} A reference to this color.
  12121. */
  12122. lerpColors( color1, color2, alpha ) {
  12123. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12124. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12125. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12126. return this;
  12127. }
  12128. /**
  12129. * Linearly interpolates this color's HSL values toward the HSL values of the
  12130. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12131. * from one color to the other, but instead going through all the hues in between
  12132. * those two colors. The alpha argument can be thought of as the ratio between
  12133. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12134. *
  12135. * @param {Color} color - The color to converge on.
  12136. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12137. * @return {Color} A reference to this color.
  12138. */
  12139. lerpHSL( color, alpha ) {
  12140. this.getHSL( _hslA );
  12141. color.getHSL( _hslB );
  12142. const h = lerp( _hslA.h, _hslB.h, alpha );
  12143. const s = lerp( _hslA.s, _hslB.s, alpha );
  12144. const l = lerp( _hslA.l, _hslB.l, alpha );
  12145. this.setHSL( h, s, l );
  12146. return this;
  12147. }
  12148. /**
  12149. * Sets the color's RGB components from the given 3D vector.
  12150. *
  12151. * @param {Vector3} v - The vector to set.
  12152. * @return {Color} A reference to this color.
  12153. */
  12154. setFromVector3( v ) {
  12155. this.r = v.x;
  12156. this.g = v.y;
  12157. this.b = v.z;
  12158. return this;
  12159. }
  12160. /**
  12161. * Transforms this color with the given 3x3 matrix.
  12162. *
  12163. * @param {Matrix3} m - The matrix.
  12164. * @return {Color} A reference to this color.
  12165. */
  12166. applyMatrix3( m ) {
  12167. const r = this.r, g = this.g, b = this.b;
  12168. const e = m.elements;
  12169. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12170. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12171. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12172. return this;
  12173. }
  12174. /**
  12175. * Returns `true` if this color is equal with the given one.
  12176. *
  12177. * @param {Color} c - The color to test for equality.
  12178. * @return {boolean} Whether this bounding color is equal with the given one.
  12179. */
  12180. equals( c ) {
  12181. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12182. }
  12183. /**
  12184. * Sets this color's RGB components from the given array.
  12185. *
  12186. * @param {Array<number>} array - An array holding the RGB values.
  12187. * @param {number} [offset=0] - The offset into the array.
  12188. * @return {Color} A reference to this color.
  12189. */
  12190. fromArray( array, offset = 0 ) {
  12191. this.r = array[ offset ];
  12192. this.g = array[ offset + 1 ];
  12193. this.b = array[ offset + 2 ];
  12194. return this;
  12195. }
  12196. /**
  12197. * Writes the RGB components of this color to the given array. If no array is provided,
  12198. * the method returns a new instance.
  12199. *
  12200. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12201. * @param {number} [offset=0] - Index of the first element in the array.
  12202. * @return {Array<number>} The color components.
  12203. */
  12204. toArray( array = [], offset = 0 ) {
  12205. array[ offset ] = this.r;
  12206. array[ offset + 1 ] = this.g;
  12207. array[ offset + 2 ] = this.b;
  12208. return array;
  12209. }
  12210. /**
  12211. * Sets the components of this color from the given buffer attribute.
  12212. *
  12213. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12214. * @param {number} index - The index into the attribute.
  12215. * @return {Color} A reference to this color.
  12216. */
  12217. fromBufferAttribute( attribute, index ) {
  12218. this.r = attribute.getX( index );
  12219. this.g = attribute.getY( index );
  12220. this.b = attribute.getZ( index );
  12221. return this;
  12222. }
  12223. /**
  12224. * This methods defines the serialization result of this class. Returns the color
  12225. * as a hexadecimal value.
  12226. *
  12227. * @return {number} The hexadecimal value.
  12228. */
  12229. toJSON() {
  12230. return this.getHex();
  12231. }
  12232. *[ Symbol.iterator ]() {
  12233. yield this.r;
  12234. yield this.g;
  12235. yield this.b;
  12236. }
  12237. }
  12238. const _color = /*@__PURE__*/ new Color();
  12239. /**
  12240. * A dictionary with X11 color names.
  12241. *
  12242. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12243. *
  12244. * @static
  12245. * @type {Object}
  12246. */
  12247. Color.NAMES = _colorKeywords;
  12248. let _materialId = 0;
  12249. /**
  12250. * Abstract base class for materials.
  12251. *
  12252. * Materials define the appearance of renderable 3D objects.
  12253. *
  12254. * @abstract
  12255. * @augments EventDispatcher
  12256. */
  12257. class Material extends EventDispatcher {
  12258. /**
  12259. * Constructs a new material.
  12260. */
  12261. constructor() {
  12262. super();
  12263. /**
  12264. * This flag can be used for type testing.
  12265. *
  12266. * @type {boolean}
  12267. * @readonly
  12268. * @default true
  12269. */
  12270. this.isMaterial = true;
  12271. /**
  12272. * The ID of the material.
  12273. *
  12274. * @name Material#id
  12275. * @type {number}
  12276. * @readonly
  12277. */
  12278. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12279. /**
  12280. * The UUID of the material.
  12281. *
  12282. * @type {string}
  12283. * @readonly
  12284. */
  12285. this.uuid = generateUUID();
  12286. /**
  12287. * The name of the material.
  12288. *
  12289. * @type {string}
  12290. */
  12291. this.name = '';
  12292. /**
  12293. * The type property is used for detecting the object type
  12294. * in context of serialization/deserialization.
  12295. *
  12296. * @type {string}
  12297. * @readonly
  12298. */
  12299. this.type = 'Material';
  12300. /**
  12301. * Defines the blending type of the material.
  12302. *
  12303. * It must be set to `CustomBlending` if custom blending properties like
  12304. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12305. * should have any effect.
  12306. *
  12307. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12308. * @default NormalBlending
  12309. */
  12310. this.blending = NormalBlending;
  12311. /**
  12312. * Defines which side of faces will be rendered - front, back or both.
  12313. *
  12314. * @type {(FrontSide|BackSide|DoubleSide)}
  12315. * @default FrontSide
  12316. */
  12317. this.side = FrontSide;
  12318. /**
  12319. * If set to `true`, vertex colors should be used.
  12320. *
  12321. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12322. * four (RGBA) component color buffer attribute is used.
  12323. *
  12324. * @type {boolean}
  12325. * @default false
  12326. */
  12327. this.vertexColors = false;
  12328. /**
  12329. * Defines how transparent the material is.
  12330. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12331. *
  12332. * If the {@link Material#transparent} is not set to `true`,
  12333. * the material will remain fully opaque and this value will only affect its color.
  12334. *
  12335. * @type {number}
  12336. * @default 1
  12337. */
  12338. this.opacity = 1;
  12339. /**
  12340. * Defines whether this material is transparent. This has an effect on
  12341. * rendering as transparent objects need special treatment and are rendered
  12342. * after non-transparent objects.
  12343. *
  12344. * When set to true, the extent to which the material is transparent is
  12345. * controlled by {@link Material#opacity}.
  12346. *
  12347. * @type {boolean}
  12348. * @default false
  12349. */
  12350. this.transparent = false;
  12351. /**
  12352. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12353. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12354. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12355. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12356. *
  12357. * @type {boolean}
  12358. * @default false
  12359. */
  12360. this.alphaHash = false;
  12361. /**
  12362. * Defines the blending source factor.
  12363. *
  12364. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12365. * @default SrcAlphaFactor
  12366. */
  12367. this.blendSrc = SrcAlphaFactor;
  12368. /**
  12369. * Defines the blending destination factor.
  12370. *
  12371. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12372. * @default OneMinusSrcAlphaFactor
  12373. */
  12374. this.blendDst = OneMinusSrcAlphaFactor;
  12375. /**
  12376. * Defines the blending equation.
  12377. *
  12378. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12379. * @default AddEquation
  12380. */
  12381. this.blendEquation = AddEquation;
  12382. /**
  12383. * Defines the blending source alpha factor.
  12384. *
  12385. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12386. * @default null
  12387. */
  12388. this.blendSrcAlpha = null;
  12389. /**
  12390. * Defines the blending destination alpha factor.
  12391. *
  12392. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12393. * @default null
  12394. */
  12395. this.blendDstAlpha = null;
  12396. /**
  12397. * Defines the blending equation of the alpha channel.
  12398. *
  12399. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12400. * @default null
  12401. */
  12402. this.blendEquationAlpha = null;
  12403. /**
  12404. * Represents the RGB values of the constant blend color.
  12405. *
  12406. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12407. *
  12408. * @type {Color}
  12409. * @default (0,0,0)
  12410. */
  12411. this.blendColor = new Color( 0, 0, 0 );
  12412. /**
  12413. * Represents the alpha value of the constant blend color.
  12414. *
  12415. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12416. *
  12417. * @type {number}
  12418. * @default 0
  12419. */
  12420. this.blendAlpha = 0;
  12421. /**
  12422. * Defines the depth function.
  12423. *
  12424. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12425. * @default LessEqualDepth
  12426. */
  12427. this.depthFunc = LessEqualDepth;
  12428. /**
  12429. * Whether to have depth test enabled when rendering this material.
  12430. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12431. *
  12432. * @type {boolean}
  12433. * @default true
  12434. */
  12435. this.depthTest = true;
  12436. /**
  12437. * Whether rendering this material has any effect on the depth buffer.
  12438. *
  12439. * When drawing 2D overlays it can be useful to disable the depth writing in
  12440. * order to layer several things together without creating z-index artifacts.
  12441. *
  12442. * @type {boolean}
  12443. * @default true
  12444. */
  12445. this.depthWrite = true;
  12446. /**
  12447. * The bit mask to use when writing to the stencil buffer.
  12448. *
  12449. * @type {number}
  12450. * @default 0xff
  12451. */
  12452. this.stencilWriteMask = 0xff;
  12453. /**
  12454. * The stencil comparison function to use.
  12455. *
  12456. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12457. * @default AlwaysStencilFunc
  12458. */
  12459. this.stencilFunc = AlwaysStencilFunc;
  12460. /**
  12461. * The value to use when performing stencil comparisons or stencil operations.
  12462. *
  12463. * @type {number}
  12464. * @default 0
  12465. */
  12466. this.stencilRef = 0;
  12467. /**
  12468. * The bit mask to use when comparing against the stencil buffer.
  12469. *
  12470. * @type {number}
  12471. * @default 0xff
  12472. */
  12473. this.stencilFuncMask = 0xff;
  12474. /**
  12475. * Which stencil operation to perform when the comparison function returns `false`.
  12476. *
  12477. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12478. * @default KeepStencilOp
  12479. */
  12480. this.stencilFail = KeepStencilOp;
  12481. /**
  12482. * Which stencil operation to perform when the comparison function returns
  12483. * `true` but the depth test fails.
  12484. *
  12485. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12486. * @default KeepStencilOp
  12487. */
  12488. this.stencilZFail = KeepStencilOp;
  12489. /**
  12490. * Which stencil operation to perform when the comparison function returns
  12491. * `true` and the depth test passes.
  12492. *
  12493. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12494. * @default KeepStencilOp
  12495. */
  12496. this.stencilZPass = KeepStencilOp;
  12497. /**
  12498. * Whether stencil operations are performed against the stencil buffer. In
  12499. * order to perform writes or comparisons against the stencil buffer this
  12500. * value must be `true`.
  12501. *
  12502. * @type {boolean}
  12503. * @default false
  12504. */
  12505. this.stencilWrite = false;
  12506. /**
  12507. * User-defined clipping planes specified as THREE.Plane objects in world
  12508. * space. These planes apply to the objects this material is attached to.
  12509. * Points in space whose signed distance to the plane is negative are clipped
  12510. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12511. * be `true`.
  12512. *
  12513. * @type {?Array<Plane>}
  12514. * @default null
  12515. */
  12516. this.clippingPlanes = null;
  12517. /**
  12518. * Changes the behavior of clipping planes so that only their intersection is
  12519. * clipped, rather than their union.
  12520. *
  12521. * @type {boolean}
  12522. * @default false
  12523. */
  12524. this.clipIntersection = false;
  12525. /**
  12526. * Defines whether to clip shadows according to the clipping planes specified
  12527. * on this material.
  12528. *
  12529. * @type {boolean}
  12530. * @default false
  12531. */
  12532. this.clipShadows = false;
  12533. /**
  12534. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12535. * is determined as follows:
  12536. *
  12537. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12538. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12539. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12540. *
  12541. * @type {?(FrontSide|BackSide|DoubleSide)}
  12542. * @default null
  12543. */
  12544. this.shadowSide = null;
  12545. /**
  12546. * Whether to render the material's color.
  12547. *
  12548. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12549. * objects that occlude other objects.
  12550. *
  12551. * @type {boolean}
  12552. * @default true
  12553. */
  12554. this.colorWrite = true;
  12555. /**
  12556. * Override the renderer's default precision for this material.
  12557. *
  12558. * @type {?('highp'|'mediump'|'lowp')}
  12559. * @default null
  12560. */
  12561. this.precision = null;
  12562. /**
  12563. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12564. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12565. * The offset is added before the depth test is performed and before the value is written
  12566. * into the depth buffer.
  12567. *
  12568. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12569. * rendering solids with highlighted edges.
  12570. *
  12571. * @type {boolean}
  12572. * @default false
  12573. */
  12574. this.polygonOffset = false;
  12575. /**
  12576. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12577. *
  12578. * @type {number}
  12579. * @default 0
  12580. */
  12581. this.polygonOffsetFactor = 0;
  12582. /**
  12583. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12584. *
  12585. * @type {number}
  12586. * @default 0
  12587. */
  12588. this.polygonOffsetUnits = 0;
  12589. /**
  12590. * Whether to apply dithering to the color to remove the appearance of banding.
  12591. *
  12592. * @type {boolean}
  12593. * @default false
  12594. */
  12595. this.dithering = false;
  12596. /**
  12597. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12598. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12599. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12600. *
  12601. * @type {boolean}
  12602. * @default false
  12603. */
  12604. this.alphaToCoverage = false;
  12605. /**
  12606. * Whether to premultiply the alpha (transparency) value.
  12607. *
  12608. * @type {boolean}
  12609. * @default false
  12610. */
  12611. this.premultipliedAlpha = false;
  12612. /**
  12613. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12614. *
  12615. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12616. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12617. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12618. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12619. * disable the two pass rendering to avoid performance issues.
  12620. *
  12621. * @type {boolean}
  12622. * @default false
  12623. */
  12624. this.forceSinglePass = false;
  12625. /**
  12626. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12627. *
  12628. * @type {boolean}
  12629. * @default true
  12630. */
  12631. this.allowOverride = true;
  12632. /**
  12633. * Defines whether 3D objects using this material are visible.
  12634. *
  12635. * @type {boolean}
  12636. * @default true
  12637. */
  12638. this.visible = true;
  12639. /**
  12640. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12641. *
  12642. * It is ignored when rendering to a render target or using post processing or when using
  12643. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12644. *
  12645. * @type {boolean}
  12646. * @default true
  12647. */
  12648. this.toneMapped = true;
  12649. /**
  12650. * An object that can be used to store custom data about the Material. It
  12651. * should not hold references to functions as these will not be cloned.
  12652. *
  12653. * @type {Object}
  12654. */
  12655. this.userData = {};
  12656. /**
  12657. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12658. *
  12659. * @type {number}
  12660. * @readonly
  12661. * @default 0
  12662. */
  12663. this.version = 0;
  12664. this._alphaTest = 0;
  12665. }
  12666. /**
  12667. * Sets the alpha value to be used when running an alpha test. The material
  12668. * will not be rendered if the opacity is lower than this value.
  12669. *
  12670. * @type {number}
  12671. * @readonly
  12672. * @default 0
  12673. */
  12674. get alphaTest() {
  12675. return this._alphaTest;
  12676. }
  12677. set alphaTest( value ) {
  12678. if ( this._alphaTest > 0 !== value > 0 ) {
  12679. this.version ++;
  12680. }
  12681. this._alphaTest = value;
  12682. }
  12683. /**
  12684. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12685. *
  12686. * This method can only be used when rendering with {@link WebGLRenderer}.
  12687. *
  12688. * @param {WebGLRenderer} renderer - The renderer.
  12689. * @param {Scene} scene - The scene.
  12690. * @param {Camera} camera - The camera that is used to render the scene.
  12691. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12692. * @param {Object3D} object - The 3D object.
  12693. * @param {Object} group - The geometry group data.
  12694. */
  12695. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12696. /**
  12697. * An optional callback that is executed immediately before the shader
  12698. * program is compiled. This function is called with the shader source code
  12699. * as a parameter. Useful for the modification of built-in materials.
  12700. *
  12701. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12702. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12703. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12704. *
  12705. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12706. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12707. */
  12708. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12709. /**
  12710. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12711. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12712. * shader or recompile the shader for this material as needed.
  12713. *
  12714. * This method can only be used when rendering with {@link WebGLRenderer}.
  12715. *
  12716. * @return {string} The custom program cache key.
  12717. */
  12718. customProgramCacheKey() {
  12719. return this.onBeforeCompile.toString();
  12720. }
  12721. /**
  12722. * This method can be used to set default values from parameter objects.
  12723. * It is a generic implementation so it can be used with different types
  12724. * of materials.
  12725. *
  12726. * @param {Object} [values] - The material values to set.
  12727. */
  12728. setValues( values ) {
  12729. if ( values === undefined ) return;
  12730. for ( const key in values ) {
  12731. const newValue = values[ key ];
  12732. if ( newValue === undefined ) {
  12733. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12734. continue;
  12735. }
  12736. const currentValue = this[ key ];
  12737. if ( currentValue === undefined ) {
  12738. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12739. continue;
  12740. }
  12741. if ( currentValue && currentValue.isColor ) {
  12742. currentValue.set( newValue );
  12743. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12744. currentValue.copy( newValue );
  12745. } else {
  12746. this[ key ] = newValue;
  12747. }
  12748. }
  12749. }
  12750. /**
  12751. * Serializes the material into JSON.
  12752. *
  12753. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12754. * @return {Object} A JSON object representing the serialized material.
  12755. * @see {@link ObjectLoader#parse}
  12756. */
  12757. toJSON( meta ) {
  12758. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12759. if ( isRootObject ) {
  12760. meta = {
  12761. textures: {},
  12762. images: {}
  12763. };
  12764. }
  12765. const data = {
  12766. metadata: {
  12767. version: 4.7,
  12768. type: 'Material',
  12769. generator: 'Material.toJSON'
  12770. }
  12771. };
  12772. // standard Material serialization
  12773. data.uuid = this.uuid;
  12774. data.type = this.type;
  12775. if ( this.name !== '' ) data.name = this.name;
  12776. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12777. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12778. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12779. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12780. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12781. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12782. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12783. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12784. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12785. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12786. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12787. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12788. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12789. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12790. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12791. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12792. }
  12793. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12794. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12795. }
  12796. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12797. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12798. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12799. }
  12800. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12801. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12802. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12803. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12804. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12805. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12806. }
  12807. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12808. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12809. }
  12810. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12811. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12812. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12813. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12814. }
  12815. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12816. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12817. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12818. if ( this.lightMap && this.lightMap.isTexture ) {
  12819. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12820. data.lightMapIntensity = this.lightMapIntensity;
  12821. }
  12822. if ( this.aoMap && this.aoMap.isTexture ) {
  12823. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12824. data.aoMapIntensity = this.aoMapIntensity;
  12825. }
  12826. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12827. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12828. data.bumpScale = this.bumpScale;
  12829. }
  12830. if ( this.normalMap && this.normalMap.isTexture ) {
  12831. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12832. data.normalMapType = this.normalMapType;
  12833. data.normalScale = this.normalScale.toArray();
  12834. }
  12835. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12836. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12837. data.displacementScale = this.displacementScale;
  12838. data.displacementBias = this.displacementBias;
  12839. }
  12840. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12841. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12842. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12843. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12844. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12845. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12846. if ( this.envMap && this.envMap.isTexture ) {
  12847. data.envMap = this.envMap.toJSON( meta ).uuid;
  12848. if ( this.combine !== undefined ) data.combine = this.combine;
  12849. }
  12850. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12851. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12852. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12853. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12854. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12855. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12856. }
  12857. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12858. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12859. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12860. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12861. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12862. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12863. if ( this.size !== undefined ) data.size = this.size;
  12864. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12865. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12866. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12867. if ( this.side !== FrontSide ) data.side = this.side;
  12868. if ( this.vertexColors === true ) data.vertexColors = true;
  12869. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12870. if ( this.transparent === true ) data.transparent = true;
  12871. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12872. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12873. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12874. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12875. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12876. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12877. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12878. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12879. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12880. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12881. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12882. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12883. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12884. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12885. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12886. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12887. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12888. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12889. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12890. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12891. // rotation (SpriteMaterial)
  12892. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12893. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12894. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12895. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12896. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12897. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12898. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12899. if ( this.scale !== undefined ) data.scale = this.scale;
  12900. if ( this.dithering === true ) data.dithering = true;
  12901. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12902. if ( this.alphaHash === true ) data.alphaHash = true;
  12903. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12904. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12905. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12906. if ( this.wireframe === true ) data.wireframe = true;
  12907. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12908. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12909. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12910. if ( this.flatShading === true ) data.flatShading = true;
  12911. if ( this.visible === false ) data.visible = false;
  12912. if ( this.toneMapped === false ) data.toneMapped = false;
  12913. if ( this.fog === false ) data.fog = false;
  12914. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12915. // TODO: Copied from Object3D.toJSON
  12916. function extractFromCache( cache ) {
  12917. const values = [];
  12918. for ( const key in cache ) {
  12919. const data = cache[ key ];
  12920. delete data.metadata;
  12921. values.push( data );
  12922. }
  12923. return values;
  12924. }
  12925. if ( isRootObject ) {
  12926. const textures = extractFromCache( meta.textures );
  12927. const images = extractFromCache( meta.images );
  12928. if ( textures.length > 0 ) data.textures = textures;
  12929. if ( images.length > 0 ) data.images = images;
  12930. }
  12931. return data;
  12932. }
  12933. /**
  12934. * Returns a new material with copied values from this instance.
  12935. *
  12936. * @return {Material} A clone of this instance.
  12937. */
  12938. clone() {
  12939. return new this.constructor().copy( this );
  12940. }
  12941. /**
  12942. * Copies the values of the given material to this instance.
  12943. *
  12944. * @param {Material} source - The material to copy.
  12945. * @return {Material} A reference to this instance.
  12946. */
  12947. copy( source ) {
  12948. this.name = source.name;
  12949. this.blending = source.blending;
  12950. this.side = source.side;
  12951. this.vertexColors = source.vertexColors;
  12952. this.opacity = source.opacity;
  12953. this.transparent = source.transparent;
  12954. this.blendSrc = source.blendSrc;
  12955. this.blendDst = source.blendDst;
  12956. this.blendEquation = source.blendEquation;
  12957. this.blendSrcAlpha = source.blendSrcAlpha;
  12958. this.blendDstAlpha = source.blendDstAlpha;
  12959. this.blendEquationAlpha = source.blendEquationAlpha;
  12960. this.blendColor.copy( source.blendColor );
  12961. this.blendAlpha = source.blendAlpha;
  12962. this.depthFunc = source.depthFunc;
  12963. this.depthTest = source.depthTest;
  12964. this.depthWrite = source.depthWrite;
  12965. this.stencilWriteMask = source.stencilWriteMask;
  12966. this.stencilFunc = source.stencilFunc;
  12967. this.stencilRef = source.stencilRef;
  12968. this.stencilFuncMask = source.stencilFuncMask;
  12969. this.stencilFail = source.stencilFail;
  12970. this.stencilZFail = source.stencilZFail;
  12971. this.stencilZPass = source.stencilZPass;
  12972. this.stencilWrite = source.stencilWrite;
  12973. const srcPlanes = source.clippingPlanes;
  12974. let dstPlanes = null;
  12975. if ( srcPlanes !== null ) {
  12976. const n = srcPlanes.length;
  12977. dstPlanes = new Array( n );
  12978. for ( let i = 0; i !== n; ++ i ) {
  12979. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12980. }
  12981. }
  12982. this.clippingPlanes = dstPlanes;
  12983. this.clipIntersection = source.clipIntersection;
  12984. this.clipShadows = source.clipShadows;
  12985. this.shadowSide = source.shadowSide;
  12986. this.colorWrite = source.colorWrite;
  12987. this.precision = source.precision;
  12988. this.polygonOffset = source.polygonOffset;
  12989. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12990. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12991. this.dithering = source.dithering;
  12992. this.alphaTest = source.alphaTest;
  12993. this.alphaHash = source.alphaHash;
  12994. this.alphaToCoverage = source.alphaToCoverage;
  12995. this.premultipliedAlpha = source.premultipliedAlpha;
  12996. this.forceSinglePass = source.forceSinglePass;
  12997. this.visible = source.visible;
  12998. this.toneMapped = source.toneMapped;
  12999. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13000. return this;
  13001. }
  13002. /**
  13003. * Frees the GPU-related resources allocated by this instance. Call this
  13004. * method whenever this instance is no longer used in your app.
  13005. *
  13006. * @fires Material#dispose
  13007. */
  13008. dispose() {
  13009. /**
  13010. * Fires when the material has been disposed of.
  13011. *
  13012. * @event Material#dispose
  13013. * @type {Object}
  13014. */
  13015. this.dispatchEvent( { type: 'dispose' } );
  13016. }
  13017. /**
  13018. * Setting this property to `true` indicates the engine the material
  13019. * needs to be recompiled.
  13020. *
  13021. * @type {boolean}
  13022. * @default false
  13023. * @param {boolean} value
  13024. */
  13025. set needsUpdate( value ) {
  13026. if ( value === true ) this.version ++;
  13027. }
  13028. }
  13029. /**
  13030. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13031. *
  13032. * This material is not affected by lights.
  13033. *
  13034. * @augments Material
  13035. */
  13036. class MeshBasicMaterial extends Material {
  13037. /**
  13038. * Constructs a new mesh basic material.
  13039. *
  13040. * @param {Object} [parameters] - An object with one or more properties
  13041. * defining the material's appearance. Any property of the material
  13042. * (including any property from inherited materials) can be passed
  13043. * in here. Color values can be passed any type of value accepted
  13044. * by {@link Color#set}.
  13045. */
  13046. constructor( parameters ) {
  13047. super();
  13048. /**
  13049. * This flag can be used for type testing.
  13050. *
  13051. * @type {boolean}
  13052. * @readonly
  13053. * @default true
  13054. */
  13055. this.isMeshBasicMaterial = true;
  13056. this.type = 'MeshBasicMaterial';
  13057. /**
  13058. * Color of the material.
  13059. *
  13060. * @type {Color}
  13061. * @default (1,1,1)
  13062. */
  13063. this.color = new Color( 0xffffff ); // diffuse
  13064. /**
  13065. * The color map. May optionally include an alpha channel, typically combined
  13066. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13067. * color is modulated by the diffuse `color`.
  13068. *
  13069. * @type {?Texture}
  13070. * @default null
  13071. */
  13072. this.map = null;
  13073. /**
  13074. * The light map. Requires a second set of UVs.
  13075. *
  13076. * @type {?Texture}
  13077. * @default null
  13078. */
  13079. this.lightMap = null;
  13080. /**
  13081. * Intensity of the baked light.
  13082. *
  13083. * @type {number}
  13084. * @default 1
  13085. */
  13086. this.lightMapIntensity = 1.0;
  13087. /**
  13088. * The red channel of this texture is used as the ambient occlusion map.
  13089. * Requires a second set of UVs.
  13090. *
  13091. * @type {?Texture}
  13092. * @default null
  13093. */
  13094. this.aoMap = null;
  13095. /**
  13096. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13097. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13098. * red channel is also `1`, ambient light is fully occluded on a surface.
  13099. *
  13100. * @type {number}
  13101. * @default 1
  13102. */
  13103. this.aoMapIntensity = 1.0;
  13104. /**
  13105. * Specular map used by the material.
  13106. *
  13107. * @type {?Texture}
  13108. * @default null
  13109. */
  13110. this.specularMap = null;
  13111. /**
  13112. * The alpha map is a grayscale texture that controls the opacity across the
  13113. * surface (black: fully transparent; white: fully opaque).
  13114. *
  13115. * Only the color of the texture is used, ignoring the alpha channel if one
  13116. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13117. * when sampling this texture due to the extra bit of precision provided for
  13118. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13119. * luminance/alpha textures will also still work as expected.
  13120. *
  13121. * @type {?Texture}
  13122. * @default null
  13123. */
  13124. this.alphaMap = null;
  13125. /**
  13126. * The environment map.
  13127. *
  13128. * @type {?Texture}
  13129. * @default null
  13130. */
  13131. this.envMap = null;
  13132. /**
  13133. * The rotation of the environment map in radians.
  13134. *
  13135. * @type {Euler}
  13136. * @default (0,0,0)
  13137. */
  13138. this.envMapRotation = new Euler();
  13139. /**
  13140. * How to combine the result of the surface's color with the environment map, if any.
  13141. *
  13142. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13143. * blend between the two colors.
  13144. *
  13145. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13146. * @default MultiplyOperation
  13147. */
  13148. this.combine = MultiplyOperation;
  13149. /**
  13150. * How much the environment map affects the surface.
  13151. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13152. *
  13153. * @type {number}
  13154. * @default 1
  13155. */
  13156. this.reflectivity = 1;
  13157. /**
  13158. * The index of refraction (IOR) of air (approximately 1) divided by the
  13159. * index of refraction of the material. It is used with environment mapping
  13160. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13161. * The refraction ratio should not exceed `1`.
  13162. *
  13163. * @type {number}
  13164. * @default 0.98
  13165. */
  13166. this.refractionRatio = 0.98;
  13167. /**
  13168. * Renders the geometry as a wireframe.
  13169. *
  13170. * @type {boolean}
  13171. * @default false
  13172. */
  13173. this.wireframe = false;
  13174. /**
  13175. * Controls the thickness of the wireframe.
  13176. *
  13177. * Can only be used with {@link SVGRenderer}.
  13178. *
  13179. * @type {number}
  13180. * @default 1
  13181. */
  13182. this.wireframeLinewidth = 1;
  13183. /**
  13184. * Defines appearance of wireframe ends.
  13185. *
  13186. * Can only be used with {@link SVGRenderer}.
  13187. *
  13188. * @type {('round'|'bevel'|'miter')}
  13189. * @default 'round'
  13190. */
  13191. this.wireframeLinecap = 'round';
  13192. /**
  13193. * Defines appearance of wireframe joints.
  13194. *
  13195. * Can only be used with {@link SVGRenderer}.
  13196. *
  13197. * @type {('round'|'bevel'|'miter')}
  13198. * @default 'round'
  13199. */
  13200. this.wireframeLinejoin = 'round';
  13201. /**
  13202. * Whether the material is affected by fog or not.
  13203. *
  13204. * @type {boolean}
  13205. * @default true
  13206. */
  13207. this.fog = true;
  13208. this.setValues( parameters );
  13209. }
  13210. copy( source ) {
  13211. super.copy( source );
  13212. this.color.copy( source.color );
  13213. this.map = source.map;
  13214. this.lightMap = source.lightMap;
  13215. this.lightMapIntensity = source.lightMapIntensity;
  13216. this.aoMap = source.aoMap;
  13217. this.aoMapIntensity = source.aoMapIntensity;
  13218. this.specularMap = source.specularMap;
  13219. this.alphaMap = source.alphaMap;
  13220. this.envMap = source.envMap;
  13221. this.envMapRotation.copy( source.envMapRotation );
  13222. this.combine = source.combine;
  13223. this.reflectivity = source.reflectivity;
  13224. this.refractionRatio = source.refractionRatio;
  13225. this.wireframe = source.wireframe;
  13226. this.wireframeLinewidth = source.wireframeLinewidth;
  13227. this.wireframeLinecap = source.wireframeLinecap;
  13228. this.wireframeLinejoin = source.wireframeLinejoin;
  13229. this.fog = source.fog;
  13230. return this;
  13231. }
  13232. }
  13233. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13234. const _tables = /*@__PURE__*/ _generateTables();
  13235. function _generateTables() {
  13236. // float32 to float16 helpers
  13237. const buffer = new ArrayBuffer( 4 );
  13238. const floatView = new Float32Array( buffer );
  13239. const uint32View = new Uint32Array( buffer );
  13240. const baseTable = new Uint32Array( 512 );
  13241. const shiftTable = new Uint32Array( 512 );
  13242. for ( let i = 0; i < 256; ++ i ) {
  13243. const e = i - 127;
  13244. // very small number (0, -0)
  13245. if ( e < -27 ) {
  13246. baseTable[ i ] = 0x0000;
  13247. baseTable[ i | 0x100 ] = 0x8000;
  13248. shiftTable[ i ] = 24;
  13249. shiftTable[ i | 0x100 ] = 24;
  13250. // small number (denorm)
  13251. } else if ( e < -14 ) {
  13252. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13253. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13254. shiftTable[ i ] = - e - 1;
  13255. shiftTable[ i | 0x100 ] = - e - 1;
  13256. // normal number
  13257. } else if ( e <= 15 ) {
  13258. baseTable[ i ] = ( e + 15 ) << 10;
  13259. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13260. shiftTable[ i ] = 13;
  13261. shiftTable[ i | 0x100 ] = 13;
  13262. // large number (Infinity, -Infinity)
  13263. } else if ( e < 128 ) {
  13264. baseTable[ i ] = 0x7c00;
  13265. baseTable[ i | 0x100 ] = 0xfc00;
  13266. shiftTable[ i ] = 24;
  13267. shiftTable[ i | 0x100 ] = 24;
  13268. // stay (NaN, Infinity, -Infinity)
  13269. } else {
  13270. baseTable[ i ] = 0x7c00;
  13271. baseTable[ i | 0x100 ] = 0xfc00;
  13272. shiftTable[ i ] = 13;
  13273. shiftTable[ i | 0x100 ] = 13;
  13274. }
  13275. }
  13276. // float16 to float32 helpers
  13277. const mantissaTable = new Uint32Array( 2048 );
  13278. const exponentTable = new Uint32Array( 64 );
  13279. const offsetTable = new Uint32Array( 64 );
  13280. for ( let i = 1; i < 1024; ++ i ) {
  13281. let m = i << 13; // zero pad mantissa bits
  13282. let e = 0; // zero exponent
  13283. // normalized
  13284. while ( ( m & 0x00800000 ) === 0 ) {
  13285. m <<= 1;
  13286. e -= 0x00800000; // decrement exponent
  13287. }
  13288. m &= -8388609; // clear leading 1 bit
  13289. e += 0x38800000; // adjust bias
  13290. mantissaTable[ i ] = m | e;
  13291. }
  13292. for ( let i = 1024; i < 2048; ++ i ) {
  13293. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13294. }
  13295. for ( let i = 1; i < 31; ++ i ) {
  13296. exponentTable[ i ] = i << 23;
  13297. }
  13298. exponentTable[ 31 ] = 0x47800000;
  13299. exponentTable[ 32 ] = 0x80000000;
  13300. for ( let i = 33; i < 63; ++ i ) {
  13301. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13302. }
  13303. exponentTable[ 63 ] = 0xc7800000;
  13304. for ( let i = 1; i < 64; ++ i ) {
  13305. if ( i !== 32 ) {
  13306. offsetTable[ i ] = 1024;
  13307. }
  13308. }
  13309. return {
  13310. floatView: floatView,
  13311. uint32View: uint32View,
  13312. baseTable: baseTable,
  13313. shiftTable: shiftTable,
  13314. mantissaTable: mantissaTable,
  13315. exponentTable: exponentTable,
  13316. offsetTable: offsetTable
  13317. };
  13318. }
  13319. /**
  13320. * Returns a half precision floating point value (FP16) from the given single
  13321. * precision floating point value (FP32).
  13322. *
  13323. * @param {number} val - A single precision floating point value.
  13324. * @return {number} The FP16 value.
  13325. */
  13326. function toHalfFloat( val ) {
  13327. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13328. val = clamp( val, -65504, 65504 );
  13329. _tables.floatView[ 0 ] = val;
  13330. const f = _tables.uint32View[ 0 ];
  13331. const e = ( f >> 23 ) & 0x1ff;
  13332. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13333. }
  13334. /**
  13335. * Returns a single precision floating point value (FP32) from the given half
  13336. * precision floating point value (FP16).
  13337. *
  13338. * @param {number} val - A half precision floating point value.
  13339. * @return {number} The FP32 value.
  13340. */
  13341. function fromHalfFloat( val ) {
  13342. const m = val >> 10;
  13343. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13344. return _tables.floatView[ 0 ];
  13345. }
  13346. /**
  13347. * A class containing utility functions for data.
  13348. *
  13349. * @hideconstructor
  13350. */
  13351. class DataUtils {
  13352. /**
  13353. * Returns a half precision floating point value (FP16) from the given single
  13354. * precision floating point value (FP32).
  13355. *
  13356. * @param {number} val - A single precision floating point value.
  13357. * @return {number} The FP16 value.
  13358. */
  13359. static toHalfFloat( val ) {
  13360. return toHalfFloat( val );
  13361. }
  13362. /**
  13363. * Returns a single precision floating point value (FP32) from the given half
  13364. * precision floating point value (FP16).
  13365. *
  13366. * @param {number} val - A half precision floating point value.
  13367. * @return {number} The FP32 value.
  13368. */
  13369. static fromHalfFloat( val ) {
  13370. return fromHalfFloat( val );
  13371. }
  13372. }
  13373. const _vector$9 = /*@__PURE__*/ new Vector3();
  13374. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13375. let _id$3 = 0;
  13376. /**
  13377. * This class stores data for an attribute (such as vertex positions, face
  13378. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13379. * a geometry, which allows for more efficient passing of data to the GPU.
  13380. *
  13381. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13382. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13383. */
  13384. class BufferAttribute {
  13385. /**
  13386. * Constructs a new buffer attribute.
  13387. *
  13388. * @param {TypedArray} array - The array holding the attribute data.
  13389. * @param {number} itemSize - The item size.
  13390. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13391. */
  13392. constructor( array, itemSize, normalized = false ) {
  13393. if ( Array.isArray( array ) ) {
  13394. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13395. }
  13396. /**
  13397. * This flag can be used for type testing.
  13398. *
  13399. * @type {boolean}
  13400. * @readonly
  13401. * @default true
  13402. */
  13403. this.isBufferAttribute = true;
  13404. /**
  13405. * The ID of the buffer attribute.
  13406. *
  13407. * @name BufferAttribute#id
  13408. * @type {number}
  13409. * @readonly
  13410. */
  13411. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13412. /**
  13413. * The name of the buffer attribute.
  13414. *
  13415. * @type {string}
  13416. */
  13417. this.name = '';
  13418. /**
  13419. * The array holding the attribute data. It should have `itemSize * numVertices`
  13420. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13421. *
  13422. * @type {TypedArray}
  13423. */
  13424. this.array = array;
  13425. /**
  13426. * The number of values of the array that should be associated with a particular vertex.
  13427. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13428. * normal, or color), then the value should be `3`.
  13429. *
  13430. * @type {number}
  13431. */
  13432. this.itemSize = itemSize;
  13433. /**
  13434. * Represents the number of items this buffer attribute stores. It is internally computed
  13435. * by dividing the `array` length by the `itemSize`.
  13436. *
  13437. * @type {number}
  13438. * @readonly
  13439. */
  13440. this.count = array !== undefined ? array.length / itemSize : 0;
  13441. /**
  13442. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13443. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13444. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13445. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13446. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13447. *
  13448. * @type {boolean}
  13449. */
  13450. this.normalized = normalized;
  13451. /**
  13452. * Defines the intended usage pattern of the data store for optimization purposes.
  13453. *
  13454. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13455. * instantiate a new one and set the desired usage before the next render.
  13456. *
  13457. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13458. * @default StaticDrawUsage
  13459. */
  13460. this.usage = StaticDrawUsage;
  13461. /**
  13462. * This can be used to only update some components of stored vectors (for example, just the
  13463. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13464. *
  13465. * @type {Array<Object>}
  13466. */
  13467. this.updateRanges = [];
  13468. /**
  13469. * Configures the bound GPU type for use in shaders.
  13470. *
  13471. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13472. * For lower precision float types, use `Float16BufferAttribute`.
  13473. *
  13474. * @type {(FloatType|IntType)}
  13475. * @default FloatType
  13476. */
  13477. this.gpuType = FloatType;
  13478. /**
  13479. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13480. *
  13481. * @type {number}
  13482. */
  13483. this.version = 0;
  13484. }
  13485. /**
  13486. * A callback function that is executed after the renderer has transferred the attribute
  13487. * array data to the GPU.
  13488. */
  13489. onUploadCallback() {}
  13490. /**
  13491. * Flag to indicate that this attribute has changed and should be re-sent to
  13492. * the GPU. Set this to `true` when you modify the value of the array.
  13493. *
  13494. * @type {number}
  13495. * @default false
  13496. * @param {boolean} value
  13497. */
  13498. set needsUpdate( value ) {
  13499. if ( value === true ) this.version ++;
  13500. }
  13501. /**
  13502. * Sets the usage of this buffer attribute.
  13503. *
  13504. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13505. * @return {BufferAttribute} A reference to this buffer attribute.
  13506. */
  13507. setUsage( value ) {
  13508. this.usage = value;
  13509. return this;
  13510. }
  13511. /**
  13512. * Adds a range of data in the data array to be updated on the GPU.
  13513. *
  13514. * @param {number} start - Position at which to start update.
  13515. * @param {number} count - The number of components to update.
  13516. */
  13517. addUpdateRange( start, count ) {
  13518. this.updateRanges.push( { start, count } );
  13519. }
  13520. /**
  13521. * Clears the update ranges.
  13522. */
  13523. clearUpdateRanges() {
  13524. this.updateRanges.length = 0;
  13525. }
  13526. /**
  13527. * Copies the values of the given buffer attribute to this instance.
  13528. *
  13529. * @param {BufferAttribute} source - The buffer attribute to copy.
  13530. * @return {BufferAttribute} A reference to this instance.
  13531. */
  13532. copy( source ) {
  13533. this.name = source.name;
  13534. this.array = new source.array.constructor( source.array );
  13535. this.itemSize = source.itemSize;
  13536. this.count = source.count;
  13537. this.normalized = source.normalized;
  13538. this.usage = source.usage;
  13539. this.gpuType = source.gpuType;
  13540. return this;
  13541. }
  13542. /**
  13543. * Copies a vector from the given buffer attribute to this one. The start
  13544. * and destination position in the attribute buffers are represented by the
  13545. * given indices.
  13546. *
  13547. * @param {number} index1 - The destination index into this buffer attribute.
  13548. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13549. * @param {number} index2 - The source index into the given buffer attribute.
  13550. * @return {BufferAttribute} A reference to this instance.
  13551. */
  13552. copyAt( index1, attribute, index2 ) {
  13553. index1 *= this.itemSize;
  13554. index2 *= attribute.itemSize;
  13555. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13556. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13557. }
  13558. return this;
  13559. }
  13560. /**
  13561. * Copies the given array data into this buffer attribute.
  13562. *
  13563. * @param {(TypedArray|Array)} array - The array to copy.
  13564. * @return {BufferAttribute} A reference to this instance.
  13565. */
  13566. copyArray( array ) {
  13567. this.array.set( array );
  13568. return this;
  13569. }
  13570. /**
  13571. * Applies the given 3x3 matrix to the given attribute. Works with
  13572. * item size `2` and `3`.
  13573. *
  13574. * @param {Matrix3} m - The matrix to apply.
  13575. * @return {BufferAttribute} A reference to this instance.
  13576. */
  13577. applyMatrix3( m ) {
  13578. if ( this.itemSize === 2 ) {
  13579. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13580. _vector2$1.fromBufferAttribute( this, i );
  13581. _vector2$1.applyMatrix3( m );
  13582. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13583. }
  13584. } else if ( this.itemSize === 3 ) {
  13585. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13586. _vector$9.fromBufferAttribute( this, i );
  13587. _vector$9.applyMatrix3( m );
  13588. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13589. }
  13590. }
  13591. return this;
  13592. }
  13593. /**
  13594. * Applies the given 4x4 matrix to the given attribute. Only works with
  13595. * item size `3`.
  13596. *
  13597. * @param {Matrix4} m - The matrix to apply.
  13598. * @return {BufferAttribute} A reference to this instance.
  13599. */
  13600. applyMatrix4( m ) {
  13601. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13602. _vector$9.fromBufferAttribute( this, i );
  13603. _vector$9.applyMatrix4( m );
  13604. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13605. }
  13606. return this;
  13607. }
  13608. /**
  13609. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13610. * item size `3`.
  13611. *
  13612. * @param {Matrix3} m - The normal matrix to apply.
  13613. * @return {BufferAttribute} A reference to this instance.
  13614. */
  13615. applyNormalMatrix( m ) {
  13616. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13617. _vector$9.fromBufferAttribute( this, i );
  13618. _vector$9.applyNormalMatrix( m );
  13619. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13620. }
  13621. return this;
  13622. }
  13623. /**
  13624. * Applies the given 4x4 matrix to the given attribute. Only works with
  13625. * item size `3` and with direction vectors.
  13626. *
  13627. * @param {Matrix4} m - The matrix to apply.
  13628. * @return {BufferAttribute} A reference to this instance.
  13629. */
  13630. transformDirection( m ) {
  13631. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13632. _vector$9.fromBufferAttribute( this, i );
  13633. _vector$9.transformDirection( m );
  13634. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13635. }
  13636. return this;
  13637. }
  13638. /**
  13639. * Sets the given array data in the buffer attribute.
  13640. *
  13641. * @param {(TypedArray|Array)} value - The array data to set.
  13642. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13643. * @return {BufferAttribute} A reference to this instance.
  13644. */
  13645. set( value, offset = 0 ) {
  13646. // Matching BufferAttribute constructor, do not normalize the array.
  13647. this.array.set( value, offset );
  13648. return this;
  13649. }
  13650. /**
  13651. * Returns the given component of the vector at the given index.
  13652. *
  13653. * @param {number} index - The index into the buffer attribute.
  13654. * @param {number} component - The component index.
  13655. * @return {number} The returned value.
  13656. */
  13657. getComponent( index, component ) {
  13658. let value = this.array[ index * this.itemSize + component ];
  13659. if ( this.normalized ) value = denormalize( value, this.array );
  13660. return value;
  13661. }
  13662. /**
  13663. * Sets the given value to the given component of the vector at the given index.
  13664. *
  13665. * @param {number} index - The index into the buffer attribute.
  13666. * @param {number} component - The component index.
  13667. * @param {number} value - The value to set.
  13668. * @return {BufferAttribute} A reference to this instance.
  13669. */
  13670. setComponent( index, component, value ) {
  13671. if ( this.normalized ) value = normalize( value, this.array );
  13672. this.array[ index * this.itemSize + component ] = value;
  13673. return this;
  13674. }
  13675. /**
  13676. * Returns the x component of the vector at the given index.
  13677. *
  13678. * @param {number} index - The index into the buffer attribute.
  13679. * @return {number} The x component.
  13680. */
  13681. getX( index ) {
  13682. let x = this.array[ index * this.itemSize ];
  13683. if ( this.normalized ) x = denormalize( x, this.array );
  13684. return x;
  13685. }
  13686. /**
  13687. * Sets the x component of the vector at the given index.
  13688. *
  13689. * @param {number} index - The index into the buffer attribute.
  13690. * @param {number} x - The value to set.
  13691. * @return {BufferAttribute} A reference to this instance.
  13692. */
  13693. setX( index, x ) {
  13694. if ( this.normalized ) x = normalize( x, this.array );
  13695. this.array[ index * this.itemSize ] = x;
  13696. return this;
  13697. }
  13698. /**
  13699. * Returns the y component of the vector at the given index.
  13700. *
  13701. * @param {number} index - The index into the buffer attribute.
  13702. * @return {number} The y component.
  13703. */
  13704. getY( index ) {
  13705. let y = this.array[ index * this.itemSize + 1 ];
  13706. if ( this.normalized ) y = denormalize( y, this.array );
  13707. return y;
  13708. }
  13709. /**
  13710. * Sets the y component of the vector at the given index.
  13711. *
  13712. * @param {number} index - The index into the buffer attribute.
  13713. * @param {number} y - The value to set.
  13714. * @return {BufferAttribute} A reference to this instance.
  13715. */
  13716. setY( index, y ) {
  13717. if ( this.normalized ) y = normalize( y, this.array );
  13718. this.array[ index * this.itemSize + 1 ] = y;
  13719. return this;
  13720. }
  13721. /**
  13722. * Returns the z component of the vector at the given index.
  13723. *
  13724. * @param {number} index - The index into the buffer attribute.
  13725. * @return {number} The z component.
  13726. */
  13727. getZ( index ) {
  13728. let z = this.array[ index * this.itemSize + 2 ];
  13729. if ( this.normalized ) z = denormalize( z, this.array );
  13730. return z;
  13731. }
  13732. /**
  13733. * Sets the z component of the vector at the given index.
  13734. *
  13735. * @param {number} index - The index into the buffer attribute.
  13736. * @param {number} z - The value to set.
  13737. * @return {BufferAttribute} A reference to this instance.
  13738. */
  13739. setZ( index, z ) {
  13740. if ( this.normalized ) z = normalize( z, this.array );
  13741. this.array[ index * this.itemSize + 2 ] = z;
  13742. return this;
  13743. }
  13744. /**
  13745. * Returns the w component of the vector at the given index.
  13746. *
  13747. * @param {number} index - The index into the buffer attribute.
  13748. * @return {number} The w component.
  13749. */
  13750. getW( index ) {
  13751. let w = this.array[ index * this.itemSize + 3 ];
  13752. if ( this.normalized ) w = denormalize( w, this.array );
  13753. return w;
  13754. }
  13755. /**
  13756. * Sets the w component of the vector at the given index.
  13757. *
  13758. * @param {number} index - The index into the buffer attribute.
  13759. * @param {number} w - The value to set.
  13760. * @return {BufferAttribute} A reference to this instance.
  13761. */
  13762. setW( index, w ) {
  13763. if ( this.normalized ) w = normalize( w, this.array );
  13764. this.array[ index * this.itemSize + 3 ] = w;
  13765. return this;
  13766. }
  13767. /**
  13768. * Sets the x and y component of the vector at the given index.
  13769. *
  13770. * @param {number} index - The index into the buffer attribute.
  13771. * @param {number} x - The value for the x component to set.
  13772. * @param {number} y - The value for the y component to set.
  13773. * @return {BufferAttribute} A reference to this instance.
  13774. */
  13775. setXY( index, x, y ) {
  13776. index *= this.itemSize;
  13777. if ( this.normalized ) {
  13778. x = normalize( x, this.array );
  13779. y = normalize( y, this.array );
  13780. }
  13781. this.array[ index + 0 ] = x;
  13782. this.array[ index + 1 ] = y;
  13783. return this;
  13784. }
  13785. /**
  13786. * Sets the x, y and z component of the vector at the given index.
  13787. *
  13788. * @param {number} index - The index into the buffer attribute.
  13789. * @param {number} x - The value for the x component to set.
  13790. * @param {number} y - The value for the y component to set.
  13791. * @param {number} z - The value for the z component to set.
  13792. * @return {BufferAttribute} A reference to this instance.
  13793. */
  13794. setXYZ( index, x, y, z ) {
  13795. index *= this.itemSize;
  13796. if ( this.normalized ) {
  13797. x = normalize( x, this.array );
  13798. y = normalize( y, this.array );
  13799. z = normalize( z, this.array );
  13800. }
  13801. this.array[ index + 0 ] = x;
  13802. this.array[ index + 1 ] = y;
  13803. this.array[ index + 2 ] = z;
  13804. return this;
  13805. }
  13806. /**
  13807. * Sets the x, y, z and w component of the vector at the given index.
  13808. *
  13809. * @param {number} index - The index into the buffer attribute.
  13810. * @param {number} x - The value for the x component to set.
  13811. * @param {number} y - The value for the y component to set.
  13812. * @param {number} z - The value for the z component to set.
  13813. * @param {number} w - The value for the w component to set.
  13814. * @return {BufferAttribute} A reference to this instance.
  13815. */
  13816. setXYZW( index, x, y, z, w ) {
  13817. index *= this.itemSize;
  13818. if ( this.normalized ) {
  13819. x = normalize( x, this.array );
  13820. y = normalize( y, this.array );
  13821. z = normalize( z, this.array );
  13822. w = normalize( w, this.array );
  13823. }
  13824. this.array[ index + 0 ] = x;
  13825. this.array[ index + 1 ] = y;
  13826. this.array[ index + 2 ] = z;
  13827. this.array[ index + 3 ] = w;
  13828. return this;
  13829. }
  13830. /**
  13831. * Sets the given callback function that is executed after the Renderer has transferred
  13832. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13833. * the upload when attribute data are not needed anymore on the CPU side.
  13834. *
  13835. * @param {Function} callback - The `onUpload()` callback.
  13836. * @return {BufferAttribute} A reference to this instance.
  13837. */
  13838. onUpload( callback ) {
  13839. this.onUploadCallback = callback;
  13840. return this;
  13841. }
  13842. /**
  13843. * Returns a new buffer attribute with copied values from this instance.
  13844. *
  13845. * @return {BufferAttribute} A clone of this instance.
  13846. */
  13847. clone() {
  13848. return new this.constructor( this.array, this.itemSize ).copy( this );
  13849. }
  13850. /**
  13851. * Serializes the buffer attribute into JSON.
  13852. *
  13853. * @return {Object} A JSON object representing the serialized buffer attribute.
  13854. */
  13855. toJSON() {
  13856. const data = {
  13857. itemSize: this.itemSize,
  13858. type: this.array.constructor.name,
  13859. array: Array.from( this.array ),
  13860. normalized: this.normalized
  13861. };
  13862. if ( this.name !== '' ) data.name = this.name;
  13863. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13864. return data;
  13865. }
  13866. }
  13867. /**
  13868. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13869. * a plain `Array` instance.
  13870. *
  13871. * @augments BufferAttribute
  13872. */
  13873. class Int8BufferAttribute extends BufferAttribute {
  13874. /**
  13875. * Constructs a new buffer attribute.
  13876. *
  13877. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13878. * @param {number} itemSize - The item size.
  13879. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13880. */
  13881. constructor( array, itemSize, normalized ) {
  13882. super( new Int8Array( array ), itemSize, normalized );
  13883. }
  13884. }
  13885. /**
  13886. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13887. * a plain `Array` instance.
  13888. *
  13889. * @augments BufferAttribute
  13890. */
  13891. class Uint8BufferAttribute extends BufferAttribute {
  13892. /**
  13893. * Constructs a new buffer attribute.
  13894. *
  13895. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13896. * @param {number} itemSize - The item size.
  13897. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13898. */
  13899. constructor( array, itemSize, normalized ) {
  13900. super( new Uint8Array( array ), itemSize, normalized );
  13901. }
  13902. }
  13903. /**
  13904. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13905. * a plain `Array` instance.
  13906. *
  13907. * @augments BufferAttribute
  13908. */
  13909. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13910. /**
  13911. * Constructs a new buffer attribute.
  13912. *
  13913. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13914. * @param {number} itemSize - The item size.
  13915. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13916. */
  13917. constructor( array, itemSize, normalized ) {
  13918. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13919. }
  13920. }
  13921. /**
  13922. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13923. * a plain `Array` instance.
  13924. *
  13925. * @augments BufferAttribute
  13926. */
  13927. class Int16BufferAttribute extends BufferAttribute {
  13928. /**
  13929. * Constructs a new buffer attribute.
  13930. *
  13931. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13932. * @param {number} itemSize - The item size.
  13933. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13934. */
  13935. constructor( array, itemSize, normalized ) {
  13936. super( new Int16Array( array ), itemSize, normalized );
  13937. }
  13938. }
  13939. /**
  13940. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13941. * a plain `Array` instance.
  13942. *
  13943. * @augments BufferAttribute
  13944. */
  13945. class Uint16BufferAttribute extends BufferAttribute {
  13946. /**
  13947. * Constructs a new buffer attribute.
  13948. *
  13949. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13950. * @param {number} itemSize - The item size.
  13951. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13952. */
  13953. constructor( array, itemSize, normalized ) {
  13954. super( new Uint16Array( array ), itemSize, normalized );
  13955. }
  13956. }
  13957. /**
  13958. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13959. * a plain `Array` instance.
  13960. *
  13961. * @augments BufferAttribute
  13962. */
  13963. class Int32BufferAttribute extends BufferAttribute {
  13964. /**
  13965. * Constructs a new buffer attribute.
  13966. *
  13967. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13968. * @param {number} itemSize - The item size.
  13969. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13970. */
  13971. constructor( array, itemSize, normalized ) {
  13972. super( new Int32Array( array ), itemSize, normalized );
  13973. }
  13974. }
  13975. /**
  13976. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13977. * a plain `Array` instance.
  13978. *
  13979. * @augments BufferAttribute
  13980. */
  13981. class Uint32BufferAttribute extends BufferAttribute {
  13982. /**
  13983. * Constructs a new buffer attribute.
  13984. *
  13985. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13986. * @param {number} itemSize - The item size.
  13987. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13988. */
  13989. constructor( array, itemSize, normalized ) {
  13990. super( new Uint32Array( array ), itemSize, normalized );
  13991. }
  13992. }
  13993. /**
  13994. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13995. * a plain `Array` instance.
  13996. *
  13997. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13998. * browser support is still problematic.
  13999. *
  14000. * @augments BufferAttribute
  14001. */
  14002. class Float16BufferAttribute extends BufferAttribute {
  14003. /**
  14004. * Constructs a new buffer attribute.
  14005. *
  14006. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14007. * @param {number} itemSize - The item size.
  14008. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14009. */
  14010. constructor( array, itemSize, normalized ) {
  14011. super( new Uint16Array( array ), itemSize, normalized );
  14012. this.isFloat16BufferAttribute = true;
  14013. }
  14014. getX( index ) {
  14015. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14016. if ( this.normalized ) x = denormalize( x, this.array );
  14017. return x;
  14018. }
  14019. setX( index, x ) {
  14020. if ( this.normalized ) x = normalize( x, this.array );
  14021. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14022. return this;
  14023. }
  14024. getY( index ) {
  14025. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14026. if ( this.normalized ) y = denormalize( y, this.array );
  14027. return y;
  14028. }
  14029. setY( index, y ) {
  14030. if ( this.normalized ) y = normalize( y, this.array );
  14031. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14032. return this;
  14033. }
  14034. getZ( index ) {
  14035. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14036. if ( this.normalized ) z = denormalize( z, this.array );
  14037. return z;
  14038. }
  14039. setZ( index, z ) {
  14040. if ( this.normalized ) z = normalize( z, this.array );
  14041. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14042. return this;
  14043. }
  14044. getW( index ) {
  14045. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14046. if ( this.normalized ) w = denormalize( w, this.array );
  14047. return w;
  14048. }
  14049. setW( index, w ) {
  14050. if ( this.normalized ) w = normalize( w, this.array );
  14051. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14052. return this;
  14053. }
  14054. setXY( index, x, y ) {
  14055. index *= this.itemSize;
  14056. if ( this.normalized ) {
  14057. x = normalize( x, this.array );
  14058. y = normalize( y, this.array );
  14059. }
  14060. this.array[ index + 0 ] = toHalfFloat( x );
  14061. this.array[ index + 1 ] = toHalfFloat( y );
  14062. return this;
  14063. }
  14064. setXYZ( index, x, y, z ) {
  14065. index *= this.itemSize;
  14066. if ( this.normalized ) {
  14067. x = normalize( x, this.array );
  14068. y = normalize( y, this.array );
  14069. z = normalize( z, this.array );
  14070. }
  14071. this.array[ index + 0 ] = toHalfFloat( x );
  14072. this.array[ index + 1 ] = toHalfFloat( y );
  14073. this.array[ index + 2 ] = toHalfFloat( z );
  14074. return this;
  14075. }
  14076. setXYZW( index, x, y, z, w ) {
  14077. index *= this.itemSize;
  14078. if ( this.normalized ) {
  14079. x = normalize( x, this.array );
  14080. y = normalize( y, this.array );
  14081. z = normalize( z, this.array );
  14082. w = normalize( w, this.array );
  14083. }
  14084. this.array[ index + 0 ] = toHalfFloat( x );
  14085. this.array[ index + 1 ] = toHalfFloat( y );
  14086. this.array[ index + 2 ] = toHalfFloat( z );
  14087. this.array[ index + 3 ] = toHalfFloat( w );
  14088. return this;
  14089. }
  14090. }
  14091. /**
  14092. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14093. * a plain `Array` instance.
  14094. *
  14095. * @augments BufferAttribute
  14096. */
  14097. class Float32BufferAttribute extends BufferAttribute {
  14098. /**
  14099. * Constructs a new buffer attribute.
  14100. *
  14101. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14102. * @param {number} itemSize - The item size.
  14103. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14104. */
  14105. constructor( array, itemSize, normalized ) {
  14106. super( new Float32Array( array ), itemSize, normalized );
  14107. }
  14108. }
  14109. let _id$2 = 0;
  14110. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14111. const _obj = /*@__PURE__*/ new Object3D();
  14112. const _offset = /*@__PURE__*/ new Vector3();
  14113. const _box$2 = /*@__PURE__*/ new Box3();
  14114. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14115. const _vector$8 = /*@__PURE__*/ new Vector3();
  14116. /**
  14117. * A representation of mesh, line, or point geometry. Includes vertex
  14118. * positions, face indices, normals, colors, UVs, and custom attributes
  14119. * within buffers, reducing the cost of passing all this data to the GPU.
  14120. *
  14121. * ```js
  14122. * const geometry = new THREE.BufferGeometry();
  14123. * // create a simple square shape. We duplicate the top left and bottom right
  14124. * // vertices because each vertex needs to appear once per triangle.
  14125. * const vertices = new Float32Array( [
  14126. * -1.0, -1.0, 1.0, // v0
  14127. * 1.0, -1.0, 1.0, // v1
  14128. * 1.0, 1.0, 1.0, // v2
  14129. *
  14130. * 1.0, 1.0, 1.0, // v3
  14131. * -1.0, 1.0, 1.0, // v4
  14132. * -1.0, -1.0, 1.0 // v5
  14133. * ] );
  14134. * // itemSize = 3 because there are 3 values (components) per vertex
  14135. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14136. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14137. * const mesh = new THREE.Mesh( geometry, material );
  14138. * ```
  14139. *
  14140. * @augments EventDispatcher
  14141. */
  14142. class BufferGeometry extends EventDispatcher {
  14143. /**
  14144. * Constructs a new geometry.
  14145. */
  14146. constructor() {
  14147. super();
  14148. /**
  14149. * This flag can be used for type testing.
  14150. *
  14151. * @type {boolean}
  14152. * @readonly
  14153. * @default true
  14154. */
  14155. this.isBufferGeometry = true;
  14156. /**
  14157. * The ID of the geometry.
  14158. *
  14159. * @name BufferGeometry#id
  14160. * @type {number}
  14161. * @readonly
  14162. */
  14163. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14164. /**
  14165. * The UUID of the geometry.
  14166. *
  14167. * @type {string}
  14168. * @readonly
  14169. */
  14170. this.uuid = generateUUID();
  14171. /**
  14172. * The name of the geometry.
  14173. *
  14174. * @type {string}
  14175. */
  14176. this.name = '';
  14177. this.type = 'BufferGeometry';
  14178. /**
  14179. * Allows for vertices to be re-used across multiple triangles; this is
  14180. * called using "indexed triangles". Each triangle is associated with the
  14181. * indices of three vertices. This attribute therefore stores the index of
  14182. * each vertex for each triangular face. If this attribute is not set, the
  14183. * renderer assumes that each three contiguous positions represent a single triangle.
  14184. *
  14185. * @type {?BufferAttribute}
  14186. * @default null
  14187. */
  14188. this.index = null;
  14189. /**
  14190. * A (storage) buffer attribute which was generated with a compute shader and
  14191. * now defines indirect draw calls.
  14192. *
  14193. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14194. *
  14195. * @type {?BufferAttribute}
  14196. * @default null
  14197. */
  14198. this.indirect = null;
  14199. /**
  14200. * This dictionary has as id the name of the attribute to be set and as value
  14201. * the buffer attribute to set it to. Rather than accessing this property directly,
  14202. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14203. *
  14204. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14205. */
  14206. this.attributes = {};
  14207. /**
  14208. * This dictionary holds the morph targets of the geometry.
  14209. *
  14210. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14211. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14212. *
  14213. * @type {Object}
  14214. */
  14215. this.morphAttributes = {};
  14216. /**
  14217. * Used to control the morph target behavior; when set to `true`, the morph
  14218. * target data is treated as relative offsets, rather than as absolute
  14219. * positions/normals.
  14220. *
  14221. * @type {boolean}
  14222. * @default false
  14223. */
  14224. this.morphTargetsRelative = false;
  14225. /**
  14226. * Split the geometry into groups, each of which will be rendered in a
  14227. * separate draw call. This allows an array of materials to be used with the geometry.
  14228. *
  14229. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14230. *
  14231. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14232. * indices, and must not leave vertices or indices unused.
  14233. *
  14234. * @type {Array<Object>}
  14235. */
  14236. this.groups = [];
  14237. /**
  14238. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14239. *
  14240. * @type {Box3}
  14241. * @default null
  14242. */
  14243. this.boundingBox = null;
  14244. /**
  14245. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14246. *
  14247. * @type {Sphere}
  14248. * @default null
  14249. */
  14250. this.boundingSphere = null;
  14251. /**
  14252. * Determines the part of the geometry to render. This should not be set directly,
  14253. * instead use `setDrawRange()`.
  14254. *
  14255. * @type {{start:number,count:number}}
  14256. */
  14257. this.drawRange = { start: 0, count: Infinity };
  14258. /**
  14259. * An object that can be used to store custom data about the geometry.
  14260. * It should not hold references to functions as these will not be cloned.
  14261. *
  14262. * @type {Object}
  14263. */
  14264. this.userData = {};
  14265. }
  14266. /**
  14267. * Returns the index of this geometry.
  14268. *
  14269. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14270. */
  14271. getIndex() {
  14272. return this.index;
  14273. }
  14274. /**
  14275. * Sets the given index to this geometry.
  14276. *
  14277. * @param {Array<number>|BufferAttribute} index - The index to set.
  14278. * @return {BufferGeometry} A reference to this instance.
  14279. */
  14280. setIndex( index ) {
  14281. if ( Array.isArray( index ) ) {
  14282. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14283. } else {
  14284. this.index = index;
  14285. }
  14286. return this;
  14287. }
  14288. /**
  14289. * Sets the given indirect attribute to this geometry.
  14290. *
  14291. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14292. * @return {BufferGeometry} A reference to this instance.
  14293. */
  14294. setIndirect( indirect ) {
  14295. this.indirect = indirect;
  14296. return this;
  14297. }
  14298. /**
  14299. * Returns the indirect attribute of this geometry.
  14300. *
  14301. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14302. */
  14303. getIndirect() {
  14304. return this.indirect;
  14305. }
  14306. /**
  14307. * Returns the buffer attribute for the given name.
  14308. *
  14309. * @param {string} name - The attribute name.
  14310. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14311. * Returns `undefined` if not attribute has been found.
  14312. */
  14313. getAttribute( name ) {
  14314. return this.attributes[ name ];
  14315. }
  14316. /**
  14317. * Sets the given attribute for the given name.
  14318. *
  14319. * @param {string} name - The attribute name.
  14320. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14321. * @return {BufferGeometry} A reference to this instance.
  14322. */
  14323. setAttribute( name, attribute ) {
  14324. this.attributes[ name ] = attribute;
  14325. return this;
  14326. }
  14327. /**
  14328. * Deletes the attribute for the given name.
  14329. *
  14330. * @param {string} name - The attribute name to delete.
  14331. * @return {BufferGeometry} A reference to this instance.
  14332. */
  14333. deleteAttribute( name ) {
  14334. delete this.attributes[ name ];
  14335. return this;
  14336. }
  14337. /**
  14338. * Returns `true` if this geometry has an attribute for the given name.
  14339. *
  14340. * @param {string} name - The attribute name.
  14341. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14342. */
  14343. hasAttribute( name ) {
  14344. return this.attributes[ name ] !== undefined;
  14345. }
  14346. /**
  14347. * Adds a group to this geometry.
  14348. *
  14349. * @param {number} start - The first element in this draw call. That is the first
  14350. * vertex for non-indexed geometry, otherwise the first triangle index.
  14351. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14352. * @param {number} [materialIndex=0] - The material array index to use.
  14353. */
  14354. addGroup( start, count, materialIndex = 0 ) {
  14355. this.groups.push( {
  14356. start: start,
  14357. count: count,
  14358. materialIndex: materialIndex
  14359. } );
  14360. }
  14361. /**
  14362. * Clears all groups.
  14363. */
  14364. clearGroups() {
  14365. this.groups = [];
  14366. }
  14367. /**
  14368. * Sets the draw range for this geometry.
  14369. *
  14370. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14371. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14372. * For indexed BufferGeometry, `count` is the number of indices to render.
  14373. */
  14374. setDrawRange( start, count ) {
  14375. this.drawRange.start = start;
  14376. this.drawRange.count = count;
  14377. }
  14378. /**
  14379. * Applies the given 4x4 transformation matrix to the geometry.
  14380. *
  14381. * @param {Matrix4} matrix - The matrix to apply.
  14382. * @return {BufferGeometry} A reference to this instance.
  14383. */
  14384. applyMatrix4( matrix ) {
  14385. const position = this.attributes.position;
  14386. if ( position !== undefined ) {
  14387. position.applyMatrix4( matrix );
  14388. position.needsUpdate = true;
  14389. }
  14390. const normal = this.attributes.normal;
  14391. if ( normal !== undefined ) {
  14392. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14393. normal.applyNormalMatrix( normalMatrix );
  14394. normal.needsUpdate = true;
  14395. }
  14396. const tangent = this.attributes.tangent;
  14397. if ( tangent !== undefined ) {
  14398. tangent.transformDirection( matrix );
  14399. tangent.needsUpdate = true;
  14400. }
  14401. if ( this.boundingBox !== null ) {
  14402. this.computeBoundingBox();
  14403. }
  14404. if ( this.boundingSphere !== null ) {
  14405. this.computeBoundingSphere();
  14406. }
  14407. return this;
  14408. }
  14409. /**
  14410. * Applies the rotation represented by the Quaternion to the geometry.
  14411. *
  14412. * @param {Quaternion} q - The Quaternion to apply.
  14413. * @return {BufferGeometry} A reference to this instance.
  14414. */
  14415. applyQuaternion( q ) {
  14416. _m1$2.makeRotationFromQuaternion( q );
  14417. this.applyMatrix4( _m1$2 );
  14418. return this;
  14419. }
  14420. /**
  14421. * Rotates the geometry about the X axis. This is typically done as a one time
  14422. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14423. * real-time mesh rotation.
  14424. *
  14425. * @param {number} angle - The angle in radians.
  14426. * @return {BufferGeometry} A reference to this instance.
  14427. */
  14428. rotateX( angle ) {
  14429. // rotate geometry around world x-axis
  14430. _m1$2.makeRotationX( angle );
  14431. this.applyMatrix4( _m1$2 );
  14432. return this;
  14433. }
  14434. /**
  14435. * Rotates the geometry about the Y axis. This is typically done as a one time
  14436. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14437. * real-time mesh rotation.
  14438. *
  14439. * @param {number} angle - The angle in radians.
  14440. * @return {BufferGeometry} A reference to this instance.
  14441. */
  14442. rotateY( angle ) {
  14443. // rotate geometry around world y-axis
  14444. _m1$2.makeRotationY( angle );
  14445. this.applyMatrix4( _m1$2 );
  14446. return this;
  14447. }
  14448. /**
  14449. * Rotates the geometry about the Z axis. This is typically done as a one time
  14450. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14451. * real-time mesh rotation.
  14452. *
  14453. * @param {number} angle - The angle in radians.
  14454. * @return {BufferGeometry} A reference to this instance.
  14455. */
  14456. rotateZ( angle ) {
  14457. // rotate geometry around world z-axis
  14458. _m1$2.makeRotationZ( angle );
  14459. this.applyMatrix4( _m1$2 );
  14460. return this;
  14461. }
  14462. /**
  14463. * Translates the geometry. This is typically done as a one time
  14464. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14465. * real-time mesh rotation.
  14466. *
  14467. * @param {number} x - The x offset.
  14468. * @param {number} y - The y offset.
  14469. * @param {number} z - The z offset.
  14470. * @return {BufferGeometry} A reference to this instance.
  14471. */
  14472. translate( x, y, z ) {
  14473. // translate geometry
  14474. _m1$2.makeTranslation( x, y, z );
  14475. this.applyMatrix4( _m1$2 );
  14476. return this;
  14477. }
  14478. /**
  14479. * Scales the geometry. This is typically done as a one time
  14480. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14481. * real-time mesh rotation.
  14482. *
  14483. * @param {number} x - The x scale.
  14484. * @param {number} y - The y scale.
  14485. * @param {number} z - The z scale.
  14486. * @return {BufferGeometry} A reference to this instance.
  14487. */
  14488. scale( x, y, z ) {
  14489. // scale geometry
  14490. _m1$2.makeScale( x, y, z );
  14491. this.applyMatrix4( _m1$2 );
  14492. return this;
  14493. }
  14494. /**
  14495. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14496. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14497. * real-time mesh rotation.
  14498. *
  14499. * @param {Vector3} vector - The target point.
  14500. * @return {BufferGeometry} A reference to this instance.
  14501. */
  14502. lookAt( vector ) {
  14503. _obj.lookAt( vector );
  14504. _obj.updateMatrix();
  14505. this.applyMatrix4( _obj.matrix );
  14506. return this;
  14507. }
  14508. /**
  14509. * Center the geometry based on its bounding box.
  14510. *
  14511. * @return {BufferGeometry} A reference to this instance.
  14512. */
  14513. center() {
  14514. this.computeBoundingBox();
  14515. this.boundingBox.getCenter( _offset ).negate();
  14516. this.translate( _offset.x, _offset.y, _offset.z );
  14517. return this;
  14518. }
  14519. /**
  14520. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14521. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14522. * set to `0`.
  14523. *
  14524. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14525. * data from the array. The length of the array must match the vertex count.
  14526. *
  14527. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14528. * @return {BufferGeometry} A reference to this instance.
  14529. */
  14530. setFromPoints( points ) {
  14531. const positionAttribute = this.getAttribute( 'position' );
  14532. if ( positionAttribute === undefined ) {
  14533. const position = [];
  14534. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14535. const point = points[ i ];
  14536. position.push( point.x, point.y, point.z || 0 );
  14537. }
  14538. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14539. } else {
  14540. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14541. for ( let i = 0; i < l; i ++ ) {
  14542. const point = points[ i ];
  14543. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14544. }
  14545. if ( points.length > positionAttribute.count ) {
  14546. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14547. }
  14548. positionAttribute.needsUpdate = true;
  14549. }
  14550. return this;
  14551. }
  14552. /**
  14553. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14554. * The bounding box is not computed by the engine; it must be computed by your app.
  14555. * You may need to recompute the bounding box if the geometry vertices are modified.
  14556. */
  14557. computeBoundingBox() {
  14558. if ( this.boundingBox === null ) {
  14559. this.boundingBox = new Box3();
  14560. }
  14561. const position = this.attributes.position;
  14562. const morphAttributesPosition = this.morphAttributes.position;
  14563. if ( position && position.isGLBufferAttribute ) {
  14564. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14565. this.boundingBox.set(
  14566. new Vector3( - Infinity, - Infinity, - Infinity ),
  14567. new Vector3( + Infinity, + Infinity, + Infinity )
  14568. );
  14569. return;
  14570. }
  14571. if ( position !== undefined ) {
  14572. this.boundingBox.setFromBufferAttribute( position );
  14573. // process morph attributes if present
  14574. if ( morphAttributesPosition ) {
  14575. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14576. const morphAttribute = morphAttributesPosition[ i ];
  14577. _box$2.setFromBufferAttribute( morphAttribute );
  14578. if ( this.morphTargetsRelative ) {
  14579. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14580. this.boundingBox.expandByPoint( _vector$8 );
  14581. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14582. this.boundingBox.expandByPoint( _vector$8 );
  14583. } else {
  14584. this.boundingBox.expandByPoint( _box$2.min );
  14585. this.boundingBox.expandByPoint( _box$2.max );
  14586. }
  14587. }
  14588. }
  14589. } else {
  14590. this.boundingBox.makeEmpty();
  14591. }
  14592. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14593. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14594. }
  14595. }
  14596. /**
  14597. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14598. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14599. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14600. */
  14601. computeBoundingSphere() {
  14602. if ( this.boundingSphere === null ) {
  14603. this.boundingSphere = new Sphere();
  14604. }
  14605. const position = this.attributes.position;
  14606. const morphAttributesPosition = this.morphAttributes.position;
  14607. if ( position && position.isGLBufferAttribute ) {
  14608. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14609. this.boundingSphere.set( new Vector3(), Infinity );
  14610. return;
  14611. }
  14612. if ( position ) {
  14613. // first, find the center of the bounding sphere
  14614. const center = this.boundingSphere.center;
  14615. _box$2.setFromBufferAttribute( position );
  14616. // process morph attributes if present
  14617. if ( morphAttributesPosition ) {
  14618. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14619. const morphAttribute = morphAttributesPosition[ i ];
  14620. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14621. if ( this.morphTargetsRelative ) {
  14622. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14623. _box$2.expandByPoint( _vector$8 );
  14624. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14625. _box$2.expandByPoint( _vector$8 );
  14626. } else {
  14627. _box$2.expandByPoint( _boxMorphTargets.min );
  14628. _box$2.expandByPoint( _boxMorphTargets.max );
  14629. }
  14630. }
  14631. }
  14632. _box$2.getCenter( center );
  14633. // second, try to find a boundingSphere with a radius smaller than the
  14634. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14635. let maxRadiusSq = 0;
  14636. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14637. _vector$8.fromBufferAttribute( position, i );
  14638. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14639. }
  14640. // process morph attributes if present
  14641. if ( morphAttributesPosition ) {
  14642. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14643. const morphAttribute = morphAttributesPosition[ i ];
  14644. const morphTargetsRelative = this.morphTargetsRelative;
  14645. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14646. _vector$8.fromBufferAttribute( morphAttribute, j );
  14647. if ( morphTargetsRelative ) {
  14648. _offset.fromBufferAttribute( position, j );
  14649. _vector$8.add( _offset );
  14650. }
  14651. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14652. }
  14653. }
  14654. }
  14655. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14656. if ( isNaN( this.boundingSphere.radius ) ) {
  14657. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14658. }
  14659. }
  14660. }
  14661. /**
  14662. * Calculates and adds a tangent attribute to this geometry.
  14663. *
  14664. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14665. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14666. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14667. */
  14668. computeTangents() {
  14669. const index = this.index;
  14670. const attributes = this.attributes;
  14671. // based on http://www.terathon.com/code/tangent.html
  14672. // (per vertex tangents)
  14673. if ( index === null ||
  14674. attributes.position === undefined ||
  14675. attributes.normal === undefined ||
  14676. attributes.uv === undefined ) {
  14677. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14678. return;
  14679. }
  14680. const positionAttribute = attributes.position;
  14681. const normalAttribute = attributes.normal;
  14682. const uvAttribute = attributes.uv;
  14683. if ( this.hasAttribute( 'tangent' ) === false ) {
  14684. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14685. }
  14686. const tangentAttribute = this.getAttribute( 'tangent' );
  14687. const tan1 = [], tan2 = [];
  14688. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14689. tan1[ i ] = new Vector3();
  14690. tan2[ i ] = new Vector3();
  14691. }
  14692. const vA = new Vector3(),
  14693. vB = new Vector3(),
  14694. vC = new Vector3(),
  14695. uvA = new Vector2(),
  14696. uvB = new Vector2(),
  14697. uvC = new Vector2(),
  14698. sdir = new Vector3(),
  14699. tdir = new Vector3();
  14700. function handleTriangle( a, b, c ) {
  14701. vA.fromBufferAttribute( positionAttribute, a );
  14702. vB.fromBufferAttribute( positionAttribute, b );
  14703. vC.fromBufferAttribute( positionAttribute, c );
  14704. uvA.fromBufferAttribute( uvAttribute, a );
  14705. uvB.fromBufferAttribute( uvAttribute, b );
  14706. uvC.fromBufferAttribute( uvAttribute, c );
  14707. vB.sub( vA );
  14708. vC.sub( vA );
  14709. uvB.sub( uvA );
  14710. uvC.sub( uvA );
  14711. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14712. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14713. if ( ! isFinite( r ) ) return;
  14714. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14715. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14716. tan1[ a ].add( sdir );
  14717. tan1[ b ].add( sdir );
  14718. tan1[ c ].add( sdir );
  14719. tan2[ a ].add( tdir );
  14720. tan2[ b ].add( tdir );
  14721. tan2[ c ].add( tdir );
  14722. }
  14723. let groups = this.groups;
  14724. if ( groups.length === 0 ) {
  14725. groups = [ {
  14726. start: 0,
  14727. count: index.count
  14728. } ];
  14729. }
  14730. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14731. const group = groups[ i ];
  14732. const start = group.start;
  14733. const count = group.count;
  14734. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14735. handleTriangle(
  14736. index.getX( j + 0 ),
  14737. index.getX( j + 1 ),
  14738. index.getX( j + 2 )
  14739. );
  14740. }
  14741. }
  14742. const tmp = new Vector3(), tmp2 = new Vector3();
  14743. const n = new Vector3(), n2 = new Vector3();
  14744. function handleVertex( v ) {
  14745. n.fromBufferAttribute( normalAttribute, v );
  14746. n2.copy( n );
  14747. const t = tan1[ v ];
  14748. // Gram-Schmidt orthogonalize
  14749. tmp.copy( t );
  14750. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14751. // Calculate handedness
  14752. tmp2.crossVectors( n2, t );
  14753. const test = tmp2.dot( tan2[ v ] );
  14754. const w = ( test < 0.0 ) ? -1 : 1.0;
  14755. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14756. }
  14757. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14758. const group = groups[ i ];
  14759. const start = group.start;
  14760. const count = group.count;
  14761. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14762. handleVertex( index.getX( j + 0 ) );
  14763. handleVertex( index.getX( j + 1 ) );
  14764. handleVertex( index.getX( j + 2 ) );
  14765. }
  14766. }
  14767. }
  14768. /**
  14769. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14770. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14771. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14772. * to be the same as the face normal.
  14773. */
  14774. computeVertexNormals() {
  14775. const index = this.index;
  14776. const positionAttribute = this.getAttribute( 'position' );
  14777. if ( positionAttribute !== undefined ) {
  14778. let normalAttribute = this.getAttribute( 'normal' );
  14779. if ( normalAttribute === undefined ) {
  14780. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14781. this.setAttribute( 'normal', normalAttribute );
  14782. } else {
  14783. // reset existing normals to zero
  14784. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14785. normalAttribute.setXYZ( i, 0, 0, 0 );
  14786. }
  14787. }
  14788. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14789. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14790. const cb = new Vector3(), ab = new Vector3();
  14791. // indexed elements
  14792. if ( index ) {
  14793. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14794. const vA = index.getX( i + 0 );
  14795. const vB = index.getX( i + 1 );
  14796. const vC = index.getX( i + 2 );
  14797. pA.fromBufferAttribute( positionAttribute, vA );
  14798. pB.fromBufferAttribute( positionAttribute, vB );
  14799. pC.fromBufferAttribute( positionAttribute, vC );
  14800. cb.subVectors( pC, pB );
  14801. ab.subVectors( pA, pB );
  14802. cb.cross( ab );
  14803. nA.fromBufferAttribute( normalAttribute, vA );
  14804. nB.fromBufferAttribute( normalAttribute, vB );
  14805. nC.fromBufferAttribute( normalAttribute, vC );
  14806. nA.add( cb );
  14807. nB.add( cb );
  14808. nC.add( cb );
  14809. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14810. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14811. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14812. }
  14813. } else {
  14814. // non-indexed elements (unconnected triangle soup)
  14815. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14816. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14817. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14818. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14819. cb.subVectors( pC, pB );
  14820. ab.subVectors( pA, pB );
  14821. cb.cross( ab );
  14822. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14823. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14824. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14825. }
  14826. }
  14827. this.normalizeNormals();
  14828. normalAttribute.needsUpdate = true;
  14829. }
  14830. }
  14831. /**
  14832. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14833. * correct lighting on the geometry surfaces.
  14834. */
  14835. normalizeNormals() {
  14836. const normals = this.attributes.normal;
  14837. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14838. _vector$8.fromBufferAttribute( normals, i );
  14839. _vector$8.normalize();
  14840. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14841. }
  14842. }
  14843. /**
  14844. * Return a new non-index version of this indexed geometry. If the geometry
  14845. * is already non-indexed, the method is a NOOP.
  14846. *
  14847. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14848. */
  14849. toNonIndexed() {
  14850. function convertBufferAttribute( attribute, indices ) {
  14851. const array = attribute.array;
  14852. const itemSize = attribute.itemSize;
  14853. const normalized = attribute.normalized;
  14854. const array2 = new array.constructor( indices.length * itemSize );
  14855. let index = 0, index2 = 0;
  14856. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14857. if ( attribute.isInterleavedBufferAttribute ) {
  14858. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14859. } else {
  14860. index = indices[ i ] * itemSize;
  14861. }
  14862. for ( let j = 0; j < itemSize; j ++ ) {
  14863. array2[ index2 ++ ] = array[ index ++ ];
  14864. }
  14865. }
  14866. return new BufferAttribute( array2, itemSize, normalized );
  14867. }
  14868. //
  14869. if ( this.index === null ) {
  14870. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14871. return this;
  14872. }
  14873. const geometry2 = new BufferGeometry();
  14874. const indices = this.index.array;
  14875. const attributes = this.attributes;
  14876. // attributes
  14877. for ( const name in attributes ) {
  14878. const attribute = attributes[ name ];
  14879. const newAttribute = convertBufferAttribute( attribute, indices );
  14880. geometry2.setAttribute( name, newAttribute );
  14881. }
  14882. // morph attributes
  14883. const morphAttributes = this.morphAttributes;
  14884. for ( const name in morphAttributes ) {
  14885. const morphArray = [];
  14886. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14887. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14888. const attribute = morphAttribute[ i ];
  14889. const newAttribute = convertBufferAttribute( attribute, indices );
  14890. morphArray.push( newAttribute );
  14891. }
  14892. geometry2.morphAttributes[ name ] = morphArray;
  14893. }
  14894. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14895. // groups
  14896. const groups = this.groups;
  14897. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14898. const group = groups[ i ];
  14899. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14900. }
  14901. return geometry2;
  14902. }
  14903. /**
  14904. * Serializes the geometry into JSON.
  14905. *
  14906. * @return {Object} A JSON object representing the serialized geometry.
  14907. */
  14908. toJSON() {
  14909. const data = {
  14910. metadata: {
  14911. version: 4.7,
  14912. type: 'BufferGeometry',
  14913. generator: 'BufferGeometry.toJSON'
  14914. }
  14915. };
  14916. // standard BufferGeometry serialization
  14917. data.uuid = this.uuid;
  14918. data.type = this.type;
  14919. if ( this.name !== '' ) data.name = this.name;
  14920. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14921. if ( this.parameters !== undefined ) {
  14922. const parameters = this.parameters;
  14923. for ( const key in parameters ) {
  14924. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14925. }
  14926. return data;
  14927. }
  14928. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14929. data.data = { attributes: {} };
  14930. const index = this.index;
  14931. if ( index !== null ) {
  14932. data.data.index = {
  14933. type: index.array.constructor.name,
  14934. array: Array.prototype.slice.call( index.array )
  14935. };
  14936. }
  14937. const attributes = this.attributes;
  14938. for ( const key in attributes ) {
  14939. const attribute = attributes[ key ];
  14940. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14941. }
  14942. const morphAttributes = {};
  14943. let hasMorphAttributes = false;
  14944. for ( const key in this.morphAttributes ) {
  14945. const attributeArray = this.morphAttributes[ key ];
  14946. const array = [];
  14947. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14948. const attribute = attributeArray[ i ];
  14949. array.push( attribute.toJSON( data.data ) );
  14950. }
  14951. if ( array.length > 0 ) {
  14952. morphAttributes[ key ] = array;
  14953. hasMorphAttributes = true;
  14954. }
  14955. }
  14956. if ( hasMorphAttributes ) {
  14957. data.data.morphAttributes = morphAttributes;
  14958. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14959. }
  14960. const groups = this.groups;
  14961. if ( groups.length > 0 ) {
  14962. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14963. }
  14964. const boundingSphere = this.boundingSphere;
  14965. if ( boundingSphere !== null ) {
  14966. data.data.boundingSphere = boundingSphere.toJSON();
  14967. }
  14968. return data;
  14969. }
  14970. /**
  14971. * Returns a new geometry with copied values from this instance.
  14972. *
  14973. * @return {BufferGeometry} A clone of this instance.
  14974. */
  14975. clone() {
  14976. return new this.constructor().copy( this );
  14977. }
  14978. /**
  14979. * Copies the values of the given geometry to this instance.
  14980. *
  14981. * @param {BufferGeometry} source - The geometry to copy.
  14982. * @return {BufferGeometry} A reference to this instance.
  14983. */
  14984. copy( source ) {
  14985. // reset
  14986. this.index = null;
  14987. this.attributes = {};
  14988. this.morphAttributes = {};
  14989. this.groups = [];
  14990. this.boundingBox = null;
  14991. this.boundingSphere = null;
  14992. // used for storing cloned, shared data
  14993. const data = {};
  14994. // name
  14995. this.name = source.name;
  14996. // index
  14997. const index = source.index;
  14998. if ( index !== null ) {
  14999. this.setIndex( index.clone() );
  15000. }
  15001. // attributes
  15002. const attributes = source.attributes;
  15003. for ( const name in attributes ) {
  15004. const attribute = attributes[ name ];
  15005. this.setAttribute( name, attribute.clone( data ) );
  15006. }
  15007. // morph attributes
  15008. const morphAttributes = source.morphAttributes;
  15009. for ( const name in morphAttributes ) {
  15010. const array = [];
  15011. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15012. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15013. array.push( morphAttribute[ i ].clone( data ) );
  15014. }
  15015. this.morphAttributes[ name ] = array;
  15016. }
  15017. this.morphTargetsRelative = source.morphTargetsRelative;
  15018. // groups
  15019. const groups = source.groups;
  15020. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15021. const group = groups[ i ];
  15022. this.addGroup( group.start, group.count, group.materialIndex );
  15023. }
  15024. // bounding box
  15025. const boundingBox = source.boundingBox;
  15026. if ( boundingBox !== null ) {
  15027. this.boundingBox = boundingBox.clone();
  15028. }
  15029. // bounding sphere
  15030. const boundingSphere = source.boundingSphere;
  15031. if ( boundingSphere !== null ) {
  15032. this.boundingSphere = boundingSphere.clone();
  15033. }
  15034. // draw range
  15035. this.drawRange.start = source.drawRange.start;
  15036. this.drawRange.count = source.drawRange.count;
  15037. // user data
  15038. this.userData = source.userData;
  15039. return this;
  15040. }
  15041. /**
  15042. * Frees the GPU-related resources allocated by this instance. Call this
  15043. * method whenever this instance is no longer used in your app.
  15044. *
  15045. * @fires BufferGeometry#dispose
  15046. */
  15047. dispose() {
  15048. this.dispatchEvent( { type: 'dispose' } );
  15049. }
  15050. }
  15051. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15052. const _ray$3 = /*@__PURE__*/ new Ray();
  15053. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15054. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15055. const _vA$1 = /*@__PURE__*/ new Vector3();
  15056. const _vB$1 = /*@__PURE__*/ new Vector3();
  15057. const _vC$1 = /*@__PURE__*/ new Vector3();
  15058. const _tempA = /*@__PURE__*/ new Vector3();
  15059. const _morphA = /*@__PURE__*/ new Vector3();
  15060. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15061. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15062. /**
  15063. * Class representing triangular polygon mesh based objects.
  15064. *
  15065. * ```js
  15066. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15067. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15068. * const mesh = new THREE.Mesh( geometry, material );
  15069. * scene.add( mesh );
  15070. * ```
  15071. *
  15072. * @augments Object3D
  15073. */
  15074. class Mesh extends Object3D {
  15075. /**
  15076. * Constructs a new mesh.
  15077. *
  15078. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15079. * @param {Material|Array<Material>} [material] - The mesh material.
  15080. */
  15081. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15082. super();
  15083. /**
  15084. * This flag can be used for type testing.
  15085. *
  15086. * @type {boolean}
  15087. * @readonly
  15088. * @default true
  15089. */
  15090. this.isMesh = true;
  15091. this.type = 'Mesh';
  15092. /**
  15093. * The mesh geometry.
  15094. *
  15095. * @type {BufferGeometry}
  15096. */
  15097. this.geometry = geometry;
  15098. /**
  15099. * The mesh material.
  15100. *
  15101. * @type {Material|Array<Material>}
  15102. * @default MeshBasicMaterial
  15103. */
  15104. this.material = material;
  15105. /**
  15106. * A dictionary representing the morph targets in the geometry. The key is the
  15107. * morph targets name, the value its attribute index. This member is `undefined`
  15108. * by default and only set when morph targets are detected in the geometry.
  15109. *
  15110. * @type {Object<String,number>|undefined}
  15111. * @default undefined
  15112. */
  15113. this.morphTargetDictionary = undefined;
  15114. /**
  15115. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15116. * is applied. This member is `undefined` by default and only set when morph targets are
  15117. * detected in the geometry.
  15118. *
  15119. * @type {Array<number>|undefined}
  15120. * @default undefined
  15121. */
  15122. this.morphTargetInfluences = undefined;
  15123. /**
  15124. * The number of instances of this mesh.
  15125. * Can only be used with {@link WebGPURenderer}.
  15126. *
  15127. * @type {number}
  15128. * @default 1
  15129. */
  15130. this.count = 1;
  15131. this.updateMorphTargets();
  15132. }
  15133. copy( source, recursive ) {
  15134. super.copy( source, recursive );
  15135. if ( source.morphTargetInfluences !== undefined ) {
  15136. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15137. }
  15138. if ( source.morphTargetDictionary !== undefined ) {
  15139. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15140. }
  15141. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15142. this.geometry = source.geometry;
  15143. return this;
  15144. }
  15145. /**
  15146. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15147. * to make sure existing morph targets can influence this 3D object.
  15148. */
  15149. updateMorphTargets() {
  15150. const geometry = this.geometry;
  15151. const morphAttributes = geometry.morphAttributes;
  15152. const keys = Object.keys( morphAttributes );
  15153. if ( keys.length > 0 ) {
  15154. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15155. if ( morphAttribute !== undefined ) {
  15156. this.morphTargetInfluences = [];
  15157. this.morphTargetDictionary = {};
  15158. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15159. const name = morphAttribute[ m ].name || String( m );
  15160. this.morphTargetInfluences.push( 0 );
  15161. this.morphTargetDictionary[ name ] = m;
  15162. }
  15163. }
  15164. }
  15165. }
  15166. /**
  15167. * Returns the local-space position of the vertex at the given index, taking into
  15168. * account the current animation state of both morph targets and skinning.
  15169. *
  15170. * @param {number} index - The vertex index.
  15171. * @param {Vector3} target - The target object that is used to store the method's result.
  15172. * @return {Vector3} The vertex position in local space.
  15173. */
  15174. getVertexPosition( index, target ) {
  15175. const geometry = this.geometry;
  15176. const position = geometry.attributes.position;
  15177. const morphPosition = geometry.morphAttributes.position;
  15178. const morphTargetsRelative = geometry.morphTargetsRelative;
  15179. target.fromBufferAttribute( position, index );
  15180. const morphInfluences = this.morphTargetInfluences;
  15181. if ( morphPosition && morphInfluences ) {
  15182. _morphA.set( 0, 0, 0 );
  15183. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15184. const influence = morphInfluences[ i ];
  15185. const morphAttribute = morphPosition[ i ];
  15186. if ( influence === 0 ) continue;
  15187. _tempA.fromBufferAttribute( morphAttribute, index );
  15188. if ( morphTargetsRelative ) {
  15189. _morphA.addScaledVector( _tempA, influence );
  15190. } else {
  15191. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15192. }
  15193. }
  15194. target.add( _morphA );
  15195. }
  15196. return target;
  15197. }
  15198. /**
  15199. * Computes intersection points between a casted ray and this line.
  15200. *
  15201. * @param {Raycaster} raycaster - The raycaster.
  15202. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15203. */
  15204. raycast( raycaster, intersects ) {
  15205. const geometry = this.geometry;
  15206. const material = this.material;
  15207. const matrixWorld = this.matrixWorld;
  15208. if ( material === undefined ) return;
  15209. // test with bounding sphere in world space
  15210. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15211. _sphere$6.copy( geometry.boundingSphere );
  15212. _sphere$6.applyMatrix4( matrixWorld );
  15213. // check distance from ray origin to bounding sphere
  15214. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15215. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15216. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15217. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15218. }
  15219. // convert ray to local space of mesh
  15220. _inverseMatrix$3.copy( matrixWorld ).invert();
  15221. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15222. // test with bounding box in local space
  15223. if ( geometry.boundingBox !== null ) {
  15224. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15225. }
  15226. // test for intersections with geometry
  15227. this._computeIntersections( raycaster, intersects, _ray$3 );
  15228. }
  15229. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15230. let intersection;
  15231. const geometry = this.geometry;
  15232. const material = this.material;
  15233. const index = geometry.index;
  15234. const position = geometry.attributes.position;
  15235. const uv = geometry.attributes.uv;
  15236. const uv1 = geometry.attributes.uv1;
  15237. const normal = geometry.attributes.normal;
  15238. const groups = geometry.groups;
  15239. const drawRange = geometry.drawRange;
  15240. if ( index !== null ) {
  15241. // indexed buffer geometry
  15242. if ( Array.isArray( material ) ) {
  15243. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15244. const group = groups[ i ];
  15245. const groupMaterial = material[ group.materialIndex ];
  15246. const start = Math.max( group.start, drawRange.start );
  15247. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15248. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15249. const a = index.getX( j );
  15250. const b = index.getX( j + 1 );
  15251. const c = index.getX( j + 2 );
  15252. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15253. if ( intersection ) {
  15254. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15255. intersection.face.materialIndex = group.materialIndex;
  15256. intersects.push( intersection );
  15257. }
  15258. }
  15259. }
  15260. } else {
  15261. const start = Math.max( 0, drawRange.start );
  15262. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15263. for ( let i = start, il = end; i < il; i += 3 ) {
  15264. const a = index.getX( i );
  15265. const b = index.getX( i + 1 );
  15266. const c = index.getX( i + 2 );
  15267. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15268. if ( intersection ) {
  15269. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15270. intersects.push( intersection );
  15271. }
  15272. }
  15273. }
  15274. } else if ( position !== undefined ) {
  15275. // non-indexed buffer geometry
  15276. if ( Array.isArray( material ) ) {
  15277. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15278. const group = groups[ i ];
  15279. const groupMaterial = material[ group.materialIndex ];
  15280. const start = Math.max( group.start, drawRange.start );
  15281. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15282. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15283. const a = j;
  15284. const b = j + 1;
  15285. const c = j + 2;
  15286. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15287. if ( intersection ) {
  15288. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15289. intersection.face.materialIndex = group.materialIndex;
  15290. intersects.push( intersection );
  15291. }
  15292. }
  15293. }
  15294. } else {
  15295. const start = Math.max( 0, drawRange.start );
  15296. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15297. for ( let i = start, il = end; i < il; i += 3 ) {
  15298. const a = i;
  15299. const b = i + 1;
  15300. const c = i + 2;
  15301. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15302. if ( intersection ) {
  15303. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15304. intersects.push( intersection );
  15305. }
  15306. }
  15307. }
  15308. }
  15309. }
  15310. }
  15311. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15312. let intersect;
  15313. if ( material.side === BackSide ) {
  15314. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15315. } else {
  15316. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15317. }
  15318. if ( intersect === null ) return null;
  15319. _intersectionPointWorld.copy( point );
  15320. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15321. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15322. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15323. return {
  15324. distance: distance,
  15325. point: _intersectionPointWorld.clone(),
  15326. object: object
  15327. };
  15328. }
  15329. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15330. object.getVertexPosition( a, _vA$1 );
  15331. object.getVertexPosition( b, _vB$1 );
  15332. object.getVertexPosition( c, _vC$1 );
  15333. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15334. if ( intersection ) {
  15335. const barycoord = new Vector3();
  15336. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15337. if ( uv ) {
  15338. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15339. }
  15340. if ( uv1 ) {
  15341. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15342. }
  15343. if ( normal ) {
  15344. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15345. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15346. intersection.normal.multiplyScalar( -1 );
  15347. }
  15348. }
  15349. const face = {
  15350. a: a,
  15351. b: b,
  15352. c: c,
  15353. normal: new Vector3(),
  15354. materialIndex: 0
  15355. };
  15356. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15357. intersection.face = face;
  15358. intersection.barycoord = barycoord;
  15359. }
  15360. return intersection;
  15361. }
  15362. /**
  15363. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15364. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15365. * of the axes.
  15366. *
  15367. * ```js
  15368. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15369. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15370. * const cube = new THREE.Mesh( geometry, material );
  15371. * scene.add( cube );
  15372. * ```
  15373. *
  15374. * @augments BufferGeometry
  15375. */
  15376. class BoxGeometry extends BufferGeometry {
  15377. /**
  15378. * Constructs a new box geometry.
  15379. *
  15380. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15381. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15382. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15383. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15384. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15385. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15386. */
  15387. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15388. super();
  15389. this.type = 'BoxGeometry';
  15390. /**
  15391. * Holds the constructor parameters that have been
  15392. * used to generate the geometry. Any modification
  15393. * after instantiation does not change the geometry.
  15394. *
  15395. * @type {Object}
  15396. */
  15397. this.parameters = {
  15398. width: width,
  15399. height: height,
  15400. depth: depth,
  15401. widthSegments: widthSegments,
  15402. heightSegments: heightSegments,
  15403. depthSegments: depthSegments
  15404. };
  15405. const scope = this;
  15406. // segments
  15407. widthSegments = Math.floor( widthSegments );
  15408. heightSegments = Math.floor( heightSegments );
  15409. depthSegments = Math.floor( depthSegments );
  15410. // buffers
  15411. const indices = [];
  15412. const vertices = [];
  15413. const normals = [];
  15414. const uvs = [];
  15415. // helper variables
  15416. let numberOfVertices = 0;
  15417. let groupStart = 0;
  15418. // build each side of the box geometry
  15419. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15420. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15421. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15422. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15423. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15424. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15425. // build geometry
  15426. this.setIndex( indices );
  15427. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15428. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15429. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15430. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15431. const segmentWidth = width / gridX;
  15432. const segmentHeight = height / gridY;
  15433. const widthHalf = width / 2;
  15434. const heightHalf = height / 2;
  15435. const depthHalf = depth / 2;
  15436. const gridX1 = gridX + 1;
  15437. const gridY1 = gridY + 1;
  15438. let vertexCounter = 0;
  15439. let groupCount = 0;
  15440. const vector = new Vector3();
  15441. // generate vertices, normals and uvs
  15442. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15443. const y = iy * segmentHeight - heightHalf;
  15444. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15445. const x = ix * segmentWidth - widthHalf;
  15446. // set values to correct vector component
  15447. vector[ u ] = x * udir;
  15448. vector[ v ] = y * vdir;
  15449. vector[ w ] = depthHalf;
  15450. // now apply vector to vertex buffer
  15451. vertices.push( vector.x, vector.y, vector.z );
  15452. // set values to correct vector component
  15453. vector[ u ] = 0;
  15454. vector[ v ] = 0;
  15455. vector[ w ] = depth > 0 ? 1 : -1;
  15456. // now apply vector to normal buffer
  15457. normals.push( vector.x, vector.y, vector.z );
  15458. // uvs
  15459. uvs.push( ix / gridX );
  15460. uvs.push( 1 - ( iy / gridY ) );
  15461. // counters
  15462. vertexCounter += 1;
  15463. }
  15464. }
  15465. // indices
  15466. // 1. you need three indices to draw a single face
  15467. // 2. a single segment consists of two faces
  15468. // 3. so we need to generate six (2*3) indices per segment
  15469. for ( let iy = 0; iy < gridY; iy ++ ) {
  15470. for ( let ix = 0; ix < gridX; ix ++ ) {
  15471. const a = numberOfVertices + ix + gridX1 * iy;
  15472. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15473. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15474. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15475. // faces
  15476. indices.push( a, b, d );
  15477. indices.push( b, c, d );
  15478. // increase counter
  15479. groupCount += 6;
  15480. }
  15481. }
  15482. // add a group to the geometry. this will ensure multi material support
  15483. scope.addGroup( groupStart, groupCount, materialIndex );
  15484. // calculate new start value for groups
  15485. groupStart += groupCount;
  15486. // update total number of vertices
  15487. numberOfVertices += vertexCounter;
  15488. }
  15489. }
  15490. copy( source ) {
  15491. super.copy( source );
  15492. this.parameters = Object.assign( {}, source.parameters );
  15493. return this;
  15494. }
  15495. /**
  15496. * Factory method for creating an instance of this class from the given
  15497. * JSON object.
  15498. *
  15499. * @param {Object} data - A JSON object representing the serialized geometry.
  15500. * @return {BoxGeometry} A new instance.
  15501. */
  15502. static fromJSON( data ) {
  15503. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15504. }
  15505. }
  15506. // Uniform Utilities
  15507. function cloneUniforms( src ) {
  15508. const dst = {};
  15509. for ( const u in src ) {
  15510. dst[ u ] = {};
  15511. for ( const p in src[ u ] ) {
  15512. const property = src[ u ][ p ];
  15513. if ( property && ( property.isColor ||
  15514. property.isMatrix3 || property.isMatrix4 ||
  15515. property.isVector2 || property.isVector3 || property.isVector4 ||
  15516. property.isTexture || property.isQuaternion ) ) {
  15517. if ( property.isRenderTargetTexture ) {
  15518. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15519. dst[ u ][ p ] = null;
  15520. } else {
  15521. dst[ u ][ p ] = property.clone();
  15522. }
  15523. } else if ( Array.isArray( property ) ) {
  15524. dst[ u ][ p ] = property.slice();
  15525. } else {
  15526. dst[ u ][ p ] = property;
  15527. }
  15528. }
  15529. }
  15530. return dst;
  15531. }
  15532. function mergeUniforms( uniforms ) {
  15533. const merged = {};
  15534. for ( let u = 0; u < uniforms.length; u ++ ) {
  15535. const tmp = cloneUniforms( uniforms[ u ] );
  15536. for ( const p in tmp ) {
  15537. merged[ p ] = tmp[ p ];
  15538. }
  15539. }
  15540. return merged;
  15541. }
  15542. function cloneUniformsGroups( src ) {
  15543. const dst = [];
  15544. for ( let u = 0; u < src.length; u ++ ) {
  15545. dst.push( src[ u ].clone() );
  15546. }
  15547. return dst;
  15548. }
  15549. function getUnlitUniformColorSpace( renderer ) {
  15550. const currentRenderTarget = renderer.getRenderTarget();
  15551. if ( currentRenderTarget === null ) {
  15552. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15553. return renderer.outputColorSpace;
  15554. }
  15555. // https://github.com/mrdoob/three.js/issues/27868
  15556. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15557. return currentRenderTarget.texture.colorSpace;
  15558. }
  15559. return ColorManagement.workingColorSpace;
  15560. }
  15561. // Legacy
  15562. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15563. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15564. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15565. /**
  15566. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15567. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15568. * effect not included with any of the built-in materials.
  15569. *
  15570. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15571. *
  15572. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15573. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15574. * you don't want that, use {@link RawShaderMaterial} instead.
  15575. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15576. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15577. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15578. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15579. * - The loop variable has to be *i*.
  15580. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15581. * value of *i* for the given iteration and can be used in preprocessor
  15582. * statements.
  15583. *
  15584. * ```js
  15585. * const material = new THREE.ShaderMaterial( {
  15586. * uniforms: {
  15587. * time: { value: 1.0 },
  15588. * resolution: { value: new THREE.Vector2() }
  15589. * },
  15590. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15591. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15592. * } );
  15593. * ```
  15594. *
  15595. * @augments Material
  15596. */
  15597. class ShaderMaterial extends Material {
  15598. /**
  15599. * Constructs a new shader material.
  15600. *
  15601. * @param {Object} [parameters] - An object with one or more properties
  15602. * defining the material's appearance. Any property of the material
  15603. * (including any property from inherited materials) can be passed
  15604. * in here. Color values can be passed any type of value accepted
  15605. * by {@link Color#set}.
  15606. */
  15607. constructor( parameters ) {
  15608. super();
  15609. /**
  15610. * This flag can be used for type testing.
  15611. *
  15612. * @type {boolean}
  15613. * @readonly
  15614. * @default true
  15615. */
  15616. this.isShaderMaterial = true;
  15617. this.type = 'ShaderMaterial';
  15618. /**
  15619. * Defines custom constants using `#define` directives within the GLSL code
  15620. * for both the vertex shader and the fragment shader; each key/value pair
  15621. * yields another directive.
  15622. * ```js
  15623. * defines: {
  15624. * FOO: 15,
  15625. * BAR: true
  15626. * }
  15627. * ```
  15628. * Yields the lines:
  15629. * ```
  15630. * #define FOO 15
  15631. * #define BAR true
  15632. * ```
  15633. *
  15634. * @type {Object}
  15635. */
  15636. this.defines = {};
  15637. /**
  15638. * An object of the form:
  15639. * ```js
  15640. * {
  15641. * "uniform1": { value: 1.0 },
  15642. * "uniform2": { value: 2 }
  15643. * }
  15644. * ```
  15645. * specifying the uniforms to be passed to the shader code; keys are uniform
  15646. * names, values are definitions of the form
  15647. * ```
  15648. * {
  15649. * value: 1.0
  15650. * }
  15651. * ```
  15652. * where `value` is the value of the uniform. Names must match the name of
  15653. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15654. * on every frame, so updating the value of the uniform will immediately
  15655. * update the value available to the GLSL code.
  15656. *
  15657. * @type {Object}
  15658. */
  15659. this.uniforms = {};
  15660. /**
  15661. * An array holding uniforms groups for configuring UBOs.
  15662. *
  15663. * @type {Array<UniformsGroup>}
  15664. */
  15665. this.uniformsGroups = [];
  15666. /**
  15667. * Vertex shader GLSL code. This is the actual code for the shader.
  15668. *
  15669. * @type {string}
  15670. */
  15671. this.vertexShader = default_vertex;
  15672. /**
  15673. * Fragment shader GLSL code. This is the actual code for the shader.
  15674. *
  15675. * @type {string}
  15676. */
  15677. this.fragmentShader = default_fragment;
  15678. /**
  15679. * Controls line thickness or lines.
  15680. *
  15681. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15682. * width of one pixel.
  15683. *
  15684. * @type {number}
  15685. * @default 1
  15686. */
  15687. this.linewidth = 1;
  15688. /**
  15689. * Renders the geometry as a wireframe.
  15690. *
  15691. * @type {boolean}
  15692. * @default false
  15693. */
  15694. this.wireframe = false;
  15695. /**
  15696. * Controls the thickness of the wireframe.
  15697. *
  15698. * WebGL and WebGPU ignore this property and always render
  15699. * 1 pixel wide lines.
  15700. *
  15701. * @type {number}
  15702. * @default 1
  15703. */
  15704. this.wireframeLinewidth = 1;
  15705. /**
  15706. * Define whether the material color is affected by global fog settings; `true`
  15707. * to pass fog uniforms to the shader.
  15708. *
  15709. * @type {boolean}
  15710. * @default false
  15711. */
  15712. this.fog = false;
  15713. /**
  15714. * Defines whether this material uses lighting; `true` to pass uniform data
  15715. * related to lighting to this shader.
  15716. *
  15717. * @type {boolean}
  15718. * @default false
  15719. */
  15720. this.lights = false;
  15721. /**
  15722. * Defines whether this material supports clipping; `true` to let the renderer
  15723. * pass the clippingPlanes uniform.
  15724. *
  15725. * @type {boolean}
  15726. * @default false
  15727. */
  15728. this.clipping = false;
  15729. /**
  15730. * Overwritten and set to `true` by default.
  15731. *
  15732. * @type {boolean}
  15733. * @default true
  15734. */
  15735. this.forceSinglePass = true;
  15736. /**
  15737. * This object allows to enable certain WebGL 2 extensions.
  15738. *
  15739. * - clipCullDistance: set to `true` to use vertex shader clipping
  15740. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15741. *
  15742. * @type {{clipCullDistance:false,multiDraw:false}}
  15743. */
  15744. this.extensions = {
  15745. clipCullDistance: false, // set to use vertex shader clipping
  15746. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15747. };
  15748. /**
  15749. * When the rendered geometry doesn't include these attributes but the
  15750. * material does, these default values will be passed to the shaders. This
  15751. * avoids errors when buffer data is missing.
  15752. *
  15753. * - color: [ 1, 1, 1 ]
  15754. * - uv: [ 0, 0 ]
  15755. * - uv1: [ 0, 0 ]
  15756. *
  15757. * @type {Object}
  15758. */
  15759. this.defaultAttributeValues = {
  15760. 'color': [ 1, 1, 1 ],
  15761. 'uv': [ 0, 0 ],
  15762. 'uv1': [ 0, 0 ]
  15763. };
  15764. /**
  15765. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15766. * to bind a generic vertex index to an attribute variable.
  15767. *
  15768. * @type {string|undefined}
  15769. * @default undefined
  15770. */
  15771. this.index0AttributeName = undefined;
  15772. /**
  15773. * Can be used to force a uniform update while changing uniforms in
  15774. * {@link Object3D#onBeforeRender}.
  15775. *
  15776. * @type {boolean}
  15777. * @default false
  15778. */
  15779. this.uniformsNeedUpdate = false;
  15780. /**
  15781. * Defines the GLSL version of custom shader code.
  15782. *
  15783. * @type {?(GLSL1|GLSL3)}
  15784. * @default null
  15785. */
  15786. this.glslVersion = null;
  15787. if ( parameters !== undefined ) {
  15788. this.setValues( parameters );
  15789. }
  15790. }
  15791. copy( source ) {
  15792. super.copy( source );
  15793. this.fragmentShader = source.fragmentShader;
  15794. this.vertexShader = source.vertexShader;
  15795. this.uniforms = cloneUniforms( source.uniforms );
  15796. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15797. this.defines = Object.assign( {}, source.defines );
  15798. this.wireframe = source.wireframe;
  15799. this.wireframeLinewidth = source.wireframeLinewidth;
  15800. this.fog = source.fog;
  15801. this.lights = source.lights;
  15802. this.clipping = source.clipping;
  15803. this.extensions = Object.assign( {}, source.extensions );
  15804. this.glslVersion = source.glslVersion;
  15805. return this;
  15806. }
  15807. toJSON( meta ) {
  15808. const data = super.toJSON( meta );
  15809. data.glslVersion = this.glslVersion;
  15810. data.uniforms = {};
  15811. for ( const name in this.uniforms ) {
  15812. const uniform = this.uniforms[ name ];
  15813. const value = uniform.value;
  15814. if ( value && value.isTexture ) {
  15815. data.uniforms[ name ] = {
  15816. type: 't',
  15817. value: value.toJSON( meta ).uuid
  15818. };
  15819. } else if ( value && value.isColor ) {
  15820. data.uniforms[ name ] = {
  15821. type: 'c',
  15822. value: value.getHex()
  15823. };
  15824. } else if ( value && value.isVector2 ) {
  15825. data.uniforms[ name ] = {
  15826. type: 'v2',
  15827. value: value.toArray()
  15828. };
  15829. } else if ( value && value.isVector3 ) {
  15830. data.uniforms[ name ] = {
  15831. type: 'v3',
  15832. value: value.toArray()
  15833. };
  15834. } else if ( value && value.isVector4 ) {
  15835. data.uniforms[ name ] = {
  15836. type: 'v4',
  15837. value: value.toArray()
  15838. };
  15839. } else if ( value && value.isMatrix3 ) {
  15840. data.uniforms[ name ] = {
  15841. type: 'm3',
  15842. value: value.toArray()
  15843. };
  15844. } else if ( value && value.isMatrix4 ) {
  15845. data.uniforms[ name ] = {
  15846. type: 'm4',
  15847. value: value.toArray()
  15848. };
  15849. } else {
  15850. data.uniforms[ name ] = {
  15851. value: value
  15852. };
  15853. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15854. }
  15855. }
  15856. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15857. data.vertexShader = this.vertexShader;
  15858. data.fragmentShader = this.fragmentShader;
  15859. data.lights = this.lights;
  15860. data.clipping = this.clipping;
  15861. const extensions = {};
  15862. for ( const key in this.extensions ) {
  15863. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15864. }
  15865. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15866. return data;
  15867. }
  15868. }
  15869. /**
  15870. * Abstract base class for cameras. This class should always be inherited
  15871. * when you build a new camera.
  15872. *
  15873. * @abstract
  15874. * @augments Object3D
  15875. */
  15876. class Camera extends Object3D {
  15877. /**
  15878. * Constructs a new camera.
  15879. */
  15880. constructor() {
  15881. super();
  15882. /**
  15883. * This flag can be used for type testing.
  15884. *
  15885. * @type {boolean}
  15886. * @readonly
  15887. * @default true
  15888. */
  15889. this.isCamera = true;
  15890. this.type = 'Camera';
  15891. /**
  15892. * The inverse of the camera's world matrix.
  15893. *
  15894. * @type {Matrix4}
  15895. */
  15896. this.matrixWorldInverse = new Matrix4();
  15897. /**
  15898. * The camera's projection matrix.
  15899. *
  15900. * @type {Matrix4}
  15901. */
  15902. this.projectionMatrix = new Matrix4();
  15903. /**
  15904. * The inverse of the camera's projection matrix.
  15905. *
  15906. * @type {Matrix4}
  15907. */
  15908. this.projectionMatrixInverse = new Matrix4();
  15909. /**
  15910. * The coordinate system in which the camera is used.
  15911. *
  15912. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15913. */
  15914. this.coordinateSystem = WebGLCoordinateSystem;
  15915. this._reversedDepth = false;
  15916. }
  15917. /**
  15918. * The flag that indicates whether the camera uses a reversed depth buffer.
  15919. *
  15920. * @type {boolean}
  15921. * @default false
  15922. */
  15923. get reversedDepth() {
  15924. return this._reversedDepth;
  15925. }
  15926. copy( source, recursive ) {
  15927. super.copy( source, recursive );
  15928. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15929. this.projectionMatrix.copy( source.projectionMatrix );
  15930. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15931. this.coordinateSystem = source.coordinateSystem;
  15932. return this;
  15933. }
  15934. /**
  15935. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15936. *
  15937. * This method is overwritten since cameras have a different forward vector compared to other
  15938. * 3D objects. A camera looks down its local, negative z-axis by default.
  15939. *
  15940. * @param {Vector3} target - The target vector the result is stored to.
  15941. * @return {Vector3} The 3D object's direction in world space.
  15942. */
  15943. getWorldDirection( target ) {
  15944. return super.getWorldDirection( target ).negate();
  15945. }
  15946. updateMatrixWorld( force ) {
  15947. super.updateMatrixWorld( force );
  15948. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15949. }
  15950. updateWorldMatrix( updateParents, updateChildren ) {
  15951. super.updateWorldMatrix( updateParents, updateChildren );
  15952. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15953. }
  15954. clone() {
  15955. return new this.constructor().copy( this );
  15956. }
  15957. }
  15958. const _v3$1 = /*@__PURE__*/ new Vector3();
  15959. const _minTarget = /*@__PURE__*/ new Vector2();
  15960. const _maxTarget = /*@__PURE__*/ new Vector2();
  15961. /**
  15962. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15963. *
  15964. * This projection mode is designed to mimic the way the human eye sees. It
  15965. * is the most common projection mode used for rendering a 3D scene.
  15966. *
  15967. * ```js
  15968. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15969. * scene.add( camera );
  15970. * ```
  15971. *
  15972. * @augments Camera
  15973. */
  15974. class PerspectiveCamera extends Camera {
  15975. /**
  15976. * Constructs a new perspective camera.
  15977. *
  15978. * @param {number} [fov=50] - The vertical field of view.
  15979. * @param {number} [aspect=1] - The aspect ratio.
  15980. * @param {number} [near=0.1] - The camera's near plane.
  15981. * @param {number} [far=2000] - The camera's far plane.
  15982. */
  15983. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15984. super();
  15985. /**
  15986. * This flag can be used for type testing.
  15987. *
  15988. * @type {boolean}
  15989. * @readonly
  15990. * @default true
  15991. */
  15992. this.isPerspectiveCamera = true;
  15993. this.type = 'PerspectiveCamera';
  15994. /**
  15995. * The vertical field of view, from bottom to top of view,
  15996. * in degrees.
  15997. *
  15998. * @type {number}
  15999. * @default 50
  16000. */
  16001. this.fov = fov;
  16002. /**
  16003. * The zoom factor of the camera.
  16004. *
  16005. * @type {number}
  16006. * @default 1
  16007. */
  16008. this.zoom = 1;
  16009. /**
  16010. * The camera's near plane. The valid range is greater than `0`
  16011. * and less than the current value of {@link PerspectiveCamera#far}.
  16012. *
  16013. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16014. * valid value for a perspective camera's near plane.
  16015. *
  16016. * @type {number}
  16017. * @default 0.1
  16018. */
  16019. this.near = near;
  16020. /**
  16021. * The camera's far plane. Must be greater than the
  16022. * current value of {@link PerspectiveCamera#near}.
  16023. *
  16024. * @type {number}
  16025. * @default 2000
  16026. */
  16027. this.far = far;
  16028. /**
  16029. * Object distance used for stereoscopy and depth-of-field effects. This
  16030. * parameter does not influence the projection matrix unless a
  16031. * {@link StereoCamera} is being used.
  16032. *
  16033. * @type {number}
  16034. * @default 10
  16035. */
  16036. this.focus = 10;
  16037. /**
  16038. * The aspect ratio, usually the canvas width / canvas height.
  16039. *
  16040. * @type {number}
  16041. * @default 1
  16042. */
  16043. this.aspect = aspect;
  16044. /**
  16045. * Represents the frustum window specification. This property should not be edited
  16046. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16047. *
  16048. * @type {?Object}
  16049. * @default null
  16050. */
  16051. this.view = null;
  16052. /**
  16053. * Film size used for the larger axis. Default is `35` (millimeters). This
  16054. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16055. * is set to a nonzero value.
  16056. *
  16057. * @type {number}
  16058. * @default 35
  16059. */
  16060. this.filmGauge = 35;
  16061. /**
  16062. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16063. *
  16064. * @type {number}
  16065. * @default 0
  16066. */
  16067. this.filmOffset = 0;
  16068. this.updateProjectionMatrix();
  16069. }
  16070. copy( source, recursive ) {
  16071. super.copy( source, recursive );
  16072. this.fov = source.fov;
  16073. this.zoom = source.zoom;
  16074. this.near = source.near;
  16075. this.far = source.far;
  16076. this.focus = source.focus;
  16077. this.aspect = source.aspect;
  16078. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16079. this.filmGauge = source.filmGauge;
  16080. this.filmOffset = source.filmOffset;
  16081. return this;
  16082. }
  16083. /**
  16084. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16085. *
  16086. * The default film gauge is 35, so that the focal length can be specified for
  16087. * a 35mm (full frame) camera.
  16088. *
  16089. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16090. */
  16091. setFocalLength( focalLength ) {
  16092. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16093. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16094. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16095. this.updateProjectionMatrix();
  16096. }
  16097. /**
  16098. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16099. * {@link PerspectiveCamera#filmGauge}.
  16100. *
  16101. * @return {number} The computed focal length.
  16102. */
  16103. getFocalLength() {
  16104. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16105. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16106. }
  16107. /**
  16108. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16109. *
  16110. * @return {number} The effective FOV.
  16111. */
  16112. getEffectiveFOV() {
  16113. return RAD2DEG * 2 * Math.atan(
  16114. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16115. }
  16116. /**
  16117. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16118. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16119. *
  16120. * @return {number} The film width.
  16121. */
  16122. getFilmWidth() {
  16123. // film not completely covered in portrait format (aspect < 1)
  16124. return this.filmGauge * Math.min( this.aspect, 1 );
  16125. }
  16126. /**
  16127. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16128. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16129. *
  16130. * @return {number} The film width.
  16131. */
  16132. getFilmHeight() {
  16133. // film not completely covered in landscape format (aspect > 1)
  16134. return this.filmGauge / Math.max( this.aspect, 1 );
  16135. }
  16136. /**
  16137. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16138. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16139. *
  16140. * @param {number} distance - The viewing distance.
  16141. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16142. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16143. */
  16144. getViewBounds( distance, minTarget, maxTarget ) {
  16145. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16146. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16147. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16148. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16149. }
  16150. /**
  16151. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16152. *
  16153. * @param {number} distance - The viewing distance.
  16154. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16155. * @returns {Vector2} The view size.
  16156. */
  16157. getViewSize( distance, target ) {
  16158. this.getViewBounds( distance, _minTarget, _maxTarget );
  16159. return target.subVectors( _maxTarget, _minTarget );
  16160. }
  16161. /**
  16162. * Sets an offset in a larger frustum. This is useful for multi-window or
  16163. * multi-monitor/multi-machine setups.
  16164. *
  16165. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16166. * the monitors are in grid like this
  16167. *```
  16168. * +---+---+---+
  16169. * | A | B | C |
  16170. * +---+---+---+
  16171. * | D | E | F |
  16172. * +---+---+---+
  16173. *```
  16174. * then for each monitor you would call it like this:
  16175. *```js
  16176. * const w = 1920;
  16177. * const h = 1080;
  16178. * const fullWidth = w * 3;
  16179. * const fullHeight = h * 2;
  16180. *
  16181. * // --A--
  16182. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16183. * // --B--
  16184. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16185. * // --C--
  16186. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16187. * // --D--
  16188. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16189. * // --E--
  16190. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16191. * // --F--
  16192. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16193. * ```
  16194. *
  16195. * Note there is no reason monitors have to be the same size or in a grid.
  16196. *
  16197. * @param {number} fullWidth - The full width of multiview setup.
  16198. * @param {number} fullHeight - The full height of multiview setup.
  16199. * @param {number} x - The horizontal offset of the subcamera.
  16200. * @param {number} y - The vertical offset of the subcamera.
  16201. * @param {number} width - The width of subcamera.
  16202. * @param {number} height - The height of subcamera.
  16203. */
  16204. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16205. this.aspect = fullWidth / fullHeight;
  16206. if ( this.view === null ) {
  16207. this.view = {
  16208. enabled: true,
  16209. fullWidth: 1,
  16210. fullHeight: 1,
  16211. offsetX: 0,
  16212. offsetY: 0,
  16213. width: 1,
  16214. height: 1
  16215. };
  16216. }
  16217. this.view.enabled = true;
  16218. this.view.fullWidth = fullWidth;
  16219. this.view.fullHeight = fullHeight;
  16220. this.view.offsetX = x;
  16221. this.view.offsetY = y;
  16222. this.view.width = width;
  16223. this.view.height = height;
  16224. this.updateProjectionMatrix();
  16225. }
  16226. /**
  16227. * Removes the view offset from the projection matrix.
  16228. */
  16229. clearViewOffset() {
  16230. if ( this.view !== null ) {
  16231. this.view.enabled = false;
  16232. }
  16233. this.updateProjectionMatrix();
  16234. }
  16235. /**
  16236. * Updates the camera's projection matrix. Must be called after any change of
  16237. * camera properties.
  16238. */
  16239. updateProjectionMatrix() {
  16240. const near = this.near;
  16241. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16242. let height = 2 * top;
  16243. let width = this.aspect * height;
  16244. let left = -0.5 * width;
  16245. const view = this.view;
  16246. if ( this.view !== null && this.view.enabled ) {
  16247. const fullWidth = view.fullWidth,
  16248. fullHeight = view.fullHeight;
  16249. left += view.offsetX * width / fullWidth;
  16250. top -= view.offsetY * height / fullHeight;
  16251. width *= view.width / fullWidth;
  16252. height *= view.height / fullHeight;
  16253. }
  16254. const skew = this.filmOffset;
  16255. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16256. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16257. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16258. }
  16259. toJSON( meta ) {
  16260. const data = super.toJSON( meta );
  16261. data.object.fov = this.fov;
  16262. data.object.zoom = this.zoom;
  16263. data.object.near = this.near;
  16264. data.object.far = this.far;
  16265. data.object.focus = this.focus;
  16266. data.object.aspect = this.aspect;
  16267. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16268. data.object.filmGauge = this.filmGauge;
  16269. data.object.filmOffset = this.filmOffset;
  16270. return data;
  16271. }
  16272. }
  16273. const fov = -90; // negative fov is not an error
  16274. const aspect = 1;
  16275. /**
  16276. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16277. * cube render target. The render target can then be used as an environment map for rendering
  16278. * realtime reflections in your scene.
  16279. *
  16280. * ```js
  16281. * // Create cube render target
  16282. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16283. *
  16284. * // Create cube camera
  16285. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16286. * scene.add( cubeCamera );
  16287. *
  16288. * // Create car
  16289. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16290. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16291. * scene.add( car );
  16292. *
  16293. * // Update the render target cube
  16294. * car.visible = false;
  16295. * cubeCamera.position.copy( car.position );
  16296. * cubeCamera.update( renderer, scene );
  16297. *
  16298. * // Render the scene
  16299. * car.visible = true;
  16300. * renderer.render( scene, camera );
  16301. * ```
  16302. *
  16303. * @augments Object3D
  16304. */
  16305. class CubeCamera extends Object3D {
  16306. /**
  16307. * Constructs a new cube camera.
  16308. *
  16309. * @param {number} near - The camera's near plane.
  16310. * @param {number} far - The camera's far plane.
  16311. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16312. */
  16313. constructor( near, far, renderTarget ) {
  16314. super();
  16315. this.type = 'CubeCamera';
  16316. /**
  16317. * A reference to the cube render target.
  16318. *
  16319. * @type {WebGLCubeRenderTarget}
  16320. */
  16321. this.renderTarget = renderTarget;
  16322. /**
  16323. * The current active coordinate system.
  16324. *
  16325. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16326. * @default null
  16327. */
  16328. this.coordinateSystem = null;
  16329. /**
  16330. * The current active mipmap level
  16331. *
  16332. * @type {number}
  16333. * @default 0
  16334. */
  16335. this.activeMipmapLevel = 0;
  16336. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16337. cameraPX.layers = this.layers;
  16338. this.add( cameraPX );
  16339. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16340. cameraNX.layers = this.layers;
  16341. this.add( cameraNX );
  16342. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16343. cameraPY.layers = this.layers;
  16344. this.add( cameraPY );
  16345. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16346. cameraNY.layers = this.layers;
  16347. this.add( cameraNY );
  16348. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16349. cameraPZ.layers = this.layers;
  16350. this.add( cameraPZ );
  16351. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16352. cameraNZ.layers = this.layers;
  16353. this.add( cameraNZ );
  16354. }
  16355. /**
  16356. * Must be called when the coordinate system of the cube camera is changed.
  16357. */
  16358. updateCoordinateSystem() {
  16359. const coordinateSystem = this.coordinateSystem;
  16360. const cameras = this.children.concat();
  16361. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16362. for ( const camera of cameras ) this.remove( camera );
  16363. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16364. cameraPX.up.set( 0, 1, 0 );
  16365. cameraPX.lookAt( 1, 0, 0 );
  16366. cameraNX.up.set( 0, 1, 0 );
  16367. cameraNX.lookAt( -1, 0, 0 );
  16368. cameraPY.up.set( 0, 0, -1 );
  16369. cameraPY.lookAt( 0, 1, 0 );
  16370. cameraNY.up.set( 0, 0, 1 );
  16371. cameraNY.lookAt( 0, -1, 0 );
  16372. cameraPZ.up.set( 0, 1, 0 );
  16373. cameraPZ.lookAt( 0, 0, 1 );
  16374. cameraNZ.up.set( 0, 1, 0 );
  16375. cameraNZ.lookAt( 0, 0, -1 );
  16376. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16377. cameraPX.up.set( 0, -1, 0 );
  16378. cameraPX.lookAt( -1, 0, 0 );
  16379. cameraNX.up.set( 0, -1, 0 );
  16380. cameraNX.lookAt( 1, 0, 0 );
  16381. cameraPY.up.set( 0, 0, 1 );
  16382. cameraPY.lookAt( 0, 1, 0 );
  16383. cameraNY.up.set( 0, 0, -1 );
  16384. cameraNY.lookAt( 0, -1, 0 );
  16385. cameraPZ.up.set( 0, -1, 0 );
  16386. cameraPZ.lookAt( 0, 0, 1 );
  16387. cameraNZ.up.set( 0, -1, 0 );
  16388. cameraNZ.lookAt( 0, 0, -1 );
  16389. } else {
  16390. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16391. }
  16392. for ( const camera of cameras ) {
  16393. this.add( camera );
  16394. camera.updateMatrixWorld();
  16395. }
  16396. }
  16397. /**
  16398. * Calling this method will render the given scene with the given renderer
  16399. * into the cube render target of the camera.
  16400. *
  16401. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16402. * @param {Scene} scene - The scene to render.
  16403. */
  16404. update( renderer, scene ) {
  16405. if ( this.parent === null ) this.updateMatrixWorld();
  16406. const { renderTarget, activeMipmapLevel } = this;
  16407. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16408. this.coordinateSystem = renderer.coordinateSystem;
  16409. this.updateCoordinateSystem();
  16410. }
  16411. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16412. const currentRenderTarget = renderer.getRenderTarget();
  16413. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16414. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16415. const currentXrEnabled = renderer.xr.enabled;
  16416. renderer.xr.enabled = false;
  16417. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16418. renderTarget.texture.generateMipmaps = false;
  16419. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16420. renderer.render( scene, cameraPX );
  16421. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16422. renderer.render( scene, cameraNX );
  16423. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16424. renderer.render( scene, cameraPY );
  16425. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16426. renderer.render( scene, cameraNY );
  16427. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16428. renderer.render( scene, cameraPZ );
  16429. // mipmaps are generated during the last call of render()
  16430. // at this point, all sides of the cube render target are defined
  16431. renderTarget.texture.generateMipmaps = generateMipmaps;
  16432. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16433. renderer.render( scene, cameraNZ );
  16434. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16435. renderer.xr.enabled = currentXrEnabled;
  16436. renderTarget.texture.needsPMREMUpdate = true;
  16437. }
  16438. }
  16439. /**
  16440. * Creates a cube texture made up of six images.
  16441. *
  16442. * ```js
  16443. * const loader = new THREE.CubeTextureLoader();
  16444. * loader.setPath( 'textures/cube/pisa/' );
  16445. *
  16446. * const textureCube = loader.load( [
  16447. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16448. * ] );
  16449. *
  16450. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16451. * ```
  16452. *
  16453. * @augments Texture
  16454. */
  16455. class CubeTexture extends Texture {
  16456. /**
  16457. * Constructs a new cube texture.
  16458. *
  16459. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16460. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16461. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16462. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16463. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16464. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16465. * @param {number} [format=RGBAFormat] - The texture format.
  16466. * @param {number} [type=UnsignedByteType] - The texture type.
  16467. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16468. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16469. */
  16470. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16471. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16472. /**
  16473. * This flag can be used for type testing.
  16474. *
  16475. * @type {boolean}
  16476. * @readonly
  16477. * @default true
  16478. */
  16479. this.isCubeTexture = true;
  16480. /**
  16481. * If set to `true`, the texture is flipped along the vertical axis when
  16482. * uploaded to the GPU.
  16483. *
  16484. * Overwritten and set to `false` by default.
  16485. *
  16486. * @type {boolean}
  16487. * @default false
  16488. */
  16489. this.flipY = false;
  16490. }
  16491. /**
  16492. * Alias for {@link CubeTexture#image}.
  16493. *
  16494. * @type {Array<Image>}
  16495. */
  16496. get images() {
  16497. return this.image;
  16498. }
  16499. set images( value ) {
  16500. this.image = value;
  16501. }
  16502. }
  16503. /**
  16504. * A cube render target used in context of {@link WebGLRenderer}.
  16505. *
  16506. * @augments WebGLRenderTarget
  16507. */
  16508. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16509. /**
  16510. * Constructs a new cube render target.
  16511. *
  16512. * @param {number} [size=1] - The size of the render target.
  16513. * @param {RenderTarget~Options} [options] - The configuration object.
  16514. */
  16515. constructor( size = 1, options = {} ) {
  16516. super( size, size, options );
  16517. /**
  16518. * This flag can be used for type testing.
  16519. *
  16520. * @type {boolean}
  16521. * @readonly
  16522. * @default true
  16523. */
  16524. this.isWebGLCubeRenderTarget = true;
  16525. const image = { width: size, height: size, depth: 1 };
  16526. const images = [ image, image, image, image, image, image ];
  16527. /**
  16528. * Overwritten with a different texture type.
  16529. *
  16530. * @type {DataArrayTexture}
  16531. */
  16532. this.texture = new CubeTexture( images );
  16533. this._setTextureOptions( options );
  16534. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16535. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16536. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16537. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16538. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16539. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16540. this.texture.isRenderTargetTexture = true;
  16541. }
  16542. /**
  16543. * Converts the given equirectangular texture to a cube map.
  16544. *
  16545. * @param {WebGLRenderer} renderer - The renderer.
  16546. * @param {Texture} texture - The equirectangular texture.
  16547. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16548. */
  16549. fromEquirectangularTexture( renderer, texture ) {
  16550. this.texture.type = texture.type;
  16551. this.texture.colorSpace = texture.colorSpace;
  16552. this.texture.generateMipmaps = texture.generateMipmaps;
  16553. this.texture.minFilter = texture.minFilter;
  16554. this.texture.magFilter = texture.magFilter;
  16555. const shader = {
  16556. uniforms: {
  16557. tEquirect: { value: null },
  16558. },
  16559. vertexShader: /* glsl */`
  16560. varying vec3 vWorldDirection;
  16561. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16562. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16563. }
  16564. void main() {
  16565. vWorldDirection = transformDirection( position, modelMatrix );
  16566. #include <begin_vertex>
  16567. #include <project_vertex>
  16568. }
  16569. `,
  16570. fragmentShader: /* glsl */`
  16571. uniform sampler2D tEquirect;
  16572. varying vec3 vWorldDirection;
  16573. #include <common>
  16574. void main() {
  16575. vec3 direction = normalize( vWorldDirection );
  16576. vec2 sampleUV = equirectUv( direction );
  16577. gl_FragColor = texture2D( tEquirect, sampleUV );
  16578. }
  16579. `
  16580. };
  16581. const geometry = new BoxGeometry( 5, 5, 5 );
  16582. const material = new ShaderMaterial( {
  16583. name: 'CubemapFromEquirect',
  16584. uniforms: cloneUniforms( shader.uniforms ),
  16585. vertexShader: shader.vertexShader,
  16586. fragmentShader: shader.fragmentShader,
  16587. side: BackSide,
  16588. blending: NoBlending
  16589. } );
  16590. material.uniforms.tEquirect.value = texture;
  16591. const mesh = new Mesh( geometry, material );
  16592. const currentMinFilter = texture.minFilter;
  16593. // Avoid blurred poles
  16594. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16595. const camera = new CubeCamera( 1, 10, this );
  16596. camera.update( renderer, mesh );
  16597. texture.minFilter = currentMinFilter;
  16598. mesh.geometry.dispose();
  16599. mesh.material.dispose();
  16600. return this;
  16601. }
  16602. /**
  16603. * Clears this cube render target.
  16604. *
  16605. * @param {WebGLRenderer} renderer - The renderer.
  16606. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16607. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16608. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16609. */
  16610. clear( renderer, color = true, depth = true, stencil = true ) {
  16611. const currentRenderTarget = renderer.getRenderTarget();
  16612. for ( let i = 0; i < 6; i ++ ) {
  16613. renderer.setRenderTarget( this, i );
  16614. renderer.clear( color, depth, stencil );
  16615. }
  16616. renderer.setRenderTarget( currentRenderTarget );
  16617. }
  16618. }
  16619. /**
  16620. * This is almost identical to an {@link Object3D}. Its purpose is to
  16621. * make working with groups of objects syntactically clearer.
  16622. *
  16623. * ```js
  16624. * // Create a group and add the two cubes.
  16625. * // These cubes can now be rotated / scaled etc as a group.
  16626. * const group = new THREE.Group();
  16627. *
  16628. * group.add( meshA );
  16629. * group.add( meshB );
  16630. *
  16631. * scene.add( group );
  16632. * ```
  16633. *
  16634. * @augments Object3D
  16635. */
  16636. class Group extends Object3D {
  16637. constructor() {
  16638. super();
  16639. /**
  16640. * This flag can be used for type testing.
  16641. *
  16642. * @type {boolean}
  16643. * @readonly
  16644. * @default true
  16645. */
  16646. this.isGroup = true;
  16647. this.type = 'Group';
  16648. }
  16649. }
  16650. const _moveEvent = { type: 'move' };
  16651. /**
  16652. * Class for representing a XR controller with its
  16653. * different coordinate systems.
  16654. *
  16655. * @private
  16656. */
  16657. class WebXRController {
  16658. /**
  16659. * Constructs a new XR controller.
  16660. */
  16661. constructor() {
  16662. /**
  16663. * A group representing the target ray space
  16664. * of the XR controller.
  16665. *
  16666. * @private
  16667. * @type {?Group}
  16668. * @default null
  16669. */
  16670. this._targetRay = null;
  16671. /**
  16672. * A group representing the grip space
  16673. * of the XR controller.
  16674. *
  16675. * @private
  16676. * @type {?Group}
  16677. * @default null
  16678. */
  16679. this._grip = null;
  16680. /**
  16681. * A group representing the hand space
  16682. * of the XR controller.
  16683. *
  16684. * @private
  16685. * @type {?Group}
  16686. * @default null
  16687. */
  16688. this._hand = null;
  16689. }
  16690. /**
  16691. * Returns a group representing the hand space of the XR controller.
  16692. *
  16693. * @return {Group} A group representing the hand space of the XR controller.
  16694. */
  16695. getHandSpace() {
  16696. if ( this._hand === null ) {
  16697. this._hand = new Group();
  16698. this._hand.matrixAutoUpdate = false;
  16699. this._hand.visible = false;
  16700. this._hand.joints = {};
  16701. this._hand.inputState = { pinching: false };
  16702. }
  16703. return this._hand;
  16704. }
  16705. /**
  16706. * Returns a group representing the target ray space of the XR controller.
  16707. *
  16708. * @return {Group} A group representing the target ray space of the XR controller.
  16709. */
  16710. getTargetRaySpace() {
  16711. if ( this._targetRay === null ) {
  16712. this._targetRay = new Group();
  16713. this._targetRay.matrixAutoUpdate = false;
  16714. this._targetRay.visible = false;
  16715. this._targetRay.hasLinearVelocity = false;
  16716. this._targetRay.linearVelocity = new Vector3();
  16717. this._targetRay.hasAngularVelocity = false;
  16718. this._targetRay.angularVelocity = new Vector3();
  16719. }
  16720. return this._targetRay;
  16721. }
  16722. /**
  16723. * Returns a group representing the grip space of the XR controller.
  16724. *
  16725. * @return {Group} A group representing the grip space of the XR controller.
  16726. */
  16727. getGripSpace() {
  16728. if ( this._grip === null ) {
  16729. this._grip = new Group();
  16730. this._grip.matrixAutoUpdate = false;
  16731. this._grip.visible = false;
  16732. this._grip.hasLinearVelocity = false;
  16733. this._grip.linearVelocity = new Vector3();
  16734. this._grip.hasAngularVelocity = false;
  16735. this._grip.angularVelocity = new Vector3();
  16736. }
  16737. return this._grip;
  16738. }
  16739. /**
  16740. * Dispatches the given event to the groups representing
  16741. * the different coordinate spaces of the XR controller.
  16742. *
  16743. * @param {Object} event - The event to dispatch.
  16744. * @return {WebXRController} A reference to this instance.
  16745. */
  16746. dispatchEvent( event ) {
  16747. if ( this._targetRay !== null ) {
  16748. this._targetRay.dispatchEvent( event );
  16749. }
  16750. if ( this._grip !== null ) {
  16751. this._grip.dispatchEvent( event );
  16752. }
  16753. if ( this._hand !== null ) {
  16754. this._hand.dispatchEvent( event );
  16755. }
  16756. return this;
  16757. }
  16758. /**
  16759. * Connects the controller with the given XR input source.
  16760. *
  16761. * @param {XRInputSource} inputSource - The input source.
  16762. * @return {WebXRController} A reference to this instance.
  16763. */
  16764. connect( inputSource ) {
  16765. if ( inputSource && inputSource.hand ) {
  16766. const hand = this._hand;
  16767. if ( hand ) {
  16768. for ( const inputjoint of inputSource.hand.values() ) {
  16769. // Initialize hand with joints when connected
  16770. this._getHandJoint( hand, inputjoint );
  16771. }
  16772. }
  16773. }
  16774. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16775. return this;
  16776. }
  16777. /**
  16778. * Disconnects the controller from the given XR input source.
  16779. *
  16780. * @param {XRInputSource} inputSource - The input source.
  16781. * @return {WebXRController} A reference to this instance.
  16782. */
  16783. disconnect( inputSource ) {
  16784. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16785. if ( this._targetRay !== null ) {
  16786. this._targetRay.visible = false;
  16787. }
  16788. if ( this._grip !== null ) {
  16789. this._grip.visible = false;
  16790. }
  16791. if ( this._hand !== null ) {
  16792. this._hand.visible = false;
  16793. }
  16794. return this;
  16795. }
  16796. /**
  16797. * Updates the controller with the given input source, XR frame and reference space.
  16798. * This updates the transformations of the groups that represent the different
  16799. * coordinate systems of the controller.
  16800. *
  16801. * @param {XRInputSource} inputSource - The input source.
  16802. * @param {XRFrame} frame - The XR frame.
  16803. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16804. * @return {WebXRController} A reference to this instance.
  16805. */
  16806. update( inputSource, frame, referenceSpace ) {
  16807. let inputPose = null;
  16808. let gripPose = null;
  16809. let handPose = null;
  16810. const targetRay = this._targetRay;
  16811. const grip = this._grip;
  16812. const hand = this._hand;
  16813. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16814. if ( hand && inputSource.hand ) {
  16815. handPose = true;
  16816. for ( const inputjoint of inputSource.hand.values() ) {
  16817. // Update the joints groups with the XRJoint poses
  16818. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16819. // The transform of this joint will be updated with the joint pose on each frame
  16820. const joint = this._getHandJoint( hand, inputjoint );
  16821. if ( jointPose !== null ) {
  16822. joint.matrix.fromArray( jointPose.transform.matrix );
  16823. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16824. joint.matrixWorldNeedsUpdate = true;
  16825. joint.jointRadius = jointPose.radius;
  16826. }
  16827. joint.visible = jointPose !== null;
  16828. }
  16829. // Custom events
  16830. // Check pinchz
  16831. const indexTip = hand.joints[ 'index-finger-tip' ];
  16832. const thumbTip = hand.joints[ 'thumb-tip' ];
  16833. const distance = indexTip.position.distanceTo( thumbTip.position );
  16834. const distanceToPinch = 0.02;
  16835. const threshold = 0.005;
  16836. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16837. hand.inputState.pinching = false;
  16838. this.dispatchEvent( {
  16839. type: 'pinchend',
  16840. handedness: inputSource.handedness,
  16841. target: this
  16842. } );
  16843. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16844. hand.inputState.pinching = true;
  16845. this.dispatchEvent( {
  16846. type: 'pinchstart',
  16847. handedness: inputSource.handedness,
  16848. target: this
  16849. } );
  16850. }
  16851. } else {
  16852. if ( grip !== null && inputSource.gripSpace ) {
  16853. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16854. if ( gripPose !== null ) {
  16855. grip.matrix.fromArray( gripPose.transform.matrix );
  16856. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16857. grip.matrixWorldNeedsUpdate = true;
  16858. if ( gripPose.linearVelocity ) {
  16859. grip.hasLinearVelocity = true;
  16860. grip.linearVelocity.copy( gripPose.linearVelocity );
  16861. } else {
  16862. grip.hasLinearVelocity = false;
  16863. }
  16864. if ( gripPose.angularVelocity ) {
  16865. grip.hasAngularVelocity = true;
  16866. grip.angularVelocity.copy( gripPose.angularVelocity );
  16867. } else {
  16868. grip.hasAngularVelocity = false;
  16869. }
  16870. }
  16871. }
  16872. }
  16873. if ( targetRay !== null ) {
  16874. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16875. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16876. if ( inputPose === null && gripPose !== null ) {
  16877. inputPose = gripPose;
  16878. }
  16879. if ( inputPose !== null ) {
  16880. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16881. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16882. targetRay.matrixWorldNeedsUpdate = true;
  16883. if ( inputPose.linearVelocity ) {
  16884. targetRay.hasLinearVelocity = true;
  16885. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16886. } else {
  16887. targetRay.hasLinearVelocity = false;
  16888. }
  16889. if ( inputPose.angularVelocity ) {
  16890. targetRay.hasAngularVelocity = true;
  16891. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16892. } else {
  16893. targetRay.hasAngularVelocity = false;
  16894. }
  16895. this.dispatchEvent( _moveEvent );
  16896. }
  16897. }
  16898. }
  16899. if ( targetRay !== null ) {
  16900. targetRay.visible = ( inputPose !== null );
  16901. }
  16902. if ( grip !== null ) {
  16903. grip.visible = ( gripPose !== null );
  16904. }
  16905. if ( hand !== null ) {
  16906. hand.visible = ( handPose !== null );
  16907. }
  16908. return this;
  16909. }
  16910. /**
  16911. * Returns a group representing the hand joint for the given input joint.
  16912. *
  16913. * @private
  16914. * @param {Group} hand - The group representing the hand space.
  16915. * @param {XRJointSpace} inputjoint - The hand joint data.
  16916. * @return {Group} A group representing the hand joint for the given input joint.
  16917. */
  16918. _getHandJoint( hand, inputjoint ) {
  16919. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16920. const joint = new Group();
  16921. joint.matrixAutoUpdate = false;
  16922. joint.visible = false;
  16923. hand.joints[ inputjoint.jointName ] = joint;
  16924. hand.add( joint );
  16925. }
  16926. return hand.joints[ inputjoint.jointName ];
  16927. }
  16928. }
  16929. /**
  16930. * This class can be used to define an exponential squared fog,
  16931. * which gives a clear view near the camera and a faster than exponentially
  16932. * densening fog farther from the camera.
  16933. *
  16934. * ```js
  16935. * const scene = new THREE.Scene();
  16936. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16937. * ```
  16938. */
  16939. class FogExp2 {
  16940. /**
  16941. * Constructs a new fog.
  16942. *
  16943. * @param {number|Color} color - The fog's color.
  16944. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16945. */
  16946. constructor( color, density = 0.00025 ) {
  16947. /**
  16948. * This flag can be used for type testing.
  16949. *
  16950. * @type {boolean}
  16951. * @readonly
  16952. * @default true
  16953. */
  16954. this.isFogExp2 = true;
  16955. /**
  16956. * The name of the fog.
  16957. *
  16958. * @type {string}
  16959. */
  16960. this.name = '';
  16961. /**
  16962. * The fog's color.
  16963. *
  16964. * @type {Color}
  16965. */
  16966. this.color = new Color( color );
  16967. /**
  16968. * Defines how fast the fog will grow dense.
  16969. *
  16970. * @type {number}
  16971. * @default 0.00025
  16972. */
  16973. this.density = density;
  16974. }
  16975. /**
  16976. * Returns a new fog with copied values from this instance.
  16977. *
  16978. * @return {FogExp2} A clone of this instance.
  16979. */
  16980. clone() {
  16981. return new FogExp2( this.color, this.density );
  16982. }
  16983. /**
  16984. * Serializes the fog into JSON.
  16985. *
  16986. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16987. * @return {Object} A JSON object representing the serialized fog
  16988. */
  16989. toJSON( /* meta */ ) {
  16990. return {
  16991. type: 'FogExp2',
  16992. name: this.name,
  16993. color: this.color.getHex(),
  16994. density: this.density
  16995. };
  16996. }
  16997. }
  16998. /**
  16999. * This class can be used to define a linear fog that grows linearly denser
  17000. * with the distance.
  17001. *
  17002. * ```js
  17003. * const scene = new THREE.Scene();
  17004. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17005. * ```
  17006. */
  17007. class Fog {
  17008. /**
  17009. * Constructs a new fog.
  17010. *
  17011. * @param {number|Color} color - The fog's color.
  17012. * @param {number} [near=1] - The minimum distance to start applying fog.
  17013. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17014. */
  17015. constructor( color, near = 1, far = 1000 ) {
  17016. /**
  17017. * This flag can be used for type testing.
  17018. *
  17019. * @type {boolean}
  17020. * @readonly
  17021. * @default true
  17022. */
  17023. this.isFog = true;
  17024. /**
  17025. * The name of the fog.
  17026. *
  17027. * @type {string}
  17028. */
  17029. this.name = '';
  17030. /**
  17031. * The fog's color.
  17032. *
  17033. * @type {Color}
  17034. */
  17035. this.color = new Color( color );
  17036. /**
  17037. * The minimum distance to start applying fog. Objects that are less than
  17038. * `near` units from the active camera won't be affected by fog.
  17039. *
  17040. * @type {number}
  17041. * @default 1
  17042. */
  17043. this.near = near;
  17044. /**
  17045. * The maximum distance at which fog stops being calculated and applied.
  17046. * Objects that are more than `far` units away from the active camera won't
  17047. * be affected by fog.
  17048. *
  17049. * @type {number}
  17050. * @default 1000
  17051. */
  17052. this.far = far;
  17053. }
  17054. /**
  17055. * Returns a new fog with copied values from this instance.
  17056. *
  17057. * @return {Fog} A clone of this instance.
  17058. */
  17059. clone() {
  17060. return new Fog( this.color, this.near, this.far );
  17061. }
  17062. /**
  17063. * Serializes the fog into JSON.
  17064. *
  17065. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17066. * @return {Object} A JSON object representing the serialized fog
  17067. */
  17068. toJSON( /* meta */ ) {
  17069. return {
  17070. type: 'Fog',
  17071. name: this.name,
  17072. color: this.color.getHex(),
  17073. near: this.near,
  17074. far: this.far
  17075. };
  17076. }
  17077. }
  17078. /**
  17079. * Scenes allow you to set up what is to be rendered and where by three.js.
  17080. * This is where you place 3D objects like meshes, lines or lights.
  17081. *
  17082. * @augments Object3D
  17083. */
  17084. class Scene extends Object3D {
  17085. /**
  17086. * Constructs a new scene.
  17087. */
  17088. constructor() {
  17089. super();
  17090. /**
  17091. * This flag can be used for type testing.
  17092. *
  17093. * @type {boolean}
  17094. * @readonly
  17095. * @default true
  17096. */
  17097. this.isScene = true;
  17098. this.type = 'Scene';
  17099. /**
  17100. * Defines the background of the scene. Valid inputs are:
  17101. *
  17102. * - A color for defining a uniform colored background.
  17103. * - A texture for defining a (flat) textured background.
  17104. * - Cube textures or equirectangular textures for defining a skybox.
  17105. *
  17106. * @type {?(Color|Texture)}
  17107. * @default null
  17108. */
  17109. this.background = null;
  17110. /**
  17111. * Sets the environment map for all physical materials in the scene. However,
  17112. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17113. * material property.
  17114. *
  17115. * @type {?Texture}
  17116. * @default null
  17117. */
  17118. this.environment = null;
  17119. /**
  17120. * A fog instance defining the type of fog that affects everything
  17121. * rendered in the scene.
  17122. *
  17123. * @type {?(Fog|FogExp2)}
  17124. * @default null
  17125. */
  17126. this.fog = null;
  17127. /**
  17128. * Sets the blurriness of the background. Only influences environment maps
  17129. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17130. * and `1`.
  17131. *
  17132. * @type {number}
  17133. * @default 0
  17134. */
  17135. this.backgroundBlurriness = 0;
  17136. /**
  17137. * Attenuates the color of the background. Only applies to background textures.
  17138. *
  17139. * @type {number}
  17140. * @default 1
  17141. */
  17142. this.backgroundIntensity = 1;
  17143. /**
  17144. * The rotation of the background in radians. Only influences environment maps
  17145. * assigned to {@link Scene#background}.
  17146. *
  17147. * @type {Euler}
  17148. * @default (0,0,0)
  17149. */
  17150. this.backgroundRotation = new Euler();
  17151. /**
  17152. * Attenuates the color of the environment. Only influences environment maps
  17153. * assigned to {@link Scene#environment}.
  17154. *
  17155. * @type {number}
  17156. * @default 1
  17157. */
  17158. this.environmentIntensity = 1;
  17159. /**
  17160. * The rotation of the environment map in radians. Only influences physical materials
  17161. * in the scene when {@link Scene#environment} is used.
  17162. *
  17163. * @type {Euler}
  17164. * @default (0,0,0)
  17165. */
  17166. this.environmentRotation = new Euler();
  17167. /**
  17168. * Forces everything in the scene to be rendered with the defined material. It is possible
  17169. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17170. *
  17171. * @type {?Material}
  17172. * @default null
  17173. */
  17174. this.overrideMaterial = null;
  17175. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17176. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17177. }
  17178. }
  17179. copy( source, recursive ) {
  17180. super.copy( source, recursive );
  17181. if ( source.background !== null ) this.background = source.background.clone();
  17182. if ( source.environment !== null ) this.environment = source.environment.clone();
  17183. if ( source.fog !== null ) this.fog = source.fog.clone();
  17184. this.backgroundBlurriness = source.backgroundBlurriness;
  17185. this.backgroundIntensity = source.backgroundIntensity;
  17186. this.backgroundRotation.copy( source.backgroundRotation );
  17187. this.environmentIntensity = source.environmentIntensity;
  17188. this.environmentRotation.copy( source.environmentRotation );
  17189. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17190. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17191. return this;
  17192. }
  17193. toJSON( meta ) {
  17194. const data = super.toJSON( meta );
  17195. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17196. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17197. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17198. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17199. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17200. data.object.environmentRotation = this.environmentRotation.toArray();
  17201. return data;
  17202. }
  17203. }
  17204. /**
  17205. * "Interleaved" means that multiple attributes, possibly of different types,
  17206. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17207. *
  17208. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17209. */
  17210. class InterleavedBuffer {
  17211. /**
  17212. * Constructs a new interleaved buffer.
  17213. *
  17214. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17215. * @param {number} stride - The number of typed-array elements per vertex.
  17216. */
  17217. constructor( array, stride ) {
  17218. /**
  17219. * This flag can be used for type testing.
  17220. *
  17221. * @type {boolean}
  17222. * @readonly
  17223. * @default true
  17224. */
  17225. this.isInterleavedBuffer = true;
  17226. /**
  17227. * A typed array with a shared buffer storing attribute data.
  17228. *
  17229. * @type {TypedArray}
  17230. */
  17231. this.array = array;
  17232. /**
  17233. * The number of typed-array elements per vertex.
  17234. *
  17235. * @type {number}
  17236. */
  17237. this.stride = stride;
  17238. /**
  17239. * The total number of elements in the array
  17240. *
  17241. * @type {number}
  17242. * @readonly
  17243. */
  17244. this.count = array !== undefined ? array.length / stride : 0;
  17245. /**
  17246. * Defines the intended usage pattern of the data store for optimization purposes.
  17247. *
  17248. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17249. * instantiate a new one and set the desired usage before the next render.
  17250. *
  17251. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17252. * @default StaticDrawUsage
  17253. */
  17254. this.usage = StaticDrawUsage;
  17255. /**
  17256. * This can be used to only update some components of stored vectors (for example, just the
  17257. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17258. *
  17259. * @type {Array<Object>}
  17260. */
  17261. this.updateRanges = [];
  17262. /**
  17263. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17264. *
  17265. * @type {number}
  17266. */
  17267. this.version = 0;
  17268. /**
  17269. * The UUID of the interleaved buffer.
  17270. *
  17271. * @type {string}
  17272. * @readonly
  17273. */
  17274. this.uuid = generateUUID();
  17275. }
  17276. /**
  17277. * A callback function that is executed after the renderer has transferred the attribute array
  17278. * data to the GPU.
  17279. */
  17280. onUploadCallback() {}
  17281. /**
  17282. * Flag to indicate that this attribute has changed and should be re-sent to
  17283. * the GPU. Set this to `true` when you modify the value of the array.
  17284. *
  17285. * @type {number}
  17286. * @default false
  17287. * @param {boolean} value
  17288. */
  17289. set needsUpdate( value ) {
  17290. if ( value === true ) this.version ++;
  17291. }
  17292. /**
  17293. * Sets the usage of this interleaved buffer.
  17294. *
  17295. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17296. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17297. */
  17298. setUsage( value ) {
  17299. this.usage = value;
  17300. return this;
  17301. }
  17302. /**
  17303. * Adds a range of data in the data array to be updated on the GPU.
  17304. *
  17305. * @param {number} start - Position at which to start update.
  17306. * @param {number} count - The number of components to update.
  17307. */
  17308. addUpdateRange( start, count ) {
  17309. this.updateRanges.push( { start, count } );
  17310. }
  17311. /**
  17312. * Clears the update ranges.
  17313. */
  17314. clearUpdateRanges() {
  17315. this.updateRanges.length = 0;
  17316. }
  17317. /**
  17318. * Copies the values of the given interleaved buffer to this instance.
  17319. *
  17320. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17321. * @return {InterleavedBuffer} A reference to this instance.
  17322. */
  17323. copy( source ) {
  17324. this.array = new source.array.constructor( source.array );
  17325. this.count = source.count;
  17326. this.stride = source.stride;
  17327. this.usage = source.usage;
  17328. return this;
  17329. }
  17330. /**
  17331. * Copies a vector from the given interleaved buffer to this one. The start
  17332. * and destination position in the attribute buffers are represented by the
  17333. * given indices.
  17334. *
  17335. * @param {number} index1 - The destination index into this interleaved buffer.
  17336. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17337. * @param {number} index2 - The source index into the given interleaved buffer.
  17338. * @return {InterleavedBuffer} A reference to this instance.
  17339. */
  17340. copyAt( index1, interleavedBuffer, index2 ) {
  17341. index1 *= this.stride;
  17342. index2 *= interleavedBuffer.stride;
  17343. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17344. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17345. }
  17346. return this;
  17347. }
  17348. /**
  17349. * Sets the given array data in the interleaved buffer.
  17350. *
  17351. * @param {(TypedArray|Array)} value - The array data to set.
  17352. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17353. * @return {InterleavedBuffer} A reference to this instance.
  17354. */
  17355. set( value, offset = 0 ) {
  17356. this.array.set( value, offset );
  17357. return this;
  17358. }
  17359. /**
  17360. * Returns a new interleaved buffer with copied values from this instance.
  17361. *
  17362. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17363. * @return {InterleavedBuffer} A clone of this instance.
  17364. */
  17365. clone( data ) {
  17366. if ( data.arrayBuffers === undefined ) {
  17367. data.arrayBuffers = {};
  17368. }
  17369. if ( this.array.buffer._uuid === undefined ) {
  17370. this.array.buffer._uuid = generateUUID();
  17371. }
  17372. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17373. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17374. }
  17375. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17376. const ib = new this.constructor( array, this.stride );
  17377. ib.setUsage( this.usage );
  17378. return ib;
  17379. }
  17380. /**
  17381. * Sets the given callback function that is executed after the Renderer has transferred
  17382. * the array data to the GPU. Can be used to perform clean-up operations after
  17383. * the upload when data are not needed anymore on the CPU side.
  17384. *
  17385. * @param {Function} callback - The `onUpload()` callback.
  17386. * @return {InterleavedBuffer} A reference to this instance.
  17387. */
  17388. onUpload( callback ) {
  17389. this.onUploadCallback = callback;
  17390. return this;
  17391. }
  17392. /**
  17393. * Serializes the interleaved buffer into JSON.
  17394. *
  17395. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17396. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17397. */
  17398. toJSON( data ) {
  17399. if ( data.arrayBuffers === undefined ) {
  17400. data.arrayBuffers = {};
  17401. }
  17402. // generate UUID for array buffer if necessary
  17403. if ( this.array.buffer._uuid === undefined ) {
  17404. this.array.buffer._uuid = generateUUID();
  17405. }
  17406. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17407. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17408. }
  17409. //
  17410. return {
  17411. uuid: this.uuid,
  17412. buffer: this.array.buffer._uuid,
  17413. type: this.array.constructor.name,
  17414. stride: this.stride
  17415. };
  17416. }
  17417. }
  17418. const _vector$7 = /*@__PURE__*/ new Vector3();
  17419. /**
  17420. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17421. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17422. * different offsets into the buffer.
  17423. */
  17424. class InterleavedBufferAttribute {
  17425. /**
  17426. * Constructs a new interleaved buffer attribute.
  17427. *
  17428. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17429. * @param {number} itemSize - The item size.
  17430. * @param {number} offset - The attribute offset into the buffer.
  17431. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17432. */
  17433. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17434. /**
  17435. * This flag can be used for type testing.
  17436. *
  17437. * @type {boolean}
  17438. * @readonly
  17439. * @default true
  17440. */
  17441. this.isInterleavedBufferAttribute = true;
  17442. /**
  17443. * The name of the buffer attribute.
  17444. *
  17445. * @type {string}
  17446. */
  17447. this.name = '';
  17448. /**
  17449. * The buffer holding the interleaved data.
  17450. *
  17451. * @type {InterleavedBuffer}
  17452. */
  17453. this.data = interleavedBuffer;
  17454. /**
  17455. * The item size, see {@link BufferAttribute#itemSize}.
  17456. *
  17457. * @type {number}
  17458. */
  17459. this.itemSize = itemSize;
  17460. /**
  17461. * The attribute offset into the buffer.
  17462. *
  17463. * @type {number}
  17464. */
  17465. this.offset = offset;
  17466. /**
  17467. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17468. *
  17469. * @type {InterleavedBuffer}
  17470. */
  17471. this.normalized = normalized;
  17472. }
  17473. /**
  17474. * The item count of this buffer attribute.
  17475. *
  17476. * @type {number}
  17477. * @readonly
  17478. */
  17479. get count() {
  17480. return this.data.count;
  17481. }
  17482. /**
  17483. * The array holding the interleaved buffer attribute data.
  17484. *
  17485. * @type {TypedArray}
  17486. */
  17487. get array() {
  17488. return this.data.array;
  17489. }
  17490. /**
  17491. * Flag to indicate that this attribute has changed and should be re-sent to
  17492. * the GPU. Set this to `true` when you modify the value of the array.
  17493. *
  17494. * @type {number}
  17495. * @default false
  17496. * @param {boolean} value
  17497. */
  17498. set needsUpdate( value ) {
  17499. this.data.needsUpdate = value;
  17500. }
  17501. /**
  17502. * Applies the given 4x4 matrix to the given attribute. Only works with
  17503. * item size `3`.
  17504. *
  17505. * @param {Matrix4} m - The matrix to apply.
  17506. * @return {InterleavedBufferAttribute} A reference to this instance.
  17507. */
  17508. applyMatrix4( m ) {
  17509. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17510. _vector$7.fromBufferAttribute( this, i );
  17511. _vector$7.applyMatrix4( m );
  17512. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17513. }
  17514. return this;
  17515. }
  17516. /**
  17517. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17518. * item size `3`.
  17519. *
  17520. * @param {Matrix3} m - The normal matrix to apply.
  17521. * @return {InterleavedBufferAttribute} A reference to this instance.
  17522. */
  17523. applyNormalMatrix( m ) {
  17524. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17525. _vector$7.fromBufferAttribute( this, i );
  17526. _vector$7.applyNormalMatrix( m );
  17527. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17528. }
  17529. return this;
  17530. }
  17531. /**
  17532. * Applies the given 4x4 matrix to the given attribute. Only works with
  17533. * item size `3` and with direction vectors.
  17534. *
  17535. * @param {Matrix4} m - The matrix to apply.
  17536. * @return {InterleavedBufferAttribute} A reference to this instance.
  17537. */
  17538. transformDirection( m ) {
  17539. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17540. _vector$7.fromBufferAttribute( this, i );
  17541. _vector$7.transformDirection( m );
  17542. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17543. }
  17544. return this;
  17545. }
  17546. /**
  17547. * Returns the given component of the vector at the given index.
  17548. *
  17549. * @param {number} index - The index into the buffer attribute.
  17550. * @param {number} component - The component index.
  17551. * @return {number} The returned value.
  17552. */
  17553. getComponent( index, component ) {
  17554. let value = this.array[ index * this.data.stride + this.offset + component ];
  17555. if ( this.normalized ) value = denormalize( value, this.array );
  17556. return value;
  17557. }
  17558. /**
  17559. * Sets the given value to the given component of the vector at the given index.
  17560. *
  17561. * @param {number} index - The index into the buffer attribute.
  17562. * @param {number} component - The component index.
  17563. * @param {number} value - The value to set.
  17564. * @return {InterleavedBufferAttribute} A reference to this instance.
  17565. */
  17566. setComponent( index, component, value ) {
  17567. if ( this.normalized ) value = normalize( value, this.array );
  17568. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17569. return this;
  17570. }
  17571. /**
  17572. * Sets the x component of the vector at the given index.
  17573. *
  17574. * @param {number} index - The index into the buffer attribute.
  17575. * @param {number} x - The value to set.
  17576. * @return {InterleavedBufferAttribute} A reference to this instance.
  17577. */
  17578. setX( index, x ) {
  17579. if ( this.normalized ) x = normalize( x, this.array );
  17580. this.data.array[ index * this.data.stride + this.offset ] = x;
  17581. return this;
  17582. }
  17583. /**
  17584. * Sets the y component of the vector at the given index.
  17585. *
  17586. * @param {number} index - The index into the buffer attribute.
  17587. * @param {number} y - The value to set.
  17588. * @return {InterleavedBufferAttribute} A reference to this instance.
  17589. */
  17590. setY( index, y ) {
  17591. if ( this.normalized ) y = normalize( y, this.array );
  17592. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17593. return this;
  17594. }
  17595. /**
  17596. * Sets the z component of the vector at the given index.
  17597. *
  17598. * @param {number} index - The index into the buffer attribute.
  17599. * @param {number} z - The value to set.
  17600. * @return {InterleavedBufferAttribute} A reference to this instance.
  17601. */
  17602. setZ( index, z ) {
  17603. if ( this.normalized ) z = normalize( z, this.array );
  17604. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17605. return this;
  17606. }
  17607. /**
  17608. * Sets the w component of the vector at the given index.
  17609. *
  17610. * @param {number} index - The index into the buffer attribute.
  17611. * @param {number} w - The value to set.
  17612. * @return {InterleavedBufferAttribute} A reference to this instance.
  17613. */
  17614. setW( index, w ) {
  17615. if ( this.normalized ) w = normalize( w, this.array );
  17616. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17617. return this;
  17618. }
  17619. /**
  17620. * Returns the x component of the vector at the given index.
  17621. *
  17622. * @param {number} index - The index into the buffer attribute.
  17623. * @return {number} The x component.
  17624. */
  17625. getX( index ) {
  17626. let x = this.data.array[ index * this.data.stride + this.offset ];
  17627. if ( this.normalized ) x = denormalize( x, this.array );
  17628. return x;
  17629. }
  17630. /**
  17631. * Returns the y component of the vector at the given index.
  17632. *
  17633. * @param {number} index - The index into the buffer attribute.
  17634. * @return {number} The y component.
  17635. */
  17636. getY( index ) {
  17637. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17638. if ( this.normalized ) y = denormalize( y, this.array );
  17639. return y;
  17640. }
  17641. /**
  17642. * Returns the z component of the vector at the given index.
  17643. *
  17644. * @param {number} index - The index into the buffer attribute.
  17645. * @return {number} The z component.
  17646. */
  17647. getZ( index ) {
  17648. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17649. if ( this.normalized ) z = denormalize( z, this.array );
  17650. return z;
  17651. }
  17652. /**
  17653. * Returns the w component of the vector at the given index.
  17654. *
  17655. * @param {number} index - The index into the buffer attribute.
  17656. * @return {number} The w component.
  17657. */
  17658. getW( index ) {
  17659. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17660. if ( this.normalized ) w = denormalize( w, this.array );
  17661. return w;
  17662. }
  17663. /**
  17664. * Sets the x and y component of the vector at the given index.
  17665. *
  17666. * @param {number} index - The index into the buffer attribute.
  17667. * @param {number} x - The value for the x component to set.
  17668. * @param {number} y - The value for the y component to set.
  17669. * @return {InterleavedBufferAttribute} A reference to this instance.
  17670. */
  17671. setXY( index, x, y ) {
  17672. index = index * this.data.stride + this.offset;
  17673. if ( this.normalized ) {
  17674. x = normalize( x, this.array );
  17675. y = normalize( y, this.array );
  17676. }
  17677. this.data.array[ index + 0 ] = x;
  17678. this.data.array[ index + 1 ] = y;
  17679. return this;
  17680. }
  17681. /**
  17682. * Sets the x, y and z component of the vector at the given index.
  17683. *
  17684. * @param {number} index - The index into the buffer attribute.
  17685. * @param {number} x - The value for the x component to set.
  17686. * @param {number} y - The value for the y component to set.
  17687. * @param {number} z - The value for the z component to set.
  17688. * @return {InterleavedBufferAttribute} A reference to this instance.
  17689. */
  17690. setXYZ( index, x, y, z ) {
  17691. index = index * this.data.stride + this.offset;
  17692. if ( this.normalized ) {
  17693. x = normalize( x, this.array );
  17694. y = normalize( y, this.array );
  17695. z = normalize( z, this.array );
  17696. }
  17697. this.data.array[ index + 0 ] = x;
  17698. this.data.array[ index + 1 ] = y;
  17699. this.data.array[ index + 2 ] = z;
  17700. return this;
  17701. }
  17702. /**
  17703. * Sets the x, y, z and w component of the vector at the given index.
  17704. *
  17705. * @param {number} index - The index into the buffer attribute.
  17706. * @param {number} x - The value for the x component to set.
  17707. * @param {number} y - The value for the y component to set.
  17708. * @param {number} z - The value for the z component to set.
  17709. * @param {number} w - The value for the w component to set.
  17710. * @return {InterleavedBufferAttribute} A reference to this instance.
  17711. */
  17712. setXYZW( index, x, y, z, w ) {
  17713. index = index * this.data.stride + this.offset;
  17714. if ( this.normalized ) {
  17715. x = normalize( x, this.array );
  17716. y = normalize( y, this.array );
  17717. z = normalize( z, this.array );
  17718. w = normalize( w, this.array );
  17719. }
  17720. this.data.array[ index + 0 ] = x;
  17721. this.data.array[ index + 1 ] = y;
  17722. this.data.array[ index + 2 ] = z;
  17723. this.data.array[ index + 3 ] = w;
  17724. return this;
  17725. }
  17726. /**
  17727. * Returns a new buffer attribute with copied values from this instance.
  17728. *
  17729. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17730. *
  17731. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17732. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17733. */
  17734. clone( data ) {
  17735. if ( data === undefined ) {
  17736. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17737. const array = [];
  17738. for ( let i = 0; i < this.count; i ++ ) {
  17739. const index = i * this.data.stride + this.offset;
  17740. for ( let j = 0; j < this.itemSize; j ++ ) {
  17741. array.push( this.data.array[ index + j ] );
  17742. }
  17743. }
  17744. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17745. } else {
  17746. if ( data.interleavedBuffers === undefined ) {
  17747. data.interleavedBuffers = {};
  17748. }
  17749. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17750. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17751. }
  17752. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17753. }
  17754. }
  17755. /**
  17756. * Serializes the buffer attribute into JSON.
  17757. *
  17758. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17759. *
  17760. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17761. * @return {Object} A JSON object representing the serialized buffer attribute.
  17762. */
  17763. toJSON( data ) {
  17764. if ( data === undefined ) {
  17765. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17766. const array = [];
  17767. for ( let i = 0; i < this.count; i ++ ) {
  17768. const index = i * this.data.stride + this.offset;
  17769. for ( let j = 0; j < this.itemSize; j ++ ) {
  17770. array.push( this.data.array[ index + j ] );
  17771. }
  17772. }
  17773. // de-interleave data and save it as an ordinary buffer attribute for now
  17774. return {
  17775. itemSize: this.itemSize,
  17776. type: this.array.constructor.name,
  17777. array: array,
  17778. normalized: this.normalized
  17779. };
  17780. } else {
  17781. // save as true interleaved attribute
  17782. if ( data.interleavedBuffers === undefined ) {
  17783. data.interleavedBuffers = {};
  17784. }
  17785. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17786. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17787. }
  17788. return {
  17789. isInterleavedBufferAttribute: true,
  17790. itemSize: this.itemSize,
  17791. data: this.data.uuid,
  17792. offset: this.offset,
  17793. normalized: this.normalized
  17794. };
  17795. }
  17796. }
  17797. }
  17798. /**
  17799. * A material for rendering instances of {@link Sprite}.
  17800. *
  17801. * ```js
  17802. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17803. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17804. *
  17805. * const sprite = new THREE.Sprite( material );
  17806. * sprite.scale.set(200, 200, 1)
  17807. * scene.add( sprite );
  17808. * ```
  17809. *
  17810. * @augments Material
  17811. */
  17812. class SpriteMaterial extends Material {
  17813. /**
  17814. * Constructs a new sprite material.
  17815. *
  17816. * @param {Object} [parameters] - An object with one or more properties
  17817. * defining the material's appearance. Any property of the material
  17818. * (including any property from inherited materials) can be passed
  17819. * in here. Color values can be passed any type of value accepted
  17820. * by {@link Color#set}.
  17821. */
  17822. constructor( parameters ) {
  17823. super();
  17824. /**
  17825. * This flag can be used for type testing.
  17826. *
  17827. * @type {boolean}
  17828. * @readonly
  17829. * @default true
  17830. */
  17831. this.isSpriteMaterial = true;
  17832. this.type = 'SpriteMaterial';
  17833. /**
  17834. * Color of the material.
  17835. *
  17836. * @type {Color}
  17837. * @default (1,1,1)
  17838. */
  17839. this.color = new Color( 0xffffff );
  17840. /**
  17841. * The color map. May optionally include an alpha channel, typically combined
  17842. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17843. * color is modulated by the diffuse `color`.
  17844. *
  17845. * @type {?Texture}
  17846. * @default null
  17847. */
  17848. this.map = null;
  17849. /**
  17850. * The alpha map is a grayscale texture that controls the opacity across the
  17851. * surface (black: fully transparent; white: fully opaque).
  17852. *
  17853. * Only the color of the texture is used, ignoring the alpha channel if one
  17854. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17855. * when sampling this texture due to the extra bit of precision provided for
  17856. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17857. * luminance/alpha textures will also still work as expected.
  17858. *
  17859. * @type {?Texture}
  17860. * @default null
  17861. */
  17862. this.alphaMap = null;
  17863. /**
  17864. * The rotation of the sprite in radians.
  17865. *
  17866. * @type {number}
  17867. * @default 0
  17868. */
  17869. this.rotation = 0;
  17870. /**
  17871. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17872. *
  17873. * @type {boolean}
  17874. * @default true
  17875. */
  17876. this.sizeAttenuation = true;
  17877. /**
  17878. * Overwritten since sprite materials are transparent
  17879. * by default.
  17880. *
  17881. * @type {boolean}
  17882. * @default true
  17883. */
  17884. this.transparent = true;
  17885. /**
  17886. * Whether the material is affected by fog or not.
  17887. *
  17888. * @type {boolean}
  17889. * @default true
  17890. */
  17891. this.fog = true;
  17892. this.setValues( parameters );
  17893. }
  17894. copy( source ) {
  17895. super.copy( source );
  17896. this.color.copy( source.color );
  17897. this.map = source.map;
  17898. this.alphaMap = source.alphaMap;
  17899. this.rotation = source.rotation;
  17900. this.sizeAttenuation = source.sizeAttenuation;
  17901. this.fog = source.fog;
  17902. return this;
  17903. }
  17904. }
  17905. let _geometry;
  17906. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17907. const _worldScale = /*@__PURE__*/ new Vector3();
  17908. const _mvPosition = /*@__PURE__*/ new Vector3();
  17909. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17910. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17911. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17912. const _vA = /*@__PURE__*/ new Vector3();
  17913. const _vB = /*@__PURE__*/ new Vector3();
  17914. const _vC = /*@__PURE__*/ new Vector3();
  17915. const _uvA = /*@__PURE__*/ new Vector2();
  17916. const _uvB = /*@__PURE__*/ new Vector2();
  17917. const _uvC = /*@__PURE__*/ new Vector2();
  17918. /**
  17919. * A sprite is a plane that always faces towards the camera, generally with a
  17920. * partially transparent texture applied.
  17921. *
  17922. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17923. * have no effect.
  17924. *
  17925. * ```js
  17926. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17927. * const material = new THREE.SpriteMaterial( { map: map } );
  17928. *
  17929. * const sprite = new THREE.Sprite( material );
  17930. * scene.add( sprite );
  17931. * ```
  17932. *
  17933. * @augments Object3D
  17934. */
  17935. class Sprite extends Object3D {
  17936. /**
  17937. * Constructs a new sprite.
  17938. *
  17939. * @param {SpriteMaterial} [material] - The sprite material.
  17940. */
  17941. constructor( material = new SpriteMaterial() ) {
  17942. super();
  17943. /**
  17944. * This flag can be used for type testing.
  17945. *
  17946. * @type {boolean}
  17947. * @readonly
  17948. * @default true
  17949. */
  17950. this.isSprite = true;
  17951. this.type = 'Sprite';
  17952. if ( _geometry === undefined ) {
  17953. _geometry = new BufferGeometry();
  17954. const float32Array = new Float32Array( [
  17955. -0.5, -0.5, 0, 0, 0,
  17956. 0.5, -0.5, 0, 1, 0,
  17957. 0.5, 0.5, 0, 1, 1,
  17958. -0.5, 0.5, 0, 0, 1
  17959. ] );
  17960. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17961. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17962. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17963. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17964. }
  17965. /**
  17966. * The sprite geometry.
  17967. *
  17968. * @type {BufferGeometry}
  17969. */
  17970. this.geometry = _geometry;
  17971. /**
  17972. * The sprite material.
  17973. *
  17974. * @type {SpriteMaterial}
  17975. */
  17976. this.material = material;
  17977. /**
  17978. * The sprite's anchor point, and the point around which the sprite rotates.
  17979. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17980. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17981. *
  17982. * @type {Vector2}
  17983. * @default (0.5,0.5)
  17984. */
  17985. this.center = new Vector2( 0.5, 0.5 );
  17986. /**
  17987. * The number of instances of this sprite.
  17988. * Can only be used with {@link WebGPURenderer}.
  17989. *
  17990. * @type {number}
  17991. * @default 1
  17992. */
  17993. this.count = 1;
  17994. }
  17995. /**
  17996. * Computes intersection points between a casted ray and this sprite.
  17997. *
  17998. * @param {Raycaster} raycaster - The raycaster.
  17999. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18000. */
  18001. raycast( raycaster, intersects ) {
  18002. if ( raycaster.camera === null ) {
  18003. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18004. }
  18005. _worldScale.setFromMatrixScale( this.matrixWorld );
  18006. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18007. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18008. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18009. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18010. _worldScale.multiplyScalar( - _mvPosition.z );
  18011. }
  18012. const rotation = this.material.rotation;
  18013. let sin, cos;
  18014. if ( rotation !== 0 ) {
  18015. cos = Math.cos( rotation );
  18016. sin = Math.sin( rotation );
  18017. }
  18018. const center = this.center;
  18019. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18020. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18021. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18022. _uvA.set( 0, 0 );
  18023. _uvB.set( 1, 0 );
  18024. _uvC.set( 1, 1 );
  18025. // check first triangle
  18026. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18027. if ( intersect === null ) {
  18028. // check second triangle
  18029. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18030. _uvB.set( 0, 1 );
  18031. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18032. if ( intersect === null ) {
  18033. return;
  18034. }
  18035. }
  18036. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18037. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18038. intersects.push( {
  18039. distance: distance,
  18040. point: _intersectPoint.clone(),
  18041. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18042. face: null,
  18043. object: this
  18044. } );
  18045. }
  18046. copy( source, recursive ) {
  18047. super.copy( source, recursive );
  18048. if ( source.center !== undefined ) this.center.copy( source.center );
  18049. this.material = source.material;
  18050. return this;
  18051. }
  18052. }
  18053. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18054. // compute position in camera space
  18055. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18056. // to check if rotation is not zero
  18057. if ( sin !== undefined ) {
  18058. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18059. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18060. } else {
  18061. _rotatedPosition.copy( _alignedPosition );
  18062. }
  18063. vertexPosition.copy( mvPosition );
  18064. vertexPosition.x += _rotatedPosition.x;
  18065. vertexPosition.y += _rotatedPosition.y;
  18066. // transform to world space
  18067. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18068. }
  18069. const _v1$2 = /*@__PURE__*/ new Vector3();
  18070. const _v2$1 = /*@__PURE__*/ new Vector3();
  18071. /**
  18072. * A component for providing a basic Level of Detail (LOD) mechanism.
  18073. *
  18074. * Every LOD level is associated with an object, and rendering can be switched
  18075. * between them at the distances specified. Typically you would create, say,
  18076. * three meshes, one for far away (low detail), one for mid range (medium
  18077. * detail) and one for close up (high detail).
  18078. *
  18079. * ```js
  18080. * const lod = new THREE.LOD();
  18081. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18082. *
  18083. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18084. * for( let i = 0; i < 3; i++ ) {
  18085. *
  18086. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18087. * const mesh = new THREE.Mesh( geometry, material );
  18088. * lod.addLevel( mesh, i * 75 );
  18089. *
  18090. * }
  18091. *
  18092. * scene.add( lod );
  18093. * ```
  18094. *
  18095. * @augments Object3D
  18096. */
  18097. class LOD extends Object3D {
  18098. /**
  18099. * Constructs a new LOD.
  18100. */
  18101. constructor() {
  18102. super();
  18103. /**
  18104. * This flag can be used for type testing.
  18105. *
  18106. * @type {boolean}
  18107. * @readonly
  18108. * @default true
  18109. */
  18110. this.isLOD = true;
  18111. /**
  18112. * The current LOD index.
  18113. *
  18114. * @private
  18115. * @type {number}
  18116. * @default 0
  18117. */
  18118. this._currentLevel = 0;
  18119. this.type = 'LOD';
  18120. Object.defineProperties( this, {
  18121. /**
  18122. * This array holds the LOD levels.
  18123. *
  18124. * @name LOD#levels
  18125. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18126. */
  18127. levels: {
  18128. enumerable: true,
  18129. value: []
  18130. }
  18131. } );
  18132. /**
  18133. * Whether the LOD object is updated automatically by the renderer per frame
  18134. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18135. * render loop by yourself.
  18136. *
  18137. * @type {boolean}
  18138. * @default true
  18139. */
  18140. this.autoUpdate = true;
  18141. }
  18142. copy( source ) {
  18143. super.copy( source, false );
  18144. const levels = source.levels;
  18145. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18146. const level = levels[ i ];
  18147. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18148. }
  18149. this.autoUpdate = source.autoUpdate;
  18150. return this;
  18151. }
  18152. /**
  18153. * Adds a mesh that will display at a certain distance and greater. Typically
  18154. * the further away the distance, the lower the detail on the mesh.
  18155. *
  18156. * @param {Object3D} object - The 3D object to display at this level.
  18157. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18158. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18159. * @return {LOD} A reference to this instance.
  18160. */
  18161. addLevel( object, distance = 0, hysteresis = 0 ) {
  18162. distance = Math.abs( distance );
  18163. const levels = this.levels;
  18164. let l;
  18165. for ( l = 0; l < levels.length; l ++ ) {
  18166. if ( distance < levels[ l ].distance ) {
  18167. break;
  18168. }
  18169. }
  18170. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18171. this.add( object );
  18172. return this;
  18173. }
  18174. /**
  18175. * Removes an existing level, based on the distance from the camera.
  18176. * Returns `true` when the level has been removed. Otherwise `false`.
  18177. *
  18178. * @param {number} distance - Distance of the level to remove.
  18179. * @return {boolean} Whether the level has been removed or not.
  18180. */
  18181. removeLevel( distance ) {
  18182. const levels = this.levels;
  18183. for ( let i = 0; i < levels.length; i ++ ) {
  18184. if ( levels[ i ].distance === distance ) {
  18185. const removedElements = levels.splice( i, 1 );
  18186. this.remove( removedElements[ 0 ].object );
  18187. return true;
  18188. }
  18189. }
  18190. return false;
  18191. }
  18192. /**
  18193. * Returns the currently active LOD level index.
  18194. *
  18195. * @return {number} The current active LOD level index.
  18196. */
  18197. getCurrentLevel() {
  18198. return this._currentLevel;
  18199. }
  18200. /**
  18201. * Returns a reference to the first 3D object that is greater than
  18202. * the given distance.
  18203. *
  18204. * @param {number} distance - The LOD distance.
  18205. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18206. */
  18207. getObjectForDistance( distance ) {
  18208. const levels = this.levels;
  18209. if ( levels.length > 0 ) {
  18210. let i, l;
  18211. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18212. let levelDistance = levels[ i ].distance;
  18213. if ( levels[ i ].object.visible ) {
  18214. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18215. }
  18216. if ( distance < levelDistance ) {
  18217. break;
  18218. }
  18219. }
  18220. return levels[ i - 1 ].object;
  18221. }
  18222. return null;
  18223. }
  18224. /**
  18225. * Computes intersection points between a casted ray and this LOD.
  18226. *
  18227. * @param {Raycaster} raycaster - The raycaster.
  18228. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18229. */
  18230. raycast( raycaster, intersects ) {
  18231. const levels = this.levels;
  18232. if ( levels.length > 0 ) {
  18233. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18234. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18235. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18236. }
  18237. }
  18238. /**
  18239. * Updates the LOD by computing which LOD level should be visible according
  18240. * to the current distance of the given camera.
  18241. *
  18242. * @param {Camera} camera - The camera the scene is rendered with.
  18243. */
  18244. update( camera ) {
  18245. const levels = this.levels;
  18246. if ( levels.length > 1 ) {
  18247. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18248. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18249. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18250. levels[ 0 ].object.visible = true;
  18251. let i, l;
  18252. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18253. let levelDistance = levels[ i ].distance;
  18254. if ( levels[ i ].object.visible ) {
  18255. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18256. }
  18257. if ( distance >= levelDistance ) {
  18258. levels[ i - 1 ].object.visible = false;
  18259. levels[ i ].object.visible = true;
  18260. } else {
  18261. break;
  18262. }
  18263. }
  18264. this._currentLevel = i - 1;
  18265. for ( ; i < l; i ++ ) {
  18266. levels[ i ].object.visible = false;
  18267. }
  18268. }
  18269. }
  18270. toJSON( meta ) {
  18271. const data = super.toJSON( meta );
  18272. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18273. data.object.levels = [];
  18274. const levels = this.levels;
  18275. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18276. const level = levels[ i ];
  18277. data.object.levels.push( {
  18278. object: level.object.uuid,
  18279. distance: level.distance,
  18280. hysteresis: level.hysteresis
  18281. } );
  18282. }
  18283. return data;
  18284. }
  18285. }
  18286. const _basePosition = /*@__PURE__*/ new Vector3();
  18287. const _skinIndex = /*@__PURE__*/ new Vector4();
  18288. const _skinWeight = /*@__PURE__*/ new Vector4();
  18289. const _vector3 = /*@__PURE__*/ new Vector3();
  18290. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18291. const _vertex = /*@__PURE__*/ new Vector3();
  18292. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18293. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18294. const _ray$2 = /*@__PURE__*/ new Ray();
  18295. /**
  18296. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18297. * vertices of the geometry with skinning/skeleton animation.
  18298. *
  18299. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18300. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18301. * vertex to a certain extend.
  18302. *
  18303. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18304. * or {@link FBXLoader } import respective models.
  18305. *
  18306. * @augments Mesh
  18307. */
  18308. class SkinnedMesh extends Mesh {
  18309. /**
  18310. * Constructs a new skinned mesh.
  18311. *
  18312. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18313. * @param {Material|Array<Material>} [material] - The mesh material.
  18314. */
  18315. constructor( geometry, material ) {
  18316. super( geometry, material );
  18317. /**
  18318. * This flag can be used for type testing.
  18319. *
  18320. * @type {boolean}
  18321. * @readonly
  18322. * @default true
  18323. */
  18324. this.isSkinnedMesh = true;
  18325. this.type = 'SkinnedMesh';
  18326. /**
  18327. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18328. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18329. * across multiple skinned meshes.
  18330. *
  18331. * @type {(AttachedBindMode|DetachedBindMode)}
  18332. * @default AttachedBindMode
  18333. */
  18334. this.bindMode = AttachedBindMode;
  18335. /**
  18336. * The base matrix that is used for the bound bone transforms.
  18337. *
  18338. * @type {Matrix4}
  18339. */
  18340. this.bindMatrix = new Matrix4();
  18341. /**
  18342. * The base matrix that is used for resetting the bound bone transforms.
  18343. *
  18344. * @type {Matrix4}
  18345. */
  18346. this.bindMatrixInverse = new Matrix4();
  18347. /**
  18348. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18349. *
  18350. * @type {?Box3}
  18351. * @default null
  18352. */
  18353. this.boundingBox = null;
  18354. /**
  18355. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18356. *
  18357. * @type {?Sphere}
  18358. * @default null
  18359. */
  18360. this.boundingSphere = null;
  18361. }
  18362. /**
  18363. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18364. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18365. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18366. * the current animation state.
  18367. */
  18368. computeBoundingBox() {
  18369. const geometry = this.geometry;
  18370. if ( this.boundingBox === null ) {
  18371. this.boundingBox = new Box3();
  18372. }
  18373. this.boundingBox.makeEmpty();
  18374. const positionAttribute = geometry.getAttribute( 'position' );
  18375. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18376. this.getVertexPosition( i, _vertex );
  18377. this.boundingBox.expandByPoint( _vertex );
  18378. }
  18379. }
  18380. /**
  18381. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18382. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18383. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18384. * per frame in order to reflect the current animation state.
  18385. */
  18386. computeBoundingSphere() {
  18387. const geometry = this.geometry;
  18388. if ( this.boundingSphere === null ) {
  18389. this.boundingSphere = new Sphere();
  18390. }
  18391. this.boundingSphere.makeEmpty();
  18392. const positionAttribute = geometry.getAttribute( 'position' );
  18393. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18394. this.getVertexPosition( i, _vertex );
  18395. this.boundingSphere.expandByPoint( _vertex );
  18396. }
  18397. }
  18398. copy( source, recursive ) {
  18399. super.copy( source, recursive );
  18400. this.bindMode = source.bindMode;
  18401. this.bindMatrix.copy( source.bindMatrix );
  18402. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18403. this.skeleton = source.skeleton;
  18404. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18405. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18406. return this;
  18407. }
  18408. raycast( raycaster, intersects ) {
  18409. const material = this.material;
  18410. const matrixWorld = this.matrixWorld;
  18411. if ( material === undefined ) return;
  18412. // test with bounding sphere in world space
  18413. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18414. _sphere$5.copy( this.boundingSphere );
  18415. _sphere$5.applyMatrix4( matrixWorld );
  18416. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18417. // convert ray to local space of skinned mesh
  18418. _inverseMatrix$2.copy( matrixWorld ).invert();
  18419. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18420. // test with bounding box in local space
  18421. if ( this.boundingBox !== null ) {
  18422. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18423. }
  18424. // test for intersections with geometry
  18425. this._computeIntersections( raycaster, intersects, _ray$2 );
  18426. }
  18427. getVertexPosition( index, target ) {
  18428. super.getVertexPosition( index, target );
  18429. this.applyBoneTransform( index, target );
  18430. return target;
  18431. }
  18432. /**
  18433. * Binds the given skeleton to the skinned mesh.
  18434. *
  18435. * @param {Skeleton} skeleton - The skeleton to bind.
  18436. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18437. * the skinned mesh's world matrix will be used instead.
  18438. */
  18439. bind( skeleton, bindMatrix ) {
  18440. this.skeleton = skeleton;
  18441. if ( bindMatrix === undefined ) {
  18442. this.updateMatrixWorld( true );
  18443. this.skeleton.calculateInverses();
  18444. bindMatrix = this.matrixWorld;
  18445. }
  18446. this.bindMatrix.copy( bindMatrix );
  18447. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18448. }
  18449. /**
  18450. * This method sets the skinned mesh in the rest pose).
  18451. */
  18452. pose() {
  18453. this.skeleton.pose();
  18454. }
  18455. /**
  18456. * Normalizes the skin weights which are defined as a buffer attribute
  18457. * in the skinned mesh's geometry.
  18458. */
  18459. normalizeSkinWeights() {
  18460. const vector = new Vector4();
  18461. const skinWeight = this.geometry.attributes.skinWeight;
  18462. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18463. vector.fromBufferAttribute( skinWeight, i );
  18464. const scale = 1.0 / vector.manhattanLength();
  18465. if ( scale !== Infinity ) {
  18466. vector.multiplyScalar( scale );
  18467. } else {
  18468. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18469. }
  18470. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18471. }
  18472. }
  18473. updateMatrixWorld( force ) {
  18474. super.updateMatrixWorld( force );
  18475. if ( this.bindMode === AttachedBindMode ) {
  18476. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18477. } else if ( this.bindMode === DetachedBindMode ) {
  18478. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18479. } else {
  18480. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18481. }
  18482. }
  18483. /**
  18484. * Applies the bone transform associated with the given index to the given
  18485. * vertex position. Returns the updated vector.
  18486. *
  18487. * @param {number} index - The vertex index.
  18488. * @param {Vector3} target - The target object that is used to store the method's result.
  18489. * the skinned mesh's world matrix will be used instead.
  18490. * @return {Vector3} The updated vertex position.
  18491. */
  18492. applyBoneTransform( index, target ) {
  18493. const skeleton = this.skeleton;
  18494. const geometry = this.geometry;
  18495. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18496. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18497. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18498. target.set( 0, 0, 0 );
  18499. for ( let i = 0; i < 4; i ++ ) {
  18500. const weight = _skinWeight.getComponent( i );
  18501. if ( weight !== 0 ) {
  18502. const boneIndex = _skinIndex.getComponent( i );
  18503. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18504. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18505. }
  18506. }
  18507. return target.applyMatrix4( this.bindMatrixInverse );
  18508. }
  18509. }
  18510. /**
  18511. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18512. * the {@link SkinnedMesh}.
  18513. *
  18514. * ```js
  18515. * const root = new THREE.Bone();
  18516. * const child = new THREE.Bone();
  18517. *
  18518. * root.add( child );
  18519. * child.position.y = 5;
  18520. * ```
  18521. *
  18522. * @augments Object3D
  18523. */
  18524. class Bone extends Object3D {
  18525. /**
  18526. * Constructs a new bone.
  18527. */
  18528. constructor() {
  18529. super();
  18530. /**
  18531. * This flag can be used for type testing.
  18532. *
  18533. * @type {boolean}
  18534. * @readonly
  18535. * @default true
  18536. */
  18537. this.isBone = true;
  18538. this.type = 'Bone';
  18539. }
  18540. }
  18541. /**
  18542. * Creates a texture directly from raw buffer data.
  18543. *
  18544. * The interpretation of the data depends on type and format: If the type is
  18545. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18546. * texel data. If the format is `RGBAFormat`, data needs four values for
  18547. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18548. *
  18549. * @augments Texture
  18550. */
  18551. class DataTexture extends Texture {
  18552. /**
  18553. * Constructs a new data texture.
  18554. *
  18555. * @param {?TypedArray} [data=null] - The buffer data.
  18556. * @param {number} [width=1] - The width of the texture.
  18557. * @param {number} [height=1] - The height of the texture.
  18558. * @param {number} [format=RGBAFormat] - The texture format.
  18559. * @param {number} [type=UnsignedByteType] - The texture type.
  18560. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18561. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18562. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18563. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18564. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18565. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18566. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18567. */
  18568. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18569. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18570. /**
  18571. * This flag can be used for type testing.
  18572. *
  18573. * @type {boolean}
  18574. * @readonly
  18575. * @default true
  18576. */
  18577. this.isDataTexture = true;
  18578. /**
  18579. * The image definition of a data texture.
  18580. *
  18581. * @type {{data:TypedArray,width:number,height:number}}
  18582. */
  18583. this.image = { data: data, width: width, height: height };
  18584. /**
  18585. * Whether to generate mipmaps (if possible) for a texture.
  18586. *
  18587. * Overwritten and set to `false` by default.
  18588. *
  18589. * @type {boolean}
  18590. * @default false
  18591. */
  18592. this.generateMipmaps = false;
  18593. /**
  18594. * If set to `true`, the texture is flipped along the vertical axis when
  18595. * uploaded to the GPU.
  18596. *
  18597. * Overwritten and set to `false` by default.
  18598. *
  18599. * @type {boolean}
  18600. * @default false
  18601. */
  18602. this.flipY = false;
  18603. /**
  18604. * Specifies the alignment requirements for the start of each pixel row in memory.
  18605. *
  18606. * Overwritten and set to `1` by default.
  18607. *
  18608. * @type {boolean}
  18609. * @default 1
  18610. */
  18611. this.unpackAlignment = 1;
  18612. }
  18613. }
  18614. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18615. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18616. /**
  18617. * Class for representing the armatures in `three.js`. The skeleton
  18618. * is defined by a hierarchy of bones.
  18619. *
  18620. * ```js
  18621. * const bones = [];
  18622. *
  18623. * const shoulder = new THREE.Bone();
  18624. * const elbow = new THREE.Bone();
  18625. * const hand = new THREE.Bone();
  18626. *
  18627. * shoulder.add( elbow );
  18628. * elbow.add( hand );
  18629. *
  18630. * bones.push( shoulder , elbow, hand);
  18631. *
  18632. * shoulder.position.y = -5;
  18633. * elbow.position.y = 0;
  18634. * hand.position.y = 5;
  18635. *
  18636. * const armSkeleton = new THREE.Skeleton( bones );
  18637. * ```
  18638. */
  18639. class Skeleton {
  18640. /**
  18641. * Constructs a new skeleton.
  18642. *
  18643. * @param {Array<Bone>} [bones] - An array of bones.
  18644. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18645. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18646. */
  18647. constructor( bones = [], boneInverses = [] ) {
  18648. this.uuid = generateUUID();
  18649. /**
  18650. * An array of bones defining the skeleton.
  18651. *
  18652. * @type {Array<Bone>}
  18653. */
  18654. this.bones = bones.slice( 0 );
  18655. /**
  18656. * An array of bone inverse matrices.
  18657. *
  18658. * @type {Array<Matrix4>}
  18659. */
  18660. this.boneInverses = boneInverses;
  18661. /**
  18662. * An array buffer holding the bone data.
  18663. * Input data for {@link Skeleton#boneTexture}.
  18664. *
  18665. * @type {?Float32Array}
  18666. * @default null
  18667. */
  18668. this.boneMatrices = null;
  18669. /**
  18670. * A texture holding the bone data for use
  18671. * in the vertex shader.
  18672. *
  18673. * @type {?DataTexture}
  18674. * @default null
  18675. */
  18676. this.boneTexture = null;
  18677. this.init();
  18678. }
  18679. /**
  18680. * Initializes the skeleton. This method gets automatically called by the constructor
  18681. * but depending on how the skeleton is created it might be necessary to call this method
  18682. * manually.
  18683. */
  18684. init() {
  18685. const bones = this.bones;
  18686. const boneInverses = this.boneInverses;
  18687. this.boneMatrices = new Float32Array( bones.length * 16 );
  18688. // calculate inverse bone matrices if necessary
  18689. if ( boneInverses.length === 0 ) {
  18690. this.calculateInverses();
  18691. } else {
  18692. // handle special case
  18693. if ( bones.length !== boneInverses.length ) {
  18694. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18695. this.boneInverses = [];
  18696. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18697. this.boneInverses.push( new Matrix4() );
  18698. }
  18699. }
  18700. }
  18701. }
  18702. /**
  18703. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18704. * and fills it with new matrices.
  18705. */
  18706. calculateInverses() {
  18707. this.boneInverses.length = 0;
  18708. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18709. const inverse = new Matrix4();
  18710. if ( this.bones[ i ] ) {
  18711. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18712. }
  18713. this.boneInverses.push( inverse );
  18714. }
  18715. }
  18716. /**
  18717. * Resets the skeleton to the base pose.
  18718. */
  18719. pose() {
  18720. // recover the bind-time world matrices
  18721. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18722. const bone = this.bones[ i ];
  18723. if ( bone ) {
  18724. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18725. }
  18726. }
  18727. // compute the local matrices, positions, rotations and scales
  18728. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18729. const bone = this.bones[ i ];
  18730. if ( bone ) {
  18731. if ( bone.parent && bone.parent.isBone ) {
  18732. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18733. bone.matrix.multiply( bone.matrixWorld );
  18734. } else {
  18735. bone.matrix.copy( bone.matrixWorld );
  18736. }
  18737. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18738. }
  18739. }
  18740. }
  18741. /**
  18742. * Resets the skeleton to the base pose.
  18743. */
  18744. update() {
  18745. const bones = this.bones;
  18746. const boneInverses = this.boneInverses;
  18747. const boneMatrices = this.boneMatrices;
  18748. const boneTexture = this.boneTexture;
  18749. // flatten bone matrices to array
  18750. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18751. // compute the offset between the current and the original transform
  18752. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18753. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18754. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18755. }
  18756. if ( boneTexture !== null ) {
  18757. boneTexture.needsUpdate = true;
  18758. }
  18759. }
  18760. /**
  18761. * Returns a new skeleton with copied values from this instance.
  18762. *
  18763. * @return {Skeleton} A clone of this instance.
  18764. */
  18765. clone() {
  18766. return new Skeleton( this.bones, this.boneInverses );
  18767. }
  18768. /**
  18769. * Computes a data texture for passing bone data to the vertex shader.
  18770. *
  18771. * @return {Skeleton} A reference of this instance.
  18772. */
  18773. computeBoneTexture() {
  18774. // layout (1 matrix = 4 pixels)
  18775. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18776. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18777. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18778. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18779. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18780. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18781. size = Math.ceil( size / 4 ) * 4;
  18782. size = Math.max( size, 4 );
  18783. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18784. boneMatrices.set( this.boneMatrices ); // copy current values
  18785. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18786. boneTexture.needsUpdate = true;
  18787. this.boneMatrices = boneMatrices;
  18788. this.boneTexture = boneTexture;
  18789. return this;
  18790. }
  18791. /**
  18792. * Searches through the skeleton's bone array and returns the first with a
  18793. * matching name.
  18794. *
  18795. * @param {string} name - The name of the bone.
  18796. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18797. */
  18798. getBoneByName( name ) {
  18799. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18800. const bone = this.bones[ i ];
  18801. if ( bone.name === name ) {
  18802. return bone;
  18803. }
  18804. }
  18805. return undefined;
  18806. }
  18807. /**
  18808. * Frees the GPU-related resources allocated by this instance. Call this
  18809. * method whenever this instance is no longer used in your app.
  18810. */
  18811. dispose( ) {
  18812. if ( this.boneTexture !== null ) {
  18813. this.boneTexture.dispose();
  18814. this.boneTexture = null;
  18815. }
  18816. }
  18817. /**
  18818. * Setups the skeleton by the given JSON and bones.
  18819. *
  18820. * @param {Object} json - The skeleton as serialized JSON.
  18821. * @param {Object<string, Bone>} bones - An array of bones.
  18822. * @return {Skeleton} A reference of this instance.
  18823. */
  18824. fromJSON( json, bones ) {
  18825. this.uuid = json.uuid;
  18826. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18827. const uuid = json.bones[ i ];
  18828. let bone = bones[ uuid ];
  18829. if ( bone === undefined ) {
  18830. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18831. bone = new Bone();
  18832. }
  18833. this.bones.push( bone );
  18834. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18835. }
  18836. this.init();
  18837. return this;
  18838. }
  18839. /**
  18840. * Serializes the skeleton into JSON.
  18841. *
  18842. * @return {Object} A JSON object representing the serialized skeleton.
  18843. * @see {@link ObjectLoader#parse}
  18844. */
  18845. toJSON() {
  18846. const data = {
  18847. metadata: {
  18848. version: 4.7,
  18849. type: 'Skeleton',
  18850. generator: 'Skeleton.toJSON'
  18851. },
  18852. bones: [],
  18853. boneInverses: []
  18854. };
  18855. data.uuid = this.uuid;
  18856. const bones = this.bones;
  18857. const boneInverses = this.boneInverses;
  18858. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18859. const bone = bones[ i ];
  18860. data.bones.push( bone.uuid );
  18861. const boneInverse = boneInverses[ i ];
  18862. data.boneInverses.push( boneInverse.toArray() );
  18863. }
  18864. return data;
  18865. }
  18866. }
  18867. /**
  18868. * An instanced version of a buffer attribute.
  18869. *
  18870. * @augments BufferAttribute
  18871. */
  18872. class InstancedBufferAttribute extends BufferAttribute {
  18873. /**
  18874. * Constructs a new instanced buffer attribute.
  18875. *
  18876. * @param {TypedArray} array - The array holding the attribute data.
  18877. * @param {number} itemSize - The item size.
  18878. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18879. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18880. */
  18881. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18882. super( array, itemSize, normalized );
  18883. /**
  18884. * This flag can be used for type testing.
  18885. *
  18886. * @type {boolean}
  18887. * @readonly
  18888. * @default true
  18889. */
  18890. this.isInstancedBufferAttribute = true;
  18891. /**
  18892. * Defines how often a value of this buffer attribute should be repeated. A
  18893. * value of one means that each value of the instanced attribute is used for
  18894. * a single instance. A value of two means that each value is used for two
  18895. * consecutive instances (and so on).
  18896. *
  18897. * @type {number}
  18898. * @default 1
  18899. */
  18900. this.meshPerAttribute = meshPerAttribute;
  18901. }
  18902. copy( source ) {
  18903. super.copy( source );
  18904. this.meshPerAttribute = source.meshPerAttribute;
  18905. return this;
  18906. }
  18907. toJSON() {
  18908. const data = super.toJSON();
  18909. data.meshPerAttribute = this.meshPerAttribute;
  18910. data.isInstancedBufferAttribute = true;
  18911. return data;
  18912. }
  18913. }
  18914. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18915. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18916. const _instanceIntersects = [];
  18917. const _box3 = /*@__PURE__*/ new Box3();
  18918. const _identity = /*@__PURE__*/ new Matrix4();
  18919. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18920. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18921. /**
  18922. * A special version of a mesh with instanced rendering support. Use
  18923. * this class if you have to render a large number of objects with the same
  18924. * geometry and material(s) but with different world transformations. The usage
  18925. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18926. * improve the overall rendering performance in your application.
  18927. *
  18928. * @augments Mesh
  18929. */
  18930. class InstancedMesh extends Mesh {
  18931. /**
  18932. * Constructs a new instanced mesh.
  18933. *
  18934. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18935. * @param {Material|Array<Material>} [material] - The mesh material.
  18936. * @param {number} count - The number of instances.
  18937. */
  18938. constructor( geometry, material, count ) {
  18939. super( geometry, material );
  18940. /**
  18941. * This flag can be used for type testing.
  18942. *
  18943. * @type {boolean}
  18944. * @readonly
  18945. * @default true
  18946. */
  18947. this.isInstancedMesh = true;
  18948. /**
  18949. * Represents the local transformation of all instances. You have to set its
  18950. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18951. * via {@link InstancedMesh#setMatrixAt}.
  18952. *
  18953. * @type {InstancedBufferAttribute}
  18954. */
  18955. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18956. /**
  18957. * Represents the color of all instances. You have to set its
  18958. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18959. * via {@link InstancedMesh#setColorAt}.
  18960. *
  18961. * @type {?InstancedBufferAttribute}
  18962. * @default null
  18963. */
  18964. this.instanceColor = null;
  18965. /**
  18966. * Represents the morph target weights of all instances. You have to set its
  18967. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18968. * via {@link InstancedMesh#setMorphAt}.
  18969. *
  18970. * @type {?DataTexture}
  18971. * @default null
  18972. */
  18973. this.morphTexture = null;
  18974. /**
  18975. * The number of instances.
  18976. *
  18977. * @type {number}
  18978. */
  18979. this.count = count;
  18980. /**
  18981. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18982. *
  18983. * @type {?Box3}
  18984. * @default null
  18985. */
  18986. this.boundingBox = null;
  18987. /**
  18988. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18989. *
  18990. * @type {?Sphere}
  18991. * @default null
  18992. */
  18993. this.boundingSphere = null;
  18994. for ( let i = 0; i < count; i ++ ) {
  18995. this.setMatrixAt( i, _identity );
  18996. }
  18997. }
  18998. /**
  18999. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19000. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19001. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19002. */
  19003. computeBoundingBox() {
  19004. const geometry = this.geometry;
  19005. const count = this.count;
  19006. if ( this.boundingBox === null ) {
  19007. this.boundingBox = new Box3();
  19008. }
  19009. if ( geometry.boundingBox === null ) {
  19010. geometry.computeBoundingBox();
  19011. }
  19012. this.boundingBox.makeEmpty();
  19013. for ( let i = 0; i < count; i ++ ) {
  19014. this.getMatrixAt( i, _instanceLocalMatrix );
  19015. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19016. this.boundingBox.union( _box3 );
  19017. }
  19018. }
  19019. /**
  19020. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19021. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19022. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19023. */
  19024. computeBoundingSphere() {
  19025. const geometry = this.geometry;
  19026. const count = this.count;
  19027. if ( this.boundingSphere === null ) {
  19028. this.boundingSphere = new Sphere();
  19029. }
  19030. if ( geometry.boundingSphere === null ) {
  19031. geometry.computeBoundingSphere();
  19032. }
  19033. this.boundingSphere.makeEmpty();
  19034. for ( let i = 0; i < count; i ++ ) {
  19035. this.getMatrixAt( i, _instanceLocalMatrix );
  19036. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19037. this.boundingSphere.union( _sphere$4 );
  19038. }
  19039. }
  19040. copy( source, recursive ) {
  19041. super.copy( source, recursive );
  19042. this.instanceMatrix.copy( source.instanceMatrix );
  19043. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19044. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19045. this.count = source.count;
  19046. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19047. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19048. return this;
  19049. }
  19050. /**
  19051. * Gets the color of the defined instance.
  19052. *
  19053. * @param {number} index - The instance index.
  19054. * @param {Color} color - The target object that is used to store the method's result.
  19055. */
  19056. getColorAt( index, color ) {
  19057. color.fromArray( this.instanceColor.array, index * 3 );
  19058. }
  19059. /**
  19060. * Gets the local transformation matrix of the defined instance.
  19061. *
  19062. * @param {number} index - The instance index.
  19063. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19064. */
  19065. getMatrixAt( index, matrix ) {
  19066. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19067. }
  19068. /**
  19069. * Gets the morph target weights of the defined instance.
  19070. *
  19071. * @param {number} index - The instance index.
  19072. * @param {Mesh} object - The target object that is used to store the method's result.
  19073. */
  19074. getMorphAt( index, object ) {
  19075. const objectInfluences = object.morphTargetInfluences;
  19076. const array = this.morphTexture.source.data.data;
  19077. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19078. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19079. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19080. objectInfluences[ i ] = array[ dataIndex + i ];
  19081. }
  19082. }
  19083. raycast( raycaster, intersects ) {
  19084. const matrixWorld = this.matrixWorld;
  19085. const raycastTimes = this.count;
  19086. _mesh$1.geometry = this.geometry;
  19087. _mesh$1.material = this.material;
  19088. if ( _mesh$1.material === undefined ) return;
  19089. // test with bounding sphere first
  19090. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19091. _sphere$4.copy( this.boundingSphere );
  19092. _sphere$4.applyMatrix4( matrixWorld );
  19093. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19094. // now test each instance
  19095. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19096. // calculate the world matrix for each instance
  19097. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19098. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19099. // the mesh represents this single instance
  19100. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19101. _mesh$1.raycast( raycaster, _instanceIntersects );
  19102. // process the result of raycast
  19103. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19104. const intersect = _instanceIntersects[ i ];
  19105. intersect.instanceId = instanceId;
  19106. intersect.object = this;
  19107. intersects.push( intersect );
  19108. }
  19109. _instanceIntersects.length = 0;
  19110. }
  19111. }
  19112. /**
  19113. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19114. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19115. *
  19116. * @param {number} index - The instance index.
  19117. * @param {Color} color - The instance color.
  19118. */
  19119. setColorAt( index, color ) {
  19120. if ( this.instanceColor === null ) {
  19121. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19122. }
  19123. color.toArray( this.instanceColor.array, index * 3 );
  19124. }
  19125. /**
  19126. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19127. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19128. *
  19129. * @param {number} index - The instance index.
  19130. * @param {Matrix4} matrix - The local transformation.
  19131. */
  19132. setMatrixAt( index, matrix ) {
  19133. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19134. }
  19135. /**
  19136. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19137. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19138. *
  19139. * @param {number} index - The instance index.
  19140. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19141. * of a single instance.
  19142. */
  19143. setMorphAt( index, object ) {
  19144. const objectInfluences = object.morphTargetInfluences;
  19145. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19146. if ( this.morphTexture === null ) {
  19147. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19148. }
  19149. const array = this.morphTexture.source.data.data;
  19150. let morphInfluencesSum = 0;
  19151. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19152. morphInfluencesSum += objectInfluences[ i ];
  19153. }
  19154. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19155. const dataIndex = len * index;
  19156. array[ dataIndex ] = morphBaseInfluence;
  19157. array.set( objectInfluences, dataIndex + 1 );
  19158. }
  19159. updateMorphTargets() {
  19160. }
  19161. /**
  19162. * Frees the GPU-related resources allocated by this instance. Call this
  19163. * method whenever this instance is no longer used in your app.
  19164. */
  19165. dispose() {
  19166. this.dispatchEvent( { type: 'dispose' } );
  19167. if ( this.morphTexture !== null ) {
  19168. this.morphTexture.dispose();
  19169. this.morphTexture = null;
  19170. }
  19171. }
  19172. }
  19173. const _vector1 = /*@__PURE__*/ new Vector3();
  19174. const _vector2 = /*@__PURE__*/ new Vector3();
  19175. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19176. /**
  19177. * A two dimensional surface that extends infinitely in 3D space, represented
  19178. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19179. * by a unit length normal vector and a constant.
  19180. */
  19181. class Plane {
  19182. /**
  19183. * Constructs a new plane.
  19184. *
  19185. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19186. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19187. */
  19188. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19189. /**
  19190. * This flag can be used for type testing.
  19191. *
  19192. * @type {boolean}
  19193. * @readonly
  19194. * @default true
  19195. */
  19196. this.isPlane = true;
  19197. /**
  19198. * A unit length vector defining the normal of the plane.
  19199. *
  19200. * @type {Vector3}
  19201. */
  19202. this.normal = normal;
  19203. /**
  19204. * The signed distance from the origin to the plane.
  19205. *
  19206. * @type {number}
  19207. * @default 0
  19208. */
  19209. this.constant = constant;
  19210. }
  19211. /**
  19212. * Sets the plane components by copying the given values.
  19213. *
  19214. * @param {Vector3} normal - The normal.
  19215. * @param {number} constant - The constant.
  19216. * @return {Plane} A reference to this plane.
  19217. */
  19218. set( normal, constant ) {
  19219. this.normal.copy( normal );
  19220. this.constant = constant;
  19221. return this;
  19222. }
  19223. /**
  19224. * Sets the plane components by defining `x`, `y`, `z` as the
  19225. * plane normal and `w` as the constant.
  19226. *
  19227. * @param {number} x - The value for the normal's x component.
  19228. * @param {number} y - The value for the normal's y component.
  19229. * @param {number} z - The value for the normal's z component.
  19230. * @param {number} w - The constant value.
  19231. * @return {Plane} A reference to this plane.
  19232. */
  19233. setComponents( x, y, z, w ) {
  19234. this.normal.set( x, y, z );
  19235. this.constant = w;
  19236. return this;
  19237. }
  19238. /**
  19239. * Sets the plane from the given normal and coplanar point (that is a point
  19240. * that lies onto the plane).
  19241. *
  19242. * @param {Vector3} normal - The normal.
  19243. * @param {Vector3} point - A coplanar point.
  19244. * @return {Plane} A reference to this plane.
  19245. */
  19246. setFromNormalAndCoplanarPoint( normal, point ) {
  19247. this.normal.copy( normal );
  19248. this.constant = - point.dot( this.normal );
  19249. return this;
  19250. }
  19251. /**
  19252. * Sets the plane from three coplanar points. The winding order is
  19253. * assumed to be counter-clockwise, and determines the direction of
  19254. * the plane normal.
  19255. *
  19256. * @param {Vector3} a - The first coplanar point.
  19257. * @param {Vector3} b - The second coplanar point.
  19258. * @param {Vector3} c - The third coplanar point.
  19259. * @return {Plane} A reference to this plane.
  19260. */
  19261. setFromCoplanarPoints( a, b, c ) {
  19262. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19263. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19264. this.setFromNormalAndCoplanarPoint( normal, a );
  19265. return this;
  19266. }
  19267. /**
  19268. * Copies the values of the given plane to this instance.
  19269. *
  19270. * @param {Plane} plane - The plane to copy.
  19271. * @return {Plane} A reference to this plane.
  19272. */
  19273. copy( plane ) {
  19274. this.normal.copy( plane.normal );
  19275. this.constant = plane.constant;
  19276. return this;
  19277. }
  19278. /**
  19279. * Normalizes the plane normal and adjusts the constant accordingly.
  19280. *
  19281. * @return {Plane} A reference to this plane.
  19282. */
  19283. normalize() {
  19284. // Note: will lead to a divide by zero if the plane is invalid.
  19285. const inverseNormalLength = 1.0 / this.normal.length();
  19286. this.normal.multiplyScalar( inverseNormalLength );
  19287. this.constant *= inverseNormalLength;
  19288. return this;
  19289. }
  19290. /**
  19291. * Negates both the plane normal and the constant.
  19292. *
  19293. * @return {Plane} A reference to this plane.
  19294. */
  19295. negate() {
  19296. this.constant *= -1;
  19297. this.normal.negate();
  19298. return this;
  19299. }
  19300. /**
  19301. * Returns the signed distance from the given point to this plane.
  19302. *
  19303. * @param {Vector3} point - The point to compute the distance for.
  19304. * @return {number} The signed distance.
  19305. */
  19306. distanceToPoint( point ) {
  19307. return this.normal.dot( point ) + this.constant;
  19308. }
  19309. /**
  19310. * Returns the signed distance from the given sphere to this plane.
  19311. *
  19312. * @param {Sphere} sphere - The sphere to compute the distance for.
  19313. * @return {number} The signed distance.
  19314. */
  19315. distanceToSphere( sphere ) {
  19316. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19317. }
  19318. /**
  19319. * Projects a the given point onto the plane.
  19320. *
  19321. * @param {Vector3} point - The point to project.
  19322. * @param {Vector3} target - The target vector that is used to store the method's result.
  19323. * @return {Vector3} The projected point on the plane.
  19324. */
  19325. projectPoint( point, target ) {
  19326. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19327. }
  19328. /**
  19329. * Returns the intersection point of the passed line and the plane. Returns
  19330. * `null` if the line does not intersect. Returns the line's starting point if
  19331. * the line is coplanar with the plane.
  19332. *
  19333. * @param {Line3} line - The line to compute the intersection for.
  19334. * @param {Vector3} target - The target vector that is used to store the method's result.
  19335. * @return {?Vector3} The intersection point.
  19336. */
  19337. intersectLine( line, target ) {
  19338. const direction = line.delta( _vector1 );
  19339. const denominator = this.normal.dot( direction );
  19340. if ( denominator === 0 ) {
  19341. // line is coplanar, return origin
  19342. if ( this.distanceToPoint( line.start ) === 0 ) {
  19343. return target.copy( line.start );
  19344. }
  19345. // Unsure if this is the correct method to handle this case.
  19346. return null;
  19347. }
  19348. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19349. if ( t < 0 || t > 1 ) {
  19350. return null;
  19351. }
  19352. return target.copy( line.start ).addScaledVector( direction, t );
  19353. }
  19354. /**
  19355. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19356. *
  19357. * @param {Line3} line - The line to test.
  19358. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19359. */
  19360. intersectsLine( line ) {
  19361. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19362. const startSign = this.distanceToPoint( line.start );
  19363. const endSign = this.distanceToPoint( line.end );
  19364. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19365. }
  19366. /**
  19367. * Returns `true` if the given bounding box intersects with the plane.
  19368. *
  19369. * @param {Box3} box - The bounding box to test.
  19370. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19371. */
  19372. intersectsBox( box ) {
  19373. return box.intersectsPlane( this );
  19374. }
  19375. /**
  19376. * Returns `true` if the given bounding sphere intersects with the plane.
  19377. *
  19378. * @param {Sphere} sphere - The bounding sphere to test.
  19379. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19380. */
  19381. intersectsSphere( sphere ) {
  19382. return sphere.intersectsPlane( this );
  19383. }
  19384. /**
  19385. * Returns a coplanar vector to the plane, by calculating the
  19386. * projection of the normal at the origin onto the plane.
  19387. *
  19388. * @param {Vector3} target - The target vector that is used to store the method's result.
  19389. * @return {Vector3} The coplanar point.
  19390. */
  19391. coplanarPoint( target ) {
  19392. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19393. }
  19394. /**
  19395. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19396. *
  19397. * The optional normal matrix can be pre-computed like so:
  19398. * ```js
  19399. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19400. * ```
  19401. *
  19402. * @param {Matrix4} matrix - The transformation matrix.
  19403. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19404. * @return {Plane} A reference to this plane.
  19405. */
  19406. applyMatrix4( matrix, optionalNormalMatrix ) {
  19407. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19408. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19409. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19410. this.constant = - referencePoint.dot( normal );
  19411. return this;
  19412. }
  19413. /**
  19414. * Translates the plane by the distance defined by the given offset vector.
  19415. * Note that this only affects the plane constant and will not affect the normal vector.
  19416. *
  19417. * @param {Vector3} offset - The offset vector.
  19418. * @return {Plane} A reference to this plane.
  19419. */
  19420. translate( offset ) {
  19421. this.constant -= offset.dot( this.normal );
  19422. return this;
  19423. }
  19424. /**
  19425. * Returns `true` if this plane is equal with the given one.
  19426. *
  19427. * @param {Plane} plane - The plane to test for equality.
  19428. * @return {boolean} Whether this plane is equal with the given one.
  19429. */
  19430. equals( plane ) {
  19431. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19432. }
  19433. /**
  19434. * Returns a new plane with copied values from this instance.
  19435. *
  19436. * @return {Plane} A clone of this instance.
  19437. */
  19438. clone() {
  19439. return new this.constructor().copy( this );
  19440. }
  19441. }
  19442. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19443. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19444. const _vector$6 = /*@__PURE__*/ new Vector3();
  19445. /**
  19446. * Frustums are used to determine what is inside the camera's field of view.
  19447. * They help speed up the rendering process - objects which lie outside a camera's
  19448. * frustum can safely be excluded from rendering.
  19449. *
  19450. * This class is mainly intended for use internally by a renderer.
  19451. */
  19452. class Frustum {
  19453. /**
  19454. * Constructs a new frustum.
  19455. *
  19456. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19457. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19458. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19459. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19460. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19461. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19462. */
  19463. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19464. /**
  19465. * This array holds the planes that enclose the frustum.
  19466. *
  19467. * @type {Array<Plane>}
  19468. */
  19469. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19470. }
  19471. /**
  19472. * Sets the frustum planes by copying the given planes.
  19473. *
  19474. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19475. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19476. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19477. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19478. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19479. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19480. * @return {Frustum} A reference to this frustum.
  19481. */
  19482. set( p0, p1, p2, p3, p4, p5 ) {
  19483. const planes = this.planes;
  19484. planes[ 0 ].copy( p0 );
  19485. planes[ 1 ].copy( p1 );
  19486. planes[ 2 ].copy( p2 );
  19487. planes[ 3 ].copy( p3 );
  19488. planes[ 4 ].copy( p4 );
  19489. planes[ 5 ].copy( p5 );
  19490. return this;
  19491. }
  19492. /**
  19493. * Copies the values of the given frustum to this instance.
  19494. *
  19495. * @param {Frustum} frustum - The frustum to copy.
  19496. * @return {Frustum} A reference to this frustum.
  19497. */
  19498. copy( frustum ) {
  19499. const planes = this.planes;
  19500. for ( let i = 0; i < 6; i ++ ) {
  19501. planes[ i ].copy( frustum.planes[ i ] );
  19502. }
  19503. return this;
  19504. }
  19505. /**
  19506. * Sets the frustum planes from the given projection matrix.
  19507. *
  19508. * @param {Matrix4} m - The projection matrix.
  19509. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19510. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19511. * @return {Frustum} A reference to this frustum.
  19512. */
  19513. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19514. const planes = this.planes;
  19515. const me = m.elements;
  19516. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19517. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19518. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19519. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19520. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19521. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19522. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19523. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19524. if ( reversedDepth ) {
  19525. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19526. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19527. } else {
  19528. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19529. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19530. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19531. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19532. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19533. } else {
  19534. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19535. }
  19536. }
  19537. return this;
  19538. }
  19539. /**
  19540. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19541. *
  19542. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19543. *
  19544. * @param {Object3D} object - The 3D object to test.
  19545. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19546. */
  19547. intersectsObject( object ) {
  19548. if ( object.boundingSphere !== undefined ) {
  19549. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19550. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19551. } else {
  19552. const geometry = object.geometry;
  19553. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19554. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19555. }
  19556. return this.intersectsSphere( _sphere$3 );
  19557. }
  19558. /**
  19559. * Returns `true` if the given sprite is intersecting this frustum.
  19560. *
  19561. * @param {Sprite} sprite - The sprite to test.
  19562. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19563. */
  19564. intersectsSprite( sprite ) {
  19565. _sphere$3.center.set( 0, 0, 0 );
  19566. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19567. _sphere$3.radius = 0.7071067811865476 + offset;
  19568. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19569. return this.intersectsSphere( _sphere$3 );
  19570. }
  19571. /**
  19572. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19573. *
  19574. * @param {Sphere} sphere - The bounding sphere to test.
  19575. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19576. */
  19577. intersectsSphere( sphere ) {
  19578. const planes = this.planes;
  19579. const center = sphere.center;
  19580. const negRadius = - sphere.radius;
  19581. for ( let i = 0; i < 6; i ++ ) {
  19582. const distance = planes[ i ].distanceToPoint( center );
  19583. if ( distance < negRadius ) {
  19584. return false;
  19585. }
  19586. }
  19587. return true;
  19588. }
  19589. /**
  19590. * Returns `true` if the given bounding box is intersecting this frustum.
  19591. *
  19592. * @param {Box3} box - The bounding box to test.
  19593. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19594. */
  19595. intersectsBox( box ) {
  19596. const planes = this.planes;
  19597. for ( let i = 0; i < 6; i ++ ) {
  19598. const plane = planes[ i ];
  19599. // corner at max distance
  19600. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19601. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19602. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19603. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19604. return false;
  19605. }
  19606. }
  19607. return true;
  19608. }
  19609. /**
  19610. * Returns `true` if the given point lies within the frustum.
  19611. *
  19612. * @param {Vector3} point - The point to test.
  19613. * @return {boolean} Whether the point lies within this frustum or not.
  19614. */
  19615. containsPoint( point ) {
  19616. const planes = this.planes;
  19617. for ( let i = 0; i < 6; i ++ ) {
  19618. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19619. return false;
  19620. }
  19621. }
  19622. return true;
  19623. }
  19624. /**
  19625. * Returns a new frustum with copied values from this instance.
  19626. *
  19627. * @return {Frustum} A clone of this instance.
  19628. */
  19629. clone() {
  19630. return new this.constructor().copy( this );
  19631. }
  19632. }
  19633. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19634. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19635. /**
  19636. * FrustumArray is used to determine if an object is visible in at least one camera
  19637. * from an array of cameras. This is particularly useful for multi-view renderers.
  19638. */
  19639. class FrustumArray {
  19640. /**
  19641. * Constructs a new frustum array.
  19642. *
  19643. */
  19644. constructor() {
  19645. /**
  19646. * The coordinate system to use.
  19647. *
  19648. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19649. * @default WebGLCoordinateSystem
  19650. */
  19651. this.coordinateSystem = WebGLCoordinateSystem;
  19652. }
  19653. /**
  19654. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19655. * from the camera array.
  19656. *
  19657. * @param {Object3D} object - The 3D object to test.
  19658. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19659. * @return {boolean} Whether the 3D object is visible in any camera.
  19660. */
  19661. intersectsObject( object, cameraArray ) {
  19662. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19663. return false;
  19664. }
  19665. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19666. const camera = cameraArray.cameras[ i ];
  19667. _projScreenMatrix$2.multiplyMatrices(
  19668. camera.projectionMatrix,
  19669. camera.matrixWorldInverse
  19670. );
  19671. _frustum$1.setFromProjectionMatrix(
  19672. _projScreenMatrix$2,
  19673. camera.coordinateSystem,
  19674. camera.reversedDepth
  19675. );
  19676. if ( _frustum$1.intersectsObject( object ) ) {
  19677. return true; // Object is visible in at least one camera
  19678. }
  19679. }
  19680. return false; // Not visible in any camera
  19681. }
  19682. /**
  19683. * Returns `true` if the given sprite is intersecting any frustum
  19684. * from the camera array.
  19685. *
  19686. * @param {Sprite} sprite - The sprite to test.
  19687. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19688. * @return {boolean} Whether the sprite is visible in any camera.
  19689. */
  19690. intersectsSprite( sprite, cameraArray ) {
  19691. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19692. return false;
  19693. }
  19694. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19695. const camera = cameraArray.cameras[ i ];
  19696. _projScreenMatrix$2.multiplyMatrices(
  19697. camera.projectionMatrix,
  19698. camera.matrixWorldInverse
  19699. );
  19700. _frustum$1.setFromProjectionMatrix(
  19701. _projScreenMatrix$2,
  19702. camera.coordinateSystem,
  19703. camera.reversedDepth
  19704. );
  19705. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19706. return true; // Sprite is visible in at least one camera
  19707. }
  19708. }
  19709. return false; // Not visible in any camera
  19710. }
  19711. /**
  19712. * Returns `true` if the given bounding sphere is intersecting any frustum
  19713. * from the camera array.
  19714. *
  19715. * @param {Sphere} sphere - The bounding sphere to test.
  19716. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19717. * @return {boolean} Whether the sphere is visible in any camera.
  19718. */
  19719. intersectsSphere( sphere, cameraArray ) {
  19720. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19721. return false;
  19722. }
  19723. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19724. const camera = cameraArray.cameras[ i ];
  19725. _projScreenMatrix$2.multiplyMatrices(
  19726. camera.projectionMatrix,
  19727. camera.matrixWorldInverse
  19728. );
  19729. _frustum$1.setFromProjectionMatrix(
  19730. _projScreenMatrix$2,
  19731. camera.coordinateSystem,
  19732. camera.reversedDepth
  19733. );
  19734. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19735. return true; // Sphere is visible in at least one camera
  19736. }
  19737. }
  19738. return false; // Not visible in any camera
  19739. }
  19740. /**
  19741. * Returns `true` if the given bounding box is intersecting any frustum
  19742. * from the camera array.
  19743. *
  19744. * @param {Box3} box - The bounding box to test.
  19745. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19746. * @return {boolean} Whether the box is visible in any camera.
  19747. */
  19748. intersectsBox( box, cameraArray ) {
  19749. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19750. return false;
  19751. }
  19752. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19753. const camera = cameraArray.cameras[ i ];
  19754. _projScreenMatrix$2.multiplyMatrices(
  19755. camera.projectionMatrix,
  19756. camera.matrixWorldInverse
  19757. );
  19758. _frustum$1.setFromProjectionMatrix(
  19759. _projScreenMatrix$2,
  19760. camera.coordinateSystem,
  19761. camera.reversedDepth
  19762. );
  19763. if ( _frustum$1.intersectsBox( box ) ) {
  19764. return true; // Box is visible in at least one camera
  19765. }
  19766. }
  19767. return false; // Not visible in any camera
  19768. }
  19769. /**
  19770. * Returns `true` if the given point lies within any frustum
  19771. * from the camera array.
  19772. *
  19773. * @param {Vector3} point - The point to test.
  19774. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19775. * @return {boolean} Whether the point is visible in any camera.
  19776. */
  19777. containsPoint( point, cameraArray ) {
  19778. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19779. return false;
  19780. }
  19781. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19782. const camera = cameraArray.cameras[ i ];
  19783. _projScreenMatrix$2.multiplyMatrices(
  19784. camera.projectionMatrix,
  19785. camera.matrixWorldInverse
  19786. );
  19787. _frustum$1.setFromProjectionMatrix(
  19788. _projScreenMatrix$2,
  19789. camera.coordinateSystem,
  19790. camera.reversedDepth
  19791. );
  19792. if ( _frustum$1.containsPoint( point ) ) {
  19793. return true; // Point is visible in at least one camera
  19794. }
  19795. }
  19796. return false; // Not visible in any camera
  19797. }
  19798. /**
  19799. * Returns a new frustum array with copied values from this instance.
  19800. *
  19801. * @return {FrustumArray} A clone of this instance.
  19802. */
  19803. clone() {
  19804. return new FrustumArray();
  19805. }
  19806. }
  19807. function ascIdSort( a, b ) {
  19808. return a - b;
  19809. }
  19810. function sortOpaque( a, b ) {
  19811. return a.z - b.z;
  19812. }
  19813. function sortTransparent( a, b ) {
  19814. return b.z - a.z;
  19815. }
  19816. class MultiDrawRenderList {
  19817. constructor() {
  19818. this.index = 0;
  19819. this.pool = [];
  19820. this.list = [];
  19821. }
  19822. push( start, count, z, index ) {
  19823. const pool = this.pool;
  19824. const list = this.list;
  19825. if ( this.index >= pool.length ) {
  19826. pool.push( {
  19827. start: -1,
  19828. count: -1,
  19829. z: -1,
  19830. index: -1,
  19831. } );
  19832. }
  19833. const item = pool[ this.index ];
  19834. list.push( item );
  19835. this.index ++;
  19836. item.start = start;
  19837. item.count = count;
  19838. item.z = z;
  19839. item.index = index;
  19840. }
  19841. reset() {
  19842. this.list.length = 0;
  19843. this.index = 0;
  19844. }
  19845. }
  19846. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19847. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19848. const _frustum = /*@__PURE__*/ new Frustum();
  19849. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19850. const _box$1 = /*@__PURE__*/ new Box3();
  19851. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19852. const _vector$5 = /*@__PURE__*/ new Vector3();
  19853. const _forward$1 = /*@__PURE__*/ new Vector3();
  19854. const _temp = /*@__PURE__*/ new Vector3();
  19855. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19856. const _mesh = /*@__PURE__*/ new Mesh();
  19857. const _batchIntersects = [];
  19858. // copies data from attribute "src" into "target" starting at "targetOffset"
  19859. function copyAttributeData( src, target, targetOffset = 0 ) {
  19860. const itemSize = target.itemSize;
  19861. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19862. // use the component getters and setters if the array data cannot
  19863. // be copied directly
  19864. const vertexCount = src.count;
  19865. for ( let i = 0; i < vertexCount; i ++ ) {
  19866. for ( let c = 0; c < itemSize; c ++ ) {
  19867. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19868. }
  19869. }
  19870. } else {
  19871. // faster copy approach using typed array set function
  19872. target.array.set( src.array, targetOffset * itemSize );
  19873. }
  19874. target.needsUpdate = true;
  19875. }
  19876. // safely copies array contents to a potentially smaller array
  19877. function copyArrayContents( src, target ) {
  19878. if ( src.constructor !== target.constructor ) {
  19879. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19880. const len = Math.min( src.length, target.length );
  19881. for ( let i = 0; i < len; i ++ ) {
  19882. target[ i ] = src[ i ];
  19883. }
  19884. } else {
  19885. // if the arrays use the same data layout we can use a fast block copy
  19886. const len = Math.min( src.length, target.length );
  19887. target.set( new src.constructor( src.buffer, 0, len ) );
  19888. }
  19889. }
  19890. /**
  19891. * A special version of a mesh with multi draw batch rendering support. Use
  19892. * this class if you have to render a large number of objects with the same
  19893. * material but with different geometries or world transformations. The usage of
  19894. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19895. * rendering performance in your application.
  19896. *
  19897. * ```js
  19898. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19899. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19900. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19901. *
  19902. * // initialize and add geometries into the batched mesh
  19903. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19904. * const boxGeometryId = batchedMesh.addGeometry( box );
  19905. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19906. *
  19907. * // create instances of those geometries
  19908. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19909. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19910. *
  19911. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19912. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19913. *
  19914. * // position the geometries
  19915. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19916. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19917. *
  19918. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19919. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19920. *
  19921. * scene.add( batchedMesh );
  19922. * ```
  19923. *
  19924. * @augments Mesh
  19925. */
  19926. class BatchedMesh extends Mesh {
  19927. /**
  19928. * Constructs a new batched mesh.
  19929. *
  19930. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19931. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19932. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19933. * @param {Material|Array<Material>} [material] - The mesh material.
  19934. */
  19935. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19936. super( new BufferGeometry(), material );
  19937. /**
  19938. * This flag can be used for type testing.
  19939. *
  19940. * @type {boolean}
  19941. * @readonly
  19942. * @default true
  19943. */
  19944. this.isBatchedMesh = true;
  19945. /**
  19946. * When set ot `true`, the individual objects of a batch are frustum culled.
  19947. *
  19948. * @type {boolean}
  19949. * @default true
  19950. */
  19951. this.perObjectFrustumCulled = true;
  19952. /**
  19953. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19954. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19955. * rendered front to back.
  19956. *
  19957. * @type {boolean}
  19958. * @default true
  19959. */
  19960. this.sortObjects = true;
  19961. /**
  19962. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19963. *
  19964. * @type {?Box3}
  19965. * @default null
  19966. */
  19967. this.boundingBox = null;
  19968. /**
  19969. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19970. *
  19971. * @type {?Sphere}
  19972. * @default null
  19973. */
  19974. this.boundingSphere = null;
  19975. /**
  19976. * Takes a sort a function that is run before render. The function takes a list of instances to
  19977. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19978. * sort with.
  19979. *
  19980. * @type {?Function}
  19981. * @default null
  19982. */
  19983. this.customSort = null;
  19984. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19985. this._instanceInfo = [];
  19986. this._geometryInfo = [];
  19987. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19988. this._availableInstanceIds = [];
  19989. this._availableGeometryIds = [];
  19990. // used to track where the next point is that geometry should be inserted
  19991. this._nextIndexStart = 0;
  19992. this._nextVertexStart = 0;
  19993. this._geometryCount = 0;
  19994. // flags
  19995. this._visibilityChanged = true;
  19996. this._geometryInitialized = false;
  19997. // cached user options
  19998. this._maxInstanceCount = maxInstanceCount;
  19999. this._maxVertexCount = maxVertexCount;
  20000. this._maxIndexCount = maxIndexCount;
  20001. // buffers for multi draw
  20002. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20003. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20004. this._multiDrawCount = 0;
  20005. this._multiDrawInstances = null;
  20006. // Local matrix per geometry by using data texture
  20007. this._matricesTexture = null;
  20008. this._indirectTexture = null;
  20009. this._colorsTexture = null;
  20010. this._initMatricesTexture();
  20011. this._initIndirectTexture();
  20012. }
  20013. /**
  20014. * The maximum number of individual instances that can be stored in the batch.
  20015. *
  20016. * @type {number}
  20017. * @readonly
  20018. */
  20019. get maxInstanceCount() {
  20020. return this._maxInstanceCount;
  20021. }
  20022. /**
  20023. * The instance count.
  20024. *
  20025. * @type {number}
  20026. * @readonly
  20027. */
  20028. get instanceCount() {
  20029. return this._instanceInfo.length - this._availableInstanceIds.length;
  20030. }
  20031. /**
  20032. * The number of unused vertices.
  20033. *
  20034. * @type {number}
  20035. * @readonly
  20036. */
  20037. get unusedVertexCount() {
  20038. return this._maxVertexCount - this._nextVertexStart;
  20039. }
  20040. /**
  20041. * The number of unused indices.
  20042. *
  20043. * @type {number}
  20044. * @readonly
  20045. */
  20046. get unusedIndexCount() {
  20047. return this._maxIndexCount - this._nextIndexStart;
  20048. }
  20049. _initMatricesTexture() {
  20050. // layout (1 matrix = 4 pixels)
  20051. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20052. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20053. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20054. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20055. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20056. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20057. size = Math.ceil( size / 4 ) * 4;
  20058. size = Math.max( size, 4 );
  20059. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20060. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20061. this._matricesTexture = matricesTexture;
  20062. }
  20063. _initIndirectTexture() {
  20064. let size = Math.sqrt( this._maxInstanceCount );
  20065. size = Math.ceil( size );
  20066. const indirectArray = new Uint32Array( size * size );
  20067. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20068. this._indirectTexture = indirectTexture;
  20069. }
  20070. _initColorsTexture() {
  20071. let size = Math.sqrt( this._maxInstanceCount );
  20072. size = Math.ceil( size );
  20073. // 4 floats per RGBA pixel initialized to white
  20074. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20075. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20076. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20077. this._colorsTexture = colorsTexture;
  20078. }
  20079. _initializeGeometry( reference ) {
  20080. const geometry = this.geometry;
  20081. const maxVertexCount = this._maxVertexCount;
  20082. const maxIndexCount = this._maxIndexCount;
  20083. if ( this._geometryInitialized === false ) {
  20084. for ( const attributeName in reference.attributes ) {
  20085. const srcAttribute = reference.getAttribute( attributeName );
  20086. const { array, itemSize, normalized } = srcAttribute;
  20087. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20088. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20089. geometry.setAttribute( attributeName, dstAttribute );
  20090. }
  20091. if ( reference.getIndex() !== null ) {
  20092. // Reserve last u16 index for primitive restart.
  20093. const indexArray = maxVertexCount > 65535
  20094. ? new Uint32Array( maxIndexCount )
  20095. : new Uint16Array( maxIndexCount );
  20096. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20097. }
  20098. this._geometryInitialized = true;
  20099. }
  20100. }
  20101. // Make sure the geometry is compatible with the existing combined geometry attributes
  20102. _validateGeometry( geometry ) {
  20103. // check to ensure the geometries are using consistent attributes and indices
  20104. const batchGeometry = this.geometry;
  20105. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20106. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20107. }
  20108. for ( const attributeName in batchGeometry.attributes ) {
  20109. if ( ! geometry.hasAttribute( attributeName ) ) {
  20110. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20111. }
  20112. const srcAttribute = geometry.getAttribute( attributeName );
  20113. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20114. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20115. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20116. }
  20117. }
  20118. }
  20119. /**
  20120. * Validates the instance defined by the given ID.
  20121. *
  20122. * @param {number} instanceId - The instance to validate.
  20123. */
  20124. validateInstanceId( instanceId ) {
  20125. const instanceInfo = this._instanceInfo;
  20126. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20127. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20128. }
  20129. }
  20130. /**
  20131. * Validates the geometry defined by the given ID.
  20132. *
  20133. * @param {number} geometryId - The geometry to validate.
  20134. */
  20135. validateGeometryId( geometryId ) {
  20136. const geometryInfoList = this._geometryInfo;
  20137. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20138. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20139. }
  20140. }
  20141. /**
  20142. * Takes a sort a function that is run before render. The function takes a list of instances to
  20143. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20144. *
  20145. * @param {Function} func - The custom sort function.
  20146. * @return {BatchedMesh} A reference to this batched mesh.
  20147. */
  20148. setCustomSort( func ) {
  20149. this.customSort = func;
  20150. return this;
  20151. }
  20152. /**
  20153. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20154. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20155. * otherwise they are `null`.
  20156. */
  20157. computeBoundingBox() {
  20158. if ( this.boundingBox === null ) {
  20159. this.boundingBox = new Box3();
  20160. }
  20161. const boundingBox = this.boundingBox;
  20162. const instanceInfo = this._instanceInfo;
  20163. boundingBox.makeEmpty();
  20164. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20165. if ( instanceInfo[ i ].active === false ) continue;
  20166. const geometryId = instanceInfo[ i ].geometryIndex;
  20167. this.getMatrixAt( i, _matrix$1 );
  20168. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20169. boundingBox.union( _box$1 );
  20170. }
  20171. }
  20172. /**
  20173. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20174. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20175. * otherwise they are `null`.
  20176. */
  20177. computeBoundingSphere() {
  20178. if ( this.boundingSphere === null ) {
  20179. this.boundingSphere = new Sphere();
  20180. }
  20181. const boundingSphere = this.boundingSphere;
  20182. const instanceInfo = this._instanceInfo;
  20183. boundingSphere.makeEmpty();
  20184. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20185. if ( instanceInfo[ i ].active === false ) continue;
  20186. const geometryId = instanceInfo[ i ].geometryIndex;
  20187. this.getMatrixAt( i, _matrix$1 );
  20188. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20189. boundingSphere.union( _sphere$2 );
  20190. }
  20191. }
  20192. /**
  20193. * Adds a new instance to the batch using the geometry of the given ID and returns
  20194. * a new id referring to the new instance to be used by other functions.
  20195. *
  20196. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20197. * @return {number} The instance ID.
  20198. */
  20199. addInstance( geometryId ) {
  20200. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20201. // ensure we're not over geometry
  20202. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20203. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20204. }
  20205. const instanceInfo = {
  20206. visible: true,
  20207. active: true,
  20208. geometryIndex: geometryId,
  20209. };
  20210. let drawId = null;
  20211. // Prioritize using previously freed instance ids
  20212. if ( this._availableInstanceIds.length > 0 ) {
  20213. this._availableInstanceIds.sort( ascIdSort );
  20214. drawId = this._availableInstanceIds.shift();
  20215. this._instanceInfo[ drawId ] = instanceInfo;
  20216. } else {
  20217. drawId = this._instanceInfo.length;
  20218. this._instanceInfo.push( instanceInfo );
  20219. }
  20220. const matricesTexture = this._matricesTexture;
  20221. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20222. matricesTexture.needsUpdate = true;
  20223. const colorsTexture = this._colorsTexture;
  20224. if ( colorsTexture ) {
  20225. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20226. colorsTexture.needsUpdate = true;
  20227. }
  20228. this._visibilityChanged = true;
  20229. return drawId;
  20230. }
  20231. /**
  20232. * Adds the given geometry to the batch and returns the associated
  20233. * geometry id referring to it to be used in other functions.
  20234. *
  20235. * @param {BufferGeometry} geometry - The geometry to add.
  20236. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20237. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20238. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20239. * Defaults to the length of the given geometry vertex buffer.
  20240. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20241. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20242. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20243. * the length of the given geometry index buffer.
  20244. * @return {number} The geometry ID.
  20245. */
  20246. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20247. this._initializeGeometry( geometry );
  20248. this._validateGeometry( geometry );
  20249. const geometryInfo = {
  20250. // geometry information
  20251. vertexStart: -1,
  20252. vertexCount: -1,
  20253. reservedVertexCount: -1,
  20254. indexStart: -1,
  20255. indexCount: -1,
  20256. reservedIndexCount: -1,
  20257. // draw range information
  20258. start: -1,
  20259. count: -1,
  20260. // state
  20261. boundingBox: null,
  20262. boundingSphere: null,
  20263. active: true,
  20264. };
  20265. const geometryInfoList = this._geometryInfo;
  20266. geometryInfo.vertexStart = this._nextVertexStart;
  20267. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20268. const index = geometry.getIndex();
  20269. const hasIndex = index !== null;
  20270. if ( hasIndex ) {
  20271. geometryInfo.indexStart = this._nextIndexStart;
  20272. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20273. }
  20274. if (
  20275. geometryInfo.indexStart !== -1 &&
  20276. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20277. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20278. ) {
  20279. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20280. }
  20281. // update id
  20282. let geometryId;
  20283. if ( this._availableGeometryIds.length > 0 ) {
  20284. this._availableGeometryIds.sort( ascIdSort );
  20285. geometryId = this._availableGeometryIds.shift();
  20286. geometryInfoList[ geometryId ] = geometryInfo;
  20287. } else {
  20288. geometryId = this._geometryCount;
  20289. this._geometryCount ++;
  20290. geometryInfoList.push( geometryInfo );
  20291. }
  20292. // update the geometry
  20293. this.setGeometryAt( geometryId, geometry );
  20294. // increment the next geometry position
  20295. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20296. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20297. return geometryId;
  20298. }
  20299. /**
  20300. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20301. * is not enough space reserved for geometry. Calling this will change all instances that are
  20302. * rendering that geometry.
  20303. *
  20304. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20305. * @param {BufferGeometry} geometry - The new geometry.
  20306. * @return {number} The geometry ID.
  20307. */
  20308. setGeometryAt( geometryId, geometry ) {
  20309. if ( geometryId >= this._geometryCount ) {
  20310. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20311. }
  20312. this._validateGeometry( geometry );
  20313. const batchGeometry = this.geometry;
  20314. const hasIndex = batchGeometry.getIndex() !== null;
  20315. const dstIndex = batchGeometry.getIndex();
  20316. const srcIndex = geometry.getIndex();
  20317. const geometryInfo = this._geometryInfo[ geometryId ];
  20318. if (
  20319. hasIndex &&
  20320. srcIndex.count > geometryInfo.reservedIndexCount ||
  20321. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20322. ) {
  20323. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20324. }
  20325. // copy geometry buffer data over
  20326. const vertexStart = geometryInfo.vertexStart;
  20327. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20328. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20329. for ( const attributeName in batchGeometry.attributes ) {
  20330. // copy attribute data
  20331. const srcAttribute = geometry.getAttribute( attributeName );
  20332. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20333. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20334. // fill the rest in with zeroes
  20335. const itemSize = srcAttribute.itemSize;
  20336. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20337. const index = vertexStart + i;
  20338. for ( let c = 0; c < itemSize; c ++ ) {
  20339. dstAttribute.setComponent( index, c, 0 );
  20340. }
  20341. }
  20342. dstAttribute.needsUpdate = true;
  20343. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20344. }
  20345. // copy index
  20346. if ( hasIndex ) {
  20347. const indexStart = geometryInfo.indexStart;
  20348. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20349. geometryInfo.indexCount = geometry.getIndex().count;
  20350. // copy index data over
  20351. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20352. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20353. }
  20354. // fill the rest in with zeroes
  20355. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20356. dstIndex.setX( indexStart + i, vertexStart );
  20357. }
  20358. dstIndex.needsUpdate = true;
  20359. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20360. }
  20361. // update the draw range
  20362. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20363. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20364. // store the bounding boxes
  20365. geometryInfo.boundingBox = null;
  20366. if ( geometry.boundingBox !== null ) {
  20367. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20368. }
  20369. geometryInfo.boundingSphere = null;
  20370. if ( geometry.boundingSphere !== null ) {
  20371. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20372. }
  20373. this._visibilityChanged = true;
  20374. return geometryId;
  20375. }
  20376. /**
  20377. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20378. * this geometry will also be removed as a side effect.
  20379. *
  20380. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20381. * @return {BatchedMesh} A reference to this batched mesh.
  20382. */
  20383. deleteGeometry( geometryId ) {
  20384. const geometryInfoList = this._geometryInfo;
  20385. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20386. return this;
  20387. }
  20388. // delete any instances associated with this geometry
  20389. const instanceInfo = this._instanceInfo;
  20390. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20391. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20392. this.deleteInstance( i );
  20393. }
  20394. }
  20395. geometryInfoList[ geometryId ].active = false;
  20396. this._availableGeometryIds.push( geometryId );
  20397. this._visibilityChanged = true;
  20398. return this;
  20399. }
  20400. /**
  20401. * Deletes an existing instance from the batch using the given ID.
  20402. *
  20403. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20404. * @return {BatchedMesh} A reference to this batched mesh.
  20405. */
  20406. deleteInstance( instanceId ) {
  20407. this.validateInstanceId( instanceId );
  20408. this._instanceInfo[ instanceId ].active = false;
  20409. this._availableInstanceIds.push( instanceId );
  20410. this._visibilityChanged = true;
  20411. return this;
  20412. }
  20413. /**
  20414. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20415. * previously deleted geometry, freeing up space to add new geometry.
  20416. *
  20417. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20418. * @return {BatchedMesh} A reference to this batched mesh.
  20419. */
  20420. optimize() {
  20421. // track the next indices to copy data to
  20422. let nextVertexStart = 0;
  20423. let nextIndexStart = 0;
  20424. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20425. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20426. const geometryInfoList = this._geometryInfo;
  20427. const indices = geometryInfoList
  20428. .map( ( e, i ) => i )
  20429. .sort( ( a, b ) => {
  20430. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20431. } );
  20432. const geometry = this.geometry;
  20433. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20434. // if a geometry range is inactive then don't copy anything
  20435. const index = indices[ i ];
  20436. const geometryInfo = geometryInfoList[ index ];
  20437. if ( geometryInfo.active === false ) {
  20438. continue;
  20439. }
  20440. // if a geometry contains an index buffer then shift it, as well
  20441. if ( geometry.index !== null ) {
  20442. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20443. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20444. const index = geometry.index;
  20445. const array = index.array;
  20446. // shift the index pointers based on how the vertex data will shift
  20447. // adjusting the index must happen first so the original vertex start value is available
  20448. const elementDelta = nextVertexStart - vertexStart;
  20449. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20450. array[ j ] = array[ j ] + elementDelta;
  20451. }
  20452. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20453. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20454. geometryInfo.indexStart = nextIndexStart;
  20455. }
  20456. nextIndexStart += geometryInfo.reservedIndexCount;
  20457. }
  20458. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20459. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20460. const { vertexStart, reservedVertexCount } = geometryInfo;
  20461. const attributes = geometry.attributes;
  20462. for ( const key in attributes ) {
  20463. const attribute = attributes[ key ];
  20464. const { array, itemSize } = attribute;
  20465. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20466. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20467. }
  20468. geometryInfo.vertexStart = nextVertexStart;
  20469. }
  20470. nextVertexStart += geometryInfo.reservedVertexCount;
  20471. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20472. // step the next geometry points to the shifted position
  20473. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20474. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20475. }
  20476. return this;
  20477. }
  20478. /**
  20479. * Returns the bounding box for the given geometry.
  20480. *
  20481. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20482. * @param {Box3} target - The target object that is used to store the method's result.
  20483. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20484. */
  20485. getBoundingBoxAt( geometryId, target ) {
  20486. if ( geometryId >= this._geometryCount ) {
  20487. return null;
  20488. }
  20489. // compute bounding box
  20490. const geometry = this.geometry;
  20491. const geometryInfo = this._geometryInfo[ geometryId ];
  20492. if ( geometryInfo.boundingBox === null ) {
  20493. const box = new Box3();
  20494. const index = geometry.index;
  20495. const position = geometry.attributes.position;
  20496. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20497. let iv = i;
  20498. if ( index ) {
  20499. iv = index.getX( iv );
  20500. }
  20501. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20502. }
  20503. geometryInfo.boundingBox = box;
  20504. }
  20505. target.copy( geometryInfo.boundingBox );
  20506. return target;
  20507. }
  20508. /**
  20509. * Returns the bounding sphere for the given geometry.
  20510. *
  20511. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20512. * @param {Sphere} target - The target object that is used to store the method's result.
  20513. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20514. */
  20515. getBoundingSphereAt( geometryId, target ) {
  20516. if ( geometryId >= this._geometryCount ) {
  20517. return null;
  20518. }
  20519. // compute bounding sphere
  20520. const geometry = this.geometry;
  20521. const geometryInfo = this._geometryInfo[ geometryId ];
  20522. if ( geometryInfo.boundingSphere === null ) {
  20523. const sphere = new Sphere();
  20524. this.getBoundingBoxAt( geometryId, _box$1 );
  20525. _box$1.getCenter( sphere.center );
  20526. const index = geometry.index;
  20527. const position = geometry.attributes.position;
  20528. let maxRadiusSq = 0;
  20529. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20530. let iv = i;
  20531. if ( index ) {
  20532. iv = index.getX( iv );
  20533. }
  20534. _vector$5.fromBufferAttribute( position, iv );
  20535. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20536. }
  20537. sphere.radius = Math.sqrt( maxRadiusSq );
  20538. geometryInfo.boundingSphere = sphere;
  20539. }
  20540. target.copy( geometryInfo.boundingSphere );
  20541. return target;
  20542. }
  20543. /**
  20544. * Sets the given local transformation matrix to the defined instance.
  20545. * Negatively scaled matrices are not supported.
  20546. *
  20547. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20548. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20549. * @return {BatchedMesh} A reference to this batched mesh.
  20550. */
  20551. setMatrixAt( instanceId, matrix ) {
  20552. this.validateInstanceId( instanceId );
  20553. const matricesTexture = this._matricesTexture;
  20554. const matricesArray = this._matricesTexture.image.data;
  20555. matrix.toArray( matricesArray, instanceId * 16 );
  20556. matricesTexture.needsUpdate = true;
  20557. return this;
  20558. }
  20559. /**
  20560. * Returns the local transformation matrix of the defined instance.
  20561. *
  20562. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20563. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20564. * @return {Matrix4} The instance's local transformation matrix.
  20565. */
  20566. getMatrixAt( instanceId, matrix ) {
  20567. this.validateInstanceId( instanceId );
  20568. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20569. }
  20570. /**
  20571. * Sets the given color to the defined instance.
  20572. *
  20573. * @param {number} instanceId - The ID of an instance to set the color of.
  20574. * @param {Color} color - The color to set the instance to.
  20575. * @return {BatchedMesh} A reference to this batched mesh.
  20576. */
  20577. setColorAt( instanceId, color ) {
  20578. this.validateInstanceId( instanceId );
  20579. if ( this._colorsTexture === null ) {
  20580. this._initColorsTexture();
  20581. }
  20582. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20583. this._colorsTexture.needsUpdate = true;
  20584. return this;
  20585. }
  20586. /**
  20587. * Returns the color of the defined instance.
  20588. *
  20589. * @param {number} instanceId - The ID of an instance to get the color of.
  20590. * @param {Color} color - The target object that is used to store the method's result.
  20591. * @return {Color} The instance's color.
  20592. */
  20593. getColorAt( instanceId, color ) {
  20594. this.validateInstanceId( instanceId );
  20595. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20596. }
  20597. /**
  20598. * Sets the visibility of the instance.
  20599. *
  20600. * @param {number} instanceId - The id of the instance to set the visibility of.
  20601. * @param {boolean} visible - Whether the instance is visible or not.
  20602. * @return {BatchedMesh} A reference to this batched mesh.
  20603. */
  20604. setVisibleAt( instanceId, visible ) {
  20605. this.validateInstanceId( instanceId );
  20606. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20607. return this;
  20608. }
  20609. this._instanceInfo[ instanceId ].visible = visible;
  20610. this._visibilityChanged = true;
  20611. return this;
  20612. }
  20613. /**
  20614. * Returns the visibility state of the defined instance.
  20615. *
  20616. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20617. * @return {boolean} Whether the instance is visible or not.
  20618. */
  20619. getVisibleAt( instanceId ) {
  20620. this.validateInstanceId( instanceId );
  20621. return this._instanceInfo[ instanceId ].visible;
  20622. }
  20623. /**
  20624. * Sets the geometry ID of the instance at the given index.
  20625. *
  20626. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20627. * @param {number} geometryId - The geometry ID to be use by the instance.
  20628. * @return {BatchedMesh} A reference to this batched mesh.
  20629. */
  20630. setGeometryIdAt( instanceId, geometryId ) {
  20631. this.validateInstanceId( instanceId );
  20632. this.validateGeometryId( geometryId );
  20633. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20634. return this;
  20635. }
  20636. /**
  20637. * Returns the geometry ID of the defined instance.
  20638. *
  20639. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20640. * @return {number} The instance's geometry ID.
  20641. */
  20642. getGeometryIdAt( instanceId ) {
  20643. this.validateInstanceId( instanceId );
  20644. return this._instanceInfo[ instanceId ].geometryIndex;
  20645. }
  20646. /**
  20647. * Get the range representing the subset of triangles related to the attached geometry,
  20648. * indicating the starting offset and count, or `null` if invalid.
  20649. *
  20650. * @param {number} geometryId - The id of the geometry to get the range of.
  20651. * @param {Object} [target] - The target object that is used to store the method's result.
  20652. * @return {{
  20653. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20654. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20655. * start:number,count:number
  20656. * }} The result object with range data.
  20657. */
  20658. getGeometryRangeAt( geometryId, target = {} ) {
  20659. this.validateGeometryId( geometryId );
  20660. const geometryInfo = this._geometryInfo[ geometryId ];
  20661. target.vertexStart = geometryInfo.vertexStart;
  20662. target.vertexCount = geometryInfo.vertexCount;
  20663. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20664. target.indexStart = geometryInfo.indexStart;
  20665. target.indexCount = geometryInfo.indexCount;
  20666. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20667. target.start = geometryInfo.start;
  20668. target.count = geometryInfo.count;
  20669. return target;
  20670. }
  20671. /**
  20672. * Resizes the necessary buffers to support the provided number of instances.
  20673. * If the provided arguments shrink the number of instances but there are not enough
  20674. * unused Ids at the end of the list then an error is thrown.
  20675. *
  20676. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20677. */
  20678. setInstanceCount( maxInstanceCount ) {
  20679. // shrink the available instances as much as possible
  20680. const availableInstanceIds = this._availableInstanceIds;
  20681. const instanceInfo = this._instanceInfo;
  20682. availableInstanceIds.sort( ascIdSort );
  20683. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20684. instanceInfo.pop();
  20685. availableInstanceIds.pop();
  20686. }
  20687. // throw an error if it can't be shrunk to the desired size
  20688. if ( maxInstanceCount < instanceInfo.length ) {
  20689. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20690. }
  20691. // copy the multi draw counts
  20692. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20693. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20694. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20695. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20696. this._multiDrawCounts = multiDrawCounts;
  20697. this._multiDrawStarts = multiDrawStarts;
  20698. this._maxInstanceCount = maxInstanceCount;
  20699. // update texture data for instance sampling
  20700. const indirectTexture = this._indirectTexture;
  20701. const matricesTexture = this._matricesTexture;
  20702. const colorsTexture = this._colorsTexture;
  20703. indirectTexture.dispose();
  20704. this._initIndirectTexture();
  20705. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20706. matricesTexture.dispose();
  20707. this._initMatricesTexture();
  20708. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20709. if ( colorsTexture ) {
  20710. colorsTexture.dispose();
  20711. this._initColorsTexture();
  20712. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20713. }
  20714. }
  20715. /**
  20716. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20717. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20718. * end of the geometry attributes then an error is thrown.
  20719. *
  20720. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20721. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20722. */
  20723. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20724. // Check if we can shrink to the requested vertex attribute size
  20725. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20726. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20727. if ( requiredVertexLength > maxVertexCount ) {
  20728. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20729. }
  20730. // Check if we can shrink to the requested index attribute size
  20731. if ( this.geometry.index ) {
  20732. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20733. if ( requiredIndexLength > maxIndexCount ) {
  20734. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20735. }
  20736. }
  20737. //
  20738. // dispose of the previous geometry
  20739. const oldGeometry = this.geometry;
  20740. oldGeometry.dispose();
  20741. // recreate the geometry needed based on the previous variant
  20742. this._maxVertexCount = maxVertexCount;
  20743. this._maxIndexCount = maxIndexCount;
  20744. if ( this._geometryInitialized ) {
  20745. this._geometryInitialized = false;
  20746. this.geometry = new BufferGeometry();
  20747. this._initializeGeometry( oldGeometry );
  20748. }
  20749. // copy data from the previous geometry
  20750. const geometry = this.geometry;
  20751. if ( oldGeometry.index ) {
  20752. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20753. }
  20754. for ( const key in oldGeometry.attributes ) {
  20755. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20756. }
  20757. }
  20758. raycast( raycaster, intersects ) {
  20759. const instanceInfo = this._instanceInfo;
  20760. const geometryInfoList = this._geometryInfo;
  20761. const matrixWorld = this.matrixWorld;
  20762. const batchGeometry = this.geometry;
  20763. // iterate over each geometry
  20764. _mesh.material = this.material;
  20765. _mesh.geometry.index = batchGeometry.index;
  20766. _mesh.geometry.attributes = batchGeometry.attributes;
  20767. if ( _mesh.geometry.boundingBox === null ) {
  20768. _mesh.geometry.boundingBox = new Box3();
  20769. }
  20770. if ( _mesh.geometry.boundingSphere === null ) {
  20771. _mesh.geometry.boundingSphere = new Sphere();
  20772. }
  20773. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20774. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20775. continue;
  20776. }
  20777. const geometryId = instanceInfo[ i ].geometryIndex;
  20778. const geometryInfo = geometryInfoList[ geometryId ];
  20779. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20780. // get the intersects
  20781. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20782. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20783. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20784. _mesh.raycast( raycaster, _batchIntersects );
  20785. // add batch id to the intersects
  20786. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20787. const intersect = _batchIntersects[ j ];
  20788. intersect.object = this;
  20789. intersect.batchId = i;
  20790. intersects.push( intersect );
  20791. }
  20792. _batchIntersects.length = 0;
  20793. }
  20794. _mesh.material = null;
  20795. _mesh.geometry.index = null;
  20796. _mesh.geometry.attributes = {};
  20797. _mesh.geometry.setDrawRange( 0, Infinity );
  20798. }
  20799. copy( source ) {
  20800. super.copy( source );
  20801. this.geometry = source.geometry.clone();
  20802. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20803. this.sortObjects = source.sortObjects;
  20804. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20805. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20806. this._geometryInfo = source._geometryInfo.map( info => ( {
  20807. ...info,
  20808. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20809. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20810. } ) );
  20811. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20812. this._availableInstanceIds = source._availableInstanceIds.slice();
  20813. this._availableGeometryIds = source._availableGeometryIds.slice();
  20814. this._nextIndexStart = source._nextIndexStart;
  20815. this._nextVertexStart = source._nextVertexStart;
  20816. this._geometryCount = source._geometryCount;
  20817. this._maxInstanceCount = source._maxInstanceCount;
  20818. this._maxVertexCount = source._maxVertexCount;
  20819. this._maxIndexCount = source._maxIndexCount;
  20820. this._geometryInitialized = source._geometryInitialized;
  20821. this._multiDrawCounts = source._multiDrawCounts.slice();
  20822. this._multiDrawStarts = source._multiDrawStarts.slice();
  20823. this._indirectTexture = source._indirectTexture.clone();
  20824. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20825. this._matricesTexture = source._matricesTexture.clone();
  20826. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20827. if ( this._colorsTexture !== null ) {
  20828. this._colorsTexture = source._colorsTexture.clone();
  20829. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20830. }
  20831. return this;
  20832. }
  20833. /**
  20834. * Frees the GPU-related resources allocated by this instance. Call this
  20835. * method whenever this instance is no longer used in your app.
  20836. */
  20837. dispose() {
  20838. // Assuming the geometry is not shared with other meshes
  20839. this.geometry.dispose();
  20840. this._matricesTexture.dispose();
  20841. this._matricesTexture = null;
  20842. this._indirectTexture.dispose();
  20843. this._indirectTexture = null;
  20844. if ( this._colorsTexture !== null ) {
  20845. this._colorsTexture.dispose();
  20846. this._colorsTexture = null;
  20847. }
  20848. }
  20849. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20850. // if visibility has not changed and frustum culling and object sorting is not required
  20851. // then skip iterating over all items
  20852. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20853. return;
  20854. }
  20855. // the indexed version of the multi draw function requires specifying the start
  20856. // offset in bytes.
  20857. const index = geometry.getIndex();
  20858. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20859. const instanceInfo = this._instanceInfo;
  20860. const multiDrawStarts = this._multiDrawStarts;
  20861. const multiDrawCounts = this._multiDrawCounts;
  20862. const geometryInfoList = this._geometryInfo;
  20863. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20864. const indirectTexture = this._indirectTexture;
  20865. const indirectArray = indirectTexture.image.data;
  20866. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20867. // prepare the frustum in the local frame
  20868. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20869. _matrix$1
  20870. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20871. .multiply( this.matrixWorld );
  20872. _frustum.setFromProjectionMatrix(
  20873. _matrix$1,
  20874. camera.coordinateSystem,
  20875. camera.reversedDepth
  20876. );
  20877. }
  20878. let multiDrawCount = 0;
  20879. if ( this.sortObjects ) {
  20880. // get the camera position in the local frame
  20881. _matrix$1.copy( this.matrixWorld ).invert();
  20882. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20883. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20884. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20885. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20886. const geometryId = instanceInfo[ i ].geometryIndex;
  20887. // get the bounds in world space
  20888. this.getMatrixAt( i, _matrix$1 );
  20889. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20890. // determine whether the batched geometry is within the frustum
  20891. let culled = false;
  20892. if ( perObjectFrustumCulled ) {
  20893. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20894. }
  20895. if ( ! culled ) {
  20896. // get the distance from camera used for sorting
  20897. const geometryInfo = geometryInfoList[ geometryId ];
  20898. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20899. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20900. }
  20901. }
  20902. }
  20903. // Sort the draw ranges and prep for rendering
  20904. const list = _renderList.list;
  20905. const customSort = this.customSort;
  20906. if ( customSort === null ) {
  20907. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20908. } else {
  20909. customSort.call( this, list, camera );
  20910. }
  20911. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20912. const item = list[ i ];
  20913. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20914. multiDrawCounts[ multiDrawCount ] = item.count;
  20915. indirectArray[ multiDrawCount ] = item.index;
  20916. multiDrawCount ++;
  20917. }
  20918. _renderList.reset();
  20919. } else {
  20920. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20921. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20922. const geometryId = instanceInfo[ i ].geometryIndex;
  20923. // determine whether the batched geometry is within the frustum
  20924. let culled = false;
  20925. if ( perObjectFrustumCulled ) {
  20926. // get the bounds in world space
  20927. this.getMatrixAt( i, _matrix$1 );
  20928. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20929. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20930. }
  20931. if ( ! culled ) {
  20932. const geometryInfo = geometryInfoList[ geometryId ];
  20933. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20934. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20935. indirectArray[ multiDrawCount ] = i;
  20936. multiDrawCount ++;
  20937. }
  20938. }
  20939. }
  20940. }
  20941. indirectTexture.needsUpdate = true;
  20942. this._multiDrawCount = multiDrawCount;
  20943. this._visibilityChanged = false;
  20944. }
  20945. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20946. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20947. }
  20948. }
  20949. /**
  20950. * A material for rendering line primitives.
  20951. *
  20952. * Materials define the appearance of renderable 3D objects.
  20953. *
  20954. * ```js
  20955. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20956. * ```
  20957. *
  20958. * @augments Material
  20959. */
  20960. class LineBasicMaterial extends Material {
  20961. /**
  20962. * Constructs a new line basic material.
  20963. *
  20964. * @param {Object} [parameters] - An object with one or more properties
  20965. * defining the material's appearance. Any property of the material
  20966. * (including any property from inherited materials) can be passed
  20967. * in here. Color values can be passed any type of value accepted
  20968. * by {@link Color#set}.
  20969. */
  20970. constructor( parameters ) {
  20971. super();
  20972. /**
  20973. * This flag can be used for type testing.
  20974. *
  20975. * @type {boolean}
  20976. * @readonly
  20977. * @default true
  20978. */
  20979. this.isLineBasicMaterial = true;
  20980. this.type = 'LineBasicMaterial';
  20981. /**
  20982. * Color of the material.
  20983. *
  20984. * @type {Color}
  20985. * @default (1,1,1)
  20986. */
  20987. this.color = new Color( 0xffffff );
  20988. /**
  20989. * Sets the color of the lines using data from a texture. The texture map
  20990. * color is modulated by the diffuse `color`.
  20991. *
  20992. * @type {?Texture}
  20993. * @default null
  20994. */
  20995. this.map = null;
  20996. /**
  20997. * Controls line thickness or lines.
  20998. *
  20999. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21000. * ignore this setting and always render line primitives with a
  21001. * width of one pixel.
  21002. *
  21003. * @type {number}
  21004. * @default 1
  21005. */
  21006. this.linewidth = 1;
  21007. /**
  21008. * Defines appearance of line ends.
  21009. *
  21010. * Can only be used with {@link SVGRenderer}.
  21011. *
  21012. * @type {('butt'|'round'|'square')}
  21013. * @default 'round'
  21014. */
  21015. this.linecap = 'round';
  21016. /**
  21017. * Defines appearance of line joints.
  21018. *
  21019. * Can only be used with {@link SVGRenderer}.
  21020. *
  21021. * @type {('round'|'bevel'|'miter')}
  21022. * @default 'round'
  21023. */
  21024. this.linejoin = 'round';
  21025. /**
  21026. * Whether the material is affected by fog or not.
  21027. *
  21028. * @type {boolean}
  21029. * @default true
  21030. */
  21031. this.fog = true;
  21032. this.setValues( parameters );
  21033. }
  21034. copy( source ) {
  21035. super.copy( source );
  21036. this.color.copy( source.color );
  21037. this.map = source.map;
  21038. this.linewidth = source.linewidth;
  21039. this.linecap = source.linecap;
  21040. this.linejoin = source.linejoin;
  21041. this.fog = source.fog;
  21042. return this;
  21043. }
  21044. }
  21045. const _vStart = /*@__PURE__*/ new Vector3();
  21046. const _vEnd = /*@__PURE__*/ new Vector3();
  21047. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21048. const _ray$1 = /*@__PURE__*/ new Ray();
  21049. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21050. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21051. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21052. /**
  21053. * A continuous line. The line are rendered by connecting consecutive
  21054. * vertices with straight lines.
  21055. *
  21056. * ```js
  21057. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21058. *
  21059. * const points = [];
  21060. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21061. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21062. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21063. *
  21064. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21065. *
  21066. * const line = new THREE.Line( geometry, material );
  21067. * scene.add( line );
  21068. * ```
  21069. *
  21070. * @augments Object3D
  21071. */
  21072. class Line extends Object3D {
  21073. /**
  21074. * Constructs a new line.
  21075. *
  21076. * @param {BufferGeometry} [geometry] - The line geometry.
  21077. * @param {Material|Array<Material>} [material] - The line material.
  21078. */
  21079. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21080. super();
  21081. /**
  21082. * This flag can be used for type testing.
  21083. *
  21084. * @type {boolean}
  21085. * @readonly
  21086. * @default true
  21087. */
  21088. this.isLine = true;
  21089. this.type = 'Line';
  21090. /**
  21091. * The line geometry.
  21092. *
  21093. * @type {BufferGeometry}
  21094. */
  21095. this.geometry = geometry;
  21096. /**
  21097. * The line material.
  21098. *
  21099. * @type {Material|Array<Material>}
  21100. * @default LineBasicMaterial
  21101. */
  21102. this.material = material;
  21103. /**
  21104. * A dictionary representing the morph targets in the geometry. The key is the
  21105. * morph targets name, the value its attribute index. This member is `undefined`
  21106. * by default and only set when morph targets are detected in the geometry.
  21107. *
  21108. * @type {Object<String,number>|undefined}
  21109. * @default undefined
  21110. */
  21111. this.morphTargetDictionary = undefined;
  21112. /**
  21113. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21114. * is applied. This member is `undefined` by default and only set when morph targets are
  21115. * detected in the geometry.
  21116. *
  21117. * @type {Array<number>|undefined}
  21118. * @default undefined
  21119. */
  21120. this.morphTargetInfluences = undefined;
  21121. this.updateMorphTargets();
  21122. }
  21123. copy( source, recursive ) {
  21124. super.copy( source, recursive );
  21125. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21126. this.geometry = source.geometry;
  21127. return this;
  21128. }
  21129. /**
  21130. * Computes an array of distance values which are necessary for rendering dashed lines.
  21131. * For each vertex in the geometry, the method calculates the cumulative length from the
  21132. * current point to the very beginning of the line.
  21133. *
  21134. * @return {Line} A reference to this line.
  21135. */
  21136. computeLineDistances() {
  21137. const geometry = this.geometry;
  21138. // we assume non-indexed geometry
  21139. if ( geometry.index === null ) {
  21140. const positionAttribute = geometry.attributes.position;
  21141. const lineDistances = [ 0 ];
  21142. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21143. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21144. _vEnd.fromBufferAttribute( positionAttribute, i );
  21145. lineDistances[ i ] = lineDistances[ i - 1 ];
  21146. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21147. }
  21148. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21149. } else {
  21150. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21151. }
  21152. return this;
  21153. }
  21154. /**
  21155. * Computes intersection points between a casted ray and this line.
  21156. *
  21157. * @param {Raycaster} raycaster - The raycaster.
  21158. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21159. */
  21160. raycast( raycaster, intersects ) {
  21161. const geometry = this.geometry;
  21162. const matrixWorld = this.matrixWorld;
  21163. const threshold = raycaster.params.Line.threshold;
  21164. const drawRange = geometry.drawRange;
  21165. // Checking boundingSphere distance to ray
  21166. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21167. _sphere$1.copy( geometry.boundingSphere );
  21168. _sphere$1.applyMatrix4( matrixWorld );
  21169. _sphere$1.radius += threshold;
  21170. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21171. //
  21172. _inverseMatrix$1.copy( matrixWorld ).invert();
  21173. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21174. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21175. const localThresholdSq = localThreshold * localThreshold;
  21176. const step = this.isLineSegments ? 2 : 1;
  21177. const index = geometry.index;
  21178. const attributes = geometry.attributes;
  21179. const positionAttribute = attributes.position;
  21180. if ( index !== null ) {
  21181. const start = Math.max( 0, drawRange.start );
  21182. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21183. for ( let i = start, l = end - 1; i < l; i += step ) {
  21184. const a = index.getX( i );
  21185. const b = index.getX( i + 1 );
  21186. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21187. if ( intersect ) {
  21188. intersects.push( intersect );
  21189. }
  21190. }
  21191. if ( this.isLineLoop ) {
  21192. const a = index.getX( end - 1 );
  21193. const b = index.getX( start );
  21194. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21195. if ( intersect ) {
  21196. intersects.push( intersect );
  21197. }
  21198. }
  21199. } else {
  21200. const start = Math.max( 0, drawRange.start );
  21201. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21202. for ( let i = start, l = end - 1; i < l; i += step ) {
  21203. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21204. if ( intersect ) {
  21205. intersects.push( intersect );
  21206. }
  21207. }
  21208. if ( this.isLineLoop ) {
  21209. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21210. if ( intersect ) {
  21211. intersects.push( intersect );
  21212. }
  21213. }
  21214. }
  21215. }
  21216. /**
  21217. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21218. * to make sure existing morph targets can influence this 3D object.
  21219. */
  21220. updateMorphTargets() {
  21221. const geometry = this.geometry;
  21222. const morphAttributes = geometry.morphAttributes;
  21223. const keys = Object.keys( morphAttributes );
  21224. if ( keys.length > 0 ) {
  21225. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21226. if ( morphAttribute !== undefined ) {
  21227. this.morphTargetInfluences = [];
  21228. this.morphTargetDictionary = {};
  21229. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21230. const name = morphAttribute[ m ].name || String( m );
  21231. this.morphTargetInfluences.push( 0 );
  21232. this.morphTargetDictionary[ name ] = m;
  21233. }
  21234. }
  21235. }
  21236. }
  21237. }
  21238. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21239. const positionAttribute = object.geometry.attributes.position;
  21240. _vStart.fromBufferAttribute( positionAttribute, a );
  21241. _vEnd.fromBufferAttribute( positionAttribute, b );
  21242. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21243. if ( distSq > thresholdSq ) return;
  21244. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21245. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21246. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21247. return {
  21248. distance: distance,
  21249. // What do we want? intersection point on the ray or on the segment??
  21250. // point: raycaster.ray.at( distance ),
  21251. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21252. index: i,
  21253. face: null,
  21254. faceIndex: null,
  21255. barycoord: null,
  21256. object: object
  21257. };
  21258. }
  21259. const _start = /*@__PURE__*/ new Vector3();
  21260. const _end = /*@__PURE__*/ new Vector3();
  21261. /**
  21262. * A series of lines drawn between pairs of vertices.
  21263. *
  21264. * @augments Line
  21265. */
  21266. class LineSegments extends Line {
  21267. /**
  21268. * Constructs a new line segments.
  21269. *
  21270. * @param {BufferGeometry} [geometry] - The line geometry.
  21271. * @param {Material|Array<Material>} [material] - The line material.
  21272. */
  21273. constructor( geometry, material ) {
  21274. super( geometry, material );
  21275. /**
  21276. * This flag can be used for type testing.
  21277. *
  21278. * @type {boolean}
  21279. * @readonly
  21280. * @default true
  21281. */
  21282. this.isLineSegments = true;
  21283. this.type = 'LineSegments';
  21284. }
  21285. computeLineDistances() {
  21286. const geometry = this.geometry;
  21287. // we assume non-indexed geometry
  21288. if ( geometry.index === null ) {
  21289. const positionAttribute = geometry.attributes.position;
  21290. const lineDistances = [];
  21291. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21292. _start.fromBufferAttribute( positionAttribute, i );
  21293. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21294. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21295. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21296. }
  21297. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21298. } else {
  21299. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21300. }
  21301. return this;
  21302. }
  21303. }
  21304. /**
  21305. * A continuous line. This is nearly the same as {@link Line} the only difference
  21306. * is that the last vertex is connected with the first vertex in order to close
  21307. * the line to form a loop.
  21308. *
  21309. * @augments Line
  21310. */
  21311. class LineLoop extends Line {
  21312. /**
  21313. * Constructs a new line loop.
  21314. *
  21315. * @param {BufferGeometry} [geometry] - The line geometry.
  21316. * @param {Material|Array<Material>} [material] - The line material.
  21317. */
  21318. constructor( geometry, material ) {
  21319. super( geometry, material );
  21320. /**
  21321. * This flag can be used for type testing.
  21322. *
  21323. * @type {boolean}
  21324. * @readonly
  21325. * @default true
  21326. */
  21327. this.isLineLoop = true;
  21328. this.type = 'LineLoop';
  21329. }
  21330. }
  21331. /**
  21332. * A material for rendering point primitives.
  21333. *
  21334. * Materials define the appearance of renderable 3D objects.
  21335. *
  21336. * ```js
  21337. * const vertices = [];
  21338. *
  21339. * for ( let i = 0; i < 10000; i ++ ) {
  21340. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21341. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21342. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21343. *
  21344. * vertices.push( x, y, z );
  21345. * }
  21346. *
  21347. * const geometry = new THREE.BufferGeometry();
  21348. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21349. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21350. * const points = new THREE.Points( geometry, material );
  21351. * scene.add( points );
  21352. * ```
  21353. *
  21354. * @augments Material
  21355. */
  21356. class PointsMaterial extends Material {
  21357. /**
  21358. * Constructs a new points material.
  21359. *
  21360. * @param {Object} [parameters] - An object with one or more properties
  21361. * defining the material's appearance. Any property of the material
  21362. * (including any property from inherited materials) can be passed
  21363. * in here. Color values can be passed any type of value accepted
  21364. * by {@link Color#set}.
  21365. */
  21366. constructor( parameters ) {
  21367. super();
  21368. /**
  21369. * This flag can be used for type testing.
  21370. *
  21371. * @type {boolean}
  21372. * @readonly
  21373. * @default true
  21374. */
  21375. this.isPointsMaterial = true;
  21376. this.type = 'PointsMaterial';
  21377. /**
  21378. * Color of the material.
  21379. *
  21380. * @type {Color}
  21381. * @default (1,1,1)
  21382. */
  21383. this.color = new Color( 0xffffff );
  21384. /**
  21385. * The color map. May optionally include an alpha channel, typically combined
  21386. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21387. * color is modulated by the diffuse `color`.
  21388. *
  21389. * @type {?Texture}
  21390. * @default null
  21391. */
  21392. this.map = null;
  21393. /**
  21394. * The alpha map is a grayscale texture that controls the opacity across the
  21395. * surface (black: fully transparent; white: fully opaque).
  21396. *
  21397. * Only the color of the texture is used, ignoring the alpha channel if one
  21398. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21399. * when sampling this texture due to the extra bit of precision provided for
  21400. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21401. * luminance/alpha textures will also still work as expected.
  21402. *
  21403. * @type {?Texture}
  21404. * @default null
  21405. */
  21406. this.alphaMap = null;
  21407. /**
  21408. * Defines the size of the points in pixels.
  21409. *
  21410. * 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}.
  21411. *
  21412. * @type {number}
  21413. * @default 1
  21414. */
  21415. this.size = 1;
  21416. /**
  21417. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21418. *
  21419. * @type {boolean}
  21420. * @default true
  21421. */
  21422. this.sizeAttenuation = true;
  21423. /**
  21424. * Whether the material is affected by fog or not.
  21425. *
  21426. * @type {boolean}
  21427. * @default true
  21428. */
  21429. this.fog = true;
  21430. this.setValues( parameters );
  21431. }
  21432. copy( source ) {
  21433. super.copy( source );
  21434. this.color.copy( source.color );
  21435. this.map = source.map;
  21436. this.alphaMap = source.alphaMap;
  21437. this.size = source.size;
  21438. this.sizeAttenuation = source.sizeAttenuation;
  21439. this.fog = source.fog;
  21440. return this;
  21441. }
  21442. }
  21443. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21444. const _ray = /*@__PURE__*/ new Ray();
  21445. const _sphere = /*@__PURE__*/ new Sphere();
  21446. const _position$2 = /*@__PURE__*/ new Vector3();
  21447. /**
  21448. * A class for displaying points or point clouds.
  21449. *
  21450. * @augments Object3D
  21451. */
  21452. class Points extends Object3D {
  21453. /**
  21454. * Constructs a new point cloud.
  21455. *
  21456. * @param {BufferGeometry} [geometry] - The points geometry.
  21457. * @param {Material|Array<Material>} [material] - The points material.
  21458. */
  21459. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21460. super();
  21461. /**
  21462. * This flag can be used for type testing.
  21463. *
  21464. * @type {boolean}
  21465. * @readonly
  21466. * @default true
  21467. */
  21468. this.isPoints = true;
  21469. this.type = 'Points';
  21470. /**
  21471. * The points geometry.
  21472. *
  21473. * @type {BufferGeometry}
  21474. */
  21475. this.geometry = geometry;
  21476. /**
  21477. * The line material.
  21478. *
  21479. * @type {Material|Array<Material>}
  21480. * @default PointsMaterial
  21481. */
  21482. this.material = material;
  21483. /**
  21484. * A dictionary representing the morph targets in the geometry. The key is the
  21485. * morph targets name, the value its attribute index. This member is `undefined`
  21486. * by default and only set when morph targets are detected in the geometry.
  21487. *
  21488. * @type {Object<String,number>|undefined}
  21489. * @default undefined
  21490. */
  21491. this.morphTargetDictionary = undefined;
  21492. /**
  21493. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21494. * is applied. This member is `undefined` by default and only set when morph targets are
  21495. * detected in the geometry.
  21496. *
  21497. * @type {Array<number>|undefined}
  21498. * @default undefined
  21499. */
  21500. this.morphTargetInfluences = undefined;
  21501. this.updateMorphTargets();
  21502. }
  21503. copy( source, recursive ) {
  21504. super.copy( source, recursive );
  21505. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21506. this.geometry = source.geometry;
  21507. return this;
  21508. }
  21509. /**
  21510. * Computes intersection points between a casted ray and this point cloud.
  21511. *
  21512. * @param {Raycaster} raycaster - The raycaster.
  21513. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21514. */
  21515. raycast( raycaster, intersects ) {
  21516. const geometry = this.geometry;
  21517. const matrixWorld = this.matrixWorld;
  21518. const threshold = raycaster.params.Points.threshold;
  21519. const drawRange = geometry.drawRange;
  21520. // Checking boundingSphere distance to ray
  21521. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21522. _sphere.copy( geometry.boundingSphere );
  21523. _sphere.applyMatrix4( matrixWorld );
  21524. _sphere.radius += threshold;
  21525. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21526. //
  21527. _inverseMatrix.copy( matrixWorld ).invert();
  21528. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21529. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21530. const localThresholdSq = localThreshold * localThreshold;
  21531. const index = geometry.index;
  21532. const attributes = geometry.attributes;
  21533. const positionAttribute = attributes.position;
  21534. if ( index !== null ) {
  21535. const start = Math.max( 0, drawRange.start );
  21536. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21537. for ( let i = start, il = end; i < il; i ++ ) {
  21538. const a = index.getX( i );
  21539. _position$2.fromBufferAttribute( positionAttribute, a );
  21540. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21541. }
  21542. } else {
  21543. const start = Math.max( 0, drawRange.start );
  21544. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21545. for ( let i = start, l = end; i < l; i ++ ) {
  21546. _position$2.fromBufferAttribute( positionAttribute, i );
  21547. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21548. }
  21549. }
  21550. }
  21551. /**
  21552. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21553. * to make sure existing morph targets can influence this 3D object.
  21554. */
  21555. updateMorphTargets() {
  21556. const geometry = this.geometry;
  21557. const morphAttributes = geometry.morphAttributes;
  21558. const keys = Object.keys( morphAttributes );
  21559. if ( keys.length > 0 ) {
  21560. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21561. if ( morphAttribute !== undefined ) {
  21562. this.morphTargetInfluences = [];
  21563. this.morphTargetDictionary = {};
  21564. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21565. const name = morphAttribute[ m ].name || String( m );
  21566. this.morphTargetInfluences.push( 0 );
  21567. this.morphTargetDictionary[ name ] = m;
  21568. }
  21569. }
  21570. }
  21571. }
  21572. }
  21573. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21574. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21575. if ( rayPointDistanceSq < localThresholdSq ) {
  21576. const intersectPoint = new Vector3();
  21577. _ray.closestPointToPoint( point, intersectPoint );
  21578. intersectPoint.applyMatrix4( matrixWorld );
  21579. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21580. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21581. intersects.push( {
  21582. distance: distance,
  21583. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21584. point: intersectPoint,
  21585. index: index,
  21586. face: null,
  21587. faceIndex: null,
  21588. barycoord: null,
  21589. object: object
  21590. } );
  21591. }
  21592. }
  21593. /**
  21594. * A texture for use with a video.
  21595. *
  21596. * ```js
  21597. * // assuming you have created a HTML video element with id="video"
  21598. * const video = document.getElementById( 'video' );
  21599. * const texture = new THREE.VideoTexture( video );
  21600. * ```
  21601. *
  21602. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21603. * set to THREE.SRGBColorSpace.
  21604. *
  21605. * Note: After the initial use of a texture, its dimensions, format, and type
  21606. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21607. *
  21608. * @augments Texture
  21609. */
  21610. class VideoTexture extends Texture {
  21611. /**
  21612. * Constructs a new video texture.
  21613. *
  21614. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21615. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21616. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21617. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21618. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21619. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21620. * @param {number} [format=RGBAFormat] - The texture format.
  21621. * @param {number} [type=UnsignedByteType] - The texture type.
  21622. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21623. */
  21624. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21625. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21626. /**
  21627. * This flag can be used for type testing.
  21628. *
  21629. * @type {boolean}
  21630. * @readonly
  21631. * @default true
  21632. */
  21633. this.isVideoTexture = true;
  21634. /**
  21635. * Whether to generate mipmaps (if possible) for a texture.
  21636. *
  21637. * Overwritten and set to `false` by default.
  21638. *
  21639. * @type {boolean}
  21640. * @default false
  21641. */
  21642. this.generateMipmaps = false;
  21643. /**
  21644. * The video frame request callback identifier, which is a positive integer.
  21645. *
  21646. * Value of 0 represents no scheduled rVFC.
  21647. *
  21648. * @private
  21649. * @type {number}
  21650. */
  21651. this._requestVideoFrameCallbackId = 0;
  21652. const scope = this;
  21653. function updateVideo() {
  21654. scope.needsUpdate = true;
  21655. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21656. }
  21657. if ( 'requestVideoFrameCallback' in video ) {
  21658. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21659. }
  21660. }
  21661. clone() {
  21662. return new this.constructor( this.image ).copy( this );
  21663. }
  21664. /**
  21665. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21666. * to `true` every time a new frame is available.
  21667. *
  21668. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21669. */
  21670. update() {
  21671. const video = this.image;
  21672. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21673. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21674. this.needsUpdate = true;
  21675. }
  21676. }
  21677. /**
  21678. * @override
  21679. */
  21680. dispose() {
  21681. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21682. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21683. }
  21684. super.dispose();
  21685. }
  21686. }
  21687. /**
  21688. * This class can be used as an alternative way to define video data. Instead of using
  21689. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21690. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21691. * video frames are decoded with the WebCodecs API.
  21692. *
  21693. * ```js
  21694. * const texture = new THREE.VideoFrameTexture();
  21695. * texture.setFrame( frame );
  21696. * ```
  21697. *
  21698. * @augments VideoTexture
  21699. */
  21700. class VideoFrameTexture extends VideoTexture {
  21701. /**
  21702. * Constructs a new video frame texture.
  21703. *
  21704. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21705. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21706. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21707. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21708. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21709. * @param {number} [format=RGBAFormat] - The texture format.
  21710. * @param {number} [type=UnsignedByteType] - The texture type.
  21711. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21712. */
  21713. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21714. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21715. /**
  21716. * This flag can be used for type testing.
  21717. *
  21718. * @type {boolean}
  21719. * @readonly
  21720. * @default true
  21721. */
  21722. this.isVideoFrameTexture = true;
  21723. }
  21724. /**
  21725. * This method overwritten with an empty implementation since
  21726. * this type of texture is updated via `setFrame()`.
  21727. */
  21728. update() {}
  21729. clone() {
  21730. return new this.constructor().copy( this ); // restoring Texture.clone()
  21731. }
  21732. /**
  21733. * Sets the current frame of the video. This will automatically update the texture
  21734. * so the data can be used for rendering.
  21735. *
  21736. * @param {VideoFrame} frame - The video frame.
  21737. */
  21738. setFrame( frame ) {
  21739. this.image = frame;
  21740. this.needsUpdate = true;
  21741. }
  21742. }
  21743. /**
  21744. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21745. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21746. * as a texture for further usage.
  21747. *
  21748. * ```js
  21749. * const pixelRatio = window.devicePixelRatio;
  21750. * const textureSize = 128 * pixelRatio;
  21751. *
  21752. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21753. *
  21754. * // calculate start position for copying part of the frame data
  21755. * const vector = new Vector2();
  21756. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21757. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21758. *
  21759. * renderer.render( scene, camera );
  21760. *
  21761. * // copy part of the rendered frame into the framebuffer texture
  21762. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21763. * ```
  21764. *
  21765. * @augments Texture
  21766. */
  21767. class FramebufferTexture extends Texture {
  21768. /**
  21769. * Constructs a new framebuffer texture.
  21770. *
  21771. * @param {number} [width] - The width of the texture.
  21772. * @param {number} [height] - The height of the texture.
  21773. */
  21774. constructor( width, height ) {
  21775. super( { width, height } );
  21776. /**
  21777. * This flag can be used for type testing.
  21778. *
  21779. * @type {boolean}
  21780. * @readonly
  21781. * @default true
  21782. */
  21783. this.isFramebufferTexture = true;
  21784. /**
  21785. * How the texture is sampled when a texel covers more than one pixel.
  21786. *
  21787. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21788. *
  21789. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21790. * @default NearestFilter
  21791. */
  21792. this.magFilter = NearestFilter;
  21793. /**
  21794. * How the texture is sampled when a texel covers less than one pixel.
  21795. *
  21796. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21797. *
  21798. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21799. * @default NearestFilter
  21800. */
  21801. this.minFilter = NearestFilter;
  21802. /**
  21803. * Whether to generate mipmaps (if possible) for a texture.
  21804. *
  21805. * Overwritten and set to `false` by default.
  21806. *
  21807. * @type {boolean}
  21808. * @default false
  21809. */
  21810. this.generateMipmaps = false;
  21811. this.needsUpdate = true;
  21812. }
  21813. }
  21814. /**
  21815. * Creates a texture based on data in compressed form.
  21816. *
  21817. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21818. *
  21819. * @augments Texture
  21820. */
  21821. class CompressedTexture extends Texture {
  21822. /**
  21823. * Constructs a new compressed texture.
  21824. *
  21825. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21826. * the data and dimensions.
  21827. * @param {number} width - The width of the texture.
  21828. * @param {number} height - The height of the texture.
  21829. * @param {number} [format=RGBAFormat] - The texture format.
  21830. * @param {number} [type=UnsignedByteType] - The texture type.
  21831. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21832. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21833. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21834. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21835. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21836. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21837. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21838. */
  21839. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21840. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21841. /**
  21842. * This flag can be used for type testing.
  21843. *
  21844. * @type {boolean}
  21845. * @readonly
  21846. * @default true
  21847. */
  21848. this.isCompressedTexture = true;
  21849. /**
  21850. * The image property of a compressed texture just defines its dimensions.
  21851. *
  21852. * @type {{width:number,height:number}}
  21853. */
  21854. this.image = { width: width, height: height };
  21855. /**
  21856. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21857. *
  21858. * @type {Array<Object>}
  21859. */
  21860. this.mipmaps = mipmaps;
  21861. /**
  21862. * If set to `true`, the texture is flipped along the vertical axis when
  21863. * uploaded to the GPU.
  21864. *
  21865. * Overwritten and set to `false` by default since it is not possible to
  21866. * flip compressed textures.
  21867. *
  21868. * @type {boolean}
  21869. * @default false
  21870. * @readonly
  21871. */
  21872. this.flipY = false;
  21873. /**
  21874. * Whether to generate mipmaps (if possible) for a texture.
  21875. *
  21876. * Overwritten and set to `false` by default since it is not
  21877. * possible to generate mipmaps for compressed data. Mipmaps
  21878. * must be embedded in the compressed texture file.
  21879. *
  21880. * @type {boolean}
  21881. * @default false
  21882. * @readonly
  21883. */
  21884. this.generateMipmaps = false;
  21885. }
  21886. }
  21887. /**
  21888. * Creates a texture 2D array based on data in compressed form.
  21889. *
  21890. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21891. *
  21892. * @augments CompressedTexture
  21893. */
  21894. class CompressedArrayTexture extends CompressedTexture {
  21895. /**
  21896. * Constructs a new compressed array texture.
  21897. *
  21898. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21899. * the data and dimensions.
  21900. * @param {number} width - The width of the texture.
  21901. * @param {number} height - The height of the texture.
  21902. * @param {number} depth - The depth of the texture.
  21903. * @param {number} [format=RGBAFormat] - The min filter value.
  21904. * @param {number} [type=UnsignedByteType] - The min filter value.
  21905. */
  21906. constructor( mipmaps, width, height, depth, format, type ) {
  21907. super( mipmaps, width, height, format, type );
  21908. /**
  21909. * This flag can be used for type testing.
  21910. *
  21911. * @type {boolean}
  21912. * @readonly
  21913. * @default true
  21914. */
  21915. this.isCompressedArrayTexture = true;
  21916. /**
  21917. * The image property of a compressed texture just defines its dimensions.
  21918. *
  21919. * @name CompressedArrayTexture#image
  21920. * @type {{width:number,height:number,depth:number}}
  21921. */
  21922. this.image.depth = depth;
  21923. /**
  21924. * This defines how the texture is wrapped in the depth and corresponds to
  21925. * *W* in UVW mapping.
  21926. *
  21927. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21928. * @default ClampToEdgeWrapping
  21929. */
  21930. this.wrapR = ClampToEdgeWrapping;
  21931. /**
  21932. * A set of all layers which need to be updated in the texture.
  21933. *
  21934. * @type {Set<number>}
  21935. */
  21936. this.layerUpdates = new Set();
  21937. }
  21938. /**
  21939. * Describes that a specific layer of the texture needs to be updated.
  21940. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21941. * entire compressed texture array is sent to the GPU. Marking specific
  21942. * layers will only transmit subsets of all mipmaps associated with a
  21943. * specific depth in the array which is often much more performant.
  21944. *
  21945. * @param {number} layerIndex - The layer index that should be updated.
  21946. */
  21947. addLayerUpdate( layerIndex ) {
  21948. this.layerUpdates.add( layerIndex );
  21949. }
  21950. /**
  21951. * Resets the layer updates registry.
  21952. */
  21953. clearLayerUpdates() {
  21954. this.layerUpdates.clear();
  21955. }
  21956. }
  21957. /**
  21958. * Creates a cube texture based on data in compressed form.
  21959. *
  21960. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21961. *
  21962. * @augments CompressedTexture
  21963. */
  21964. class CompressedCubeTexture extends CompressedTexture {
  21965. /**
  21966. * Constructs a new compressed texture.
  21967. *
  21968. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21969. * @param {number} [format=RGBAFormat] - The texture format.
  21970. * @param {number} [type=UnsignedByteType] - The texture type.
  21971. */
  21972. constructor( images, format, type ) {
  21973. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21974. /**
  21975. * This flag can be used for type testing.
  21976. *
  21977. * @type {boolean}
  21978. * @readonly
  21979. * @default true
  21980. */
  21981. this.isCompressedCubeTexture = true;
  21982. /**
  21983. * This flag can be used for type testing.
  21984. *
  21985. * @type {boolean}
  21986. * @readonly
  21987. * @default true
  21988. */
  21989. this.isCubeTexture = true;
  21990. this.image = images;
  21991. }
  21992. }
  21993. /**
  21994. * Creates a texture from a canvas element.
  21995. *
  21996. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21997. * to `true` immediately since a canvas can directly be used for rendering.
  21998. *
  21999. * @augments Texture
  22000. */
  22001. class CanvasTexture extends Texture {
  22002. /**
  22003. * Constructs a new texture.
  22004. *
  22005. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22006. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22007. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22008. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22009. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22010. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22011. * @param {number} [format=RGBAFormat] - The texture format.
  22012. * @param {number} [type=UnsignedByteType] - The texture type.
  22013. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22014. */
  22015. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22016. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22017. /**
  22018. * This flag can be used for type testing.
  22019. *
  22020. * @type {boolean}
  22021. * @readonly
  22022. * @default true
  22023. */
  22024. this.isCanvasTexture = true;
  22025. this.needsUpdate = true;
  22026. }
  22027. }
  22028. /**
  22029. * This class can be used to automatically save the depth information of a
  22030. * rendering into a texture.
  22031. *
  22032. * @augments Texture
  22033. */
  22034. class DepthTexture extends Texture {
  22035. /**
  22036. * Constructs a new depth texture.
  22037. *
  22038. * @param {number} width - The width of the texture.
  22039. * @param {number} height - The height of the texture.
  22040. * @param {number} [type=UnsignedIntType] - The texture type.
  22041. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22042. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22043. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22044. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22045. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22046. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22047. * @param {number} [format=DepthFormat] - The texture format.
  22048. * @param {number} [depth=1] - The depth of the texture.
  22049. */
  22050. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22051. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22052. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22053. }
  22054. const image = { width: width, height: height, depth: depth };
  22055. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22056. /**
  22057. * This flag can be used for type testing.
  22058. *
  22059. * @type {boolean}
  22060. * @readonly
  22061. * @default true
  22062. */
  22063. this.isDepthTexture = true;
  22064. /**
  22065. * If set to `true`, the texture is flipped along the vertical axis when
  22066. * uploaded to the GPU.
  22067. *
  22068. * Overwritten and set to `false` by default.
  22069. *
  22070. * @type {boolean}
  22071. * @default false
  22072. */
  22073. this.flipY = false;
  22074. /**
  22075. * Whether to generate mipmaps (if possible) for a texture.
  22076. *
  22077. * Overwritten and set to `false` by default.
  22078. *
  22079. * @type {boolean}
  22080. * @default false
  22081. */
  22082. this.generateMipmaps = false;
  22083. /**
  22084. * Code corresponding to the depth compare function.
  22085. *
  22086. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22087. * @default null
  22088. */
  22089. this.compareFunction = null;
  22090. }
  22091. copy( source ) {
  22092. super.copy( source );
  22093. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22094. this.compareFunction = source.compareFunction;
  22095. return this;
  22096. }
  22097. toJSON( meta ) {
  22098. const data = super.toJSON( meta );
  22099. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22100. return data;
  22101. }
  22102. }
  22103. /**
  22104. * A geometry class for representing a capsule.
  22105. *
  22106. * ```js
  22107. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22108. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22109. * const capsule = new THREE.Mesh( geometry, material );
  22110. * scene.add( capsule );
  22111. * ```
  22112. *
  22113. * @augments BufferGeometry
  22114. */
  22115. class CapsuleGeometry extends BufferGeometry {
  22116. /**
  22117. * Constructs a new capsule geometry.
  22118. *
  22119. * @param {number} [radius=1] - Radius of the capsule.
  22120. * @param {number} [height=1] - Height of the middle section.
  22121. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22122. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22123. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22124. */
  22125. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22126. super();
  22127. this.type = 'CapsuleGeometry';
  22128. /**
  22129. * Holds the constructor parameters that have been
  22130. * used to generate the geometry. Any modification
  22131. * after instantiation does not change the geometry.
  22132. *
  22133. * @type {Object}
  22134. */
  22135. this.parameters = {
  22136. radius: radius,
  22137. height: height,
  22138. capSegments: capSegments,
  22139. radialSegments: radialSegments,
  22140. heightSegments: heightSegments,
  22141. };
  22142. height = Math.max( 0, height );
  22143. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22144. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22145. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22146. // buffers
  22147. const indices = [];
  22148. const vertices = [];
  22149. const normals = [];
  22150. const uvs = [];
  22151. // helper variables
  22152. const halfHeight = height / 2;
  22153. const capArcLength = ( Math.PI / 2 ) * radius;
  22154. const cylinderPartLength = height;
  22155. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22156. const numVerticalSegments = capSegments * 2 + heightSegments;
  22157. const verticesPerRow = radialSegments + 1;
  22158. const normal = new Vector3();
  22159. const vertex = new Vector3();
  22160. // generate vertices, normals, and uvs
  22161. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22162. let currentArcLength = 0;
  22163. let profileY = 0;
  22164. let profileRadius = 0;
  22165. let normalYComponent = 0;
  22166. if ( iy <= capSegments ) {
  22167. // bottom cap
  22168. const segmentProgress = iy / capSegments;
  22169. const angle = ( segmentProgress * Math.PI ) / 2;
  22170. profileY = - halfHeight - radius * Math.cos( angle );
  22171. profileRadius = radius * Math.sin( angle );
  22172. normalYComponent = - radius * Math.cos( angle );
  22173. currentArcLength = segmentProgress * capArcLength;
  22174. } else if ( iy <= capSegments + heightSegments ) {
  22175. // middle section
  22176. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22177. profileY = - halfHeight + segmentProgress * height;
  22178. profileRadius = radius;
  22179. normalYComponent = 0;
  22180. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22181. } else {
  22182. // top cap
  22183. const segmentProgress =
  22184. ( iy - capSegments - heightSegments ) / capSegments;
  22185. const angle = ( segmentProgress * Math.PI ) / 2;
  22186. profileY = halfHeight + radius * Math.sin( angle );
  22187. profileRadius = radius * Math.cos( angle );
  22188. normalYComponent = radius * Math.sin( angle );
  22189. currentArcLength =
  22190. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22191. }
  22192. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22193. // special case for the poles
  22194. let uOffset = 0;
  22195. if ( iy === 0 ) {
  22196. uOffset = 0.5 / radialSegments;
  22197. } else if ( iy === numVerticalSegments ) {
  22198. uOffset = -0.5 / radialSegments;
  22199. }
  22200. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22201. const u = ix / radialSegments;
  22202. const theta = u * Math.PI * 2;
  22203. const sinTheta = Math.sin( theta );
  22204. const cosTheta = Math.cos( theta );
  22205. // vertex
  22206. vertex.x = - profileRadius * cosTheta;
  22207. vertex.y = profileY;
  22208. vertex.z = profileRadius * sinTheta;
  22209. vertices.push( vertex.x, vertex.y, vertex.z );
  22210. // normal
  22211. normal.set(
  22212. - profileRadius * cosTheta,
  22213. normalYComponent,
  22214. profileRadius * sinTheta
  22215. );
  22216. normal.normalize();
  22217. normals.push( normal.x, normal.y, normal.z );
  22218. // uv
  22219. uvs.push( u + uOffset, v );
  22220. }
  22221. if ( iy > 0 ) {
  22222. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22223. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22224. const i1 = prevIndexRow + ix;
  22225. const i2 = prevIndexRow + ix + 1;
  22226. const i3 = iy * verticesPerRow + ix;
  22227. const i4 = iy * verticesPerRow + ix + 1;
  22228. indices.push( i1, i2, i3 );
  22229. indices.push( i2, i4, i3 );
  22230. }
  22231. }
  22232. }
  22233. // build geometry
  22234. this.setIndex( indices );
  22235. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22236. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22237. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22238. }
  22239. copy( source ) {
  22240. super.copy( source );
  22241. this.parameters = Object.assign( {}, source.parameters );
  22242. return this;
  22243. }
  22244. /**
  22245. * Factory method for creating an instance of this class from the given
  22246. * JSON object.
  22247. *
  22248. * @param {Object} data - A JSON object representing the serialized geometry.
  22249. * @return {CapsuleGeometry} A new instance.
  22250. */
  22251. static fromJSON( data ) {
  22252. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22253. }
  22254. }
  22255. /**
  22256. * A simple shape of Euclidean geometry. It is constructed from a
  22257. * number of triangular segments that are oriented around a central point and
  22258. * extend as far out as a given radius. It is built counter-clockwise from a
  22259. * start angle and a given central angle. It can also be used to create
  22260. * regular polygons, where the number of segments determines the number of
  22261. * sides.
  22262. *
  22263. * ```js
  22264. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22265. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22266. * const circle = new THREE.Mesh( geometry, material );
  22267. * scene.add( circle )
  22268. * ```
  22269. *
  22270. * @augments BufferGeometry
  22271. */
  22272. class CircleGeometry extends BufferGeometry {
  22273. /**
  22274. * Constructs a new circle geometry.
  22275. *
  22276. * @param {number} [radius=1] - Radius of the circle.
  22277. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22278. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22279. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22280. * of the circular sector in radians. The default value results in a complete circle.
  22281. */
  22282. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22283. super();
  22284. this.type = 'CircleGeometry';
  22285. /**
  22286. * Holds the constructor parameters that have been
  22287. * used to generate the geometry. Any modification
  22288. * after instantiation does not change the geometry.
  22289. *
  22290. * @type {Object}
  22291. */
  22292. this.parameters = {
  22293. radius: radius,
  22294. segments: segments,
  22295. thetaStart: thetaStart,
  22296. thetaLength: thetaLength
  22297. };
  22298. segments = Math.max( 3, segments );
  22299. // buffers
  22300. const indices = [];
  22301. const vertices = [];
  22302. const normals = [];
  22303. const uvs = [];
  22304. // helper variables
  22305. const vertex = new Vector3();
  22306. const uv = new Vector2();
  22307. // center point
  22308. vertices.push( 0, 0, 0 );
  22309. normals.push( 0, 0, 1 );
  22310. uvs.push( 0.5, 0.5 );
  22311. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22312. const segment = thetaStart + s / segments * thetaLength;
  22313. // vertex
  22314. vertex.x = radius * Math.cos( segment );
  22315. vertex.y = radius * Math.sin( segment );
  22316. vertices.push( vertex.x, vertex.y, vertex.z );
  22317. // normal
  22318. normals.push( 0, 0, 1 );
  22319. // uvs
  22320. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22321. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22322. uvs.push( uv.x, uv.y );
  22323. }
  22324. // indices
  22325. for ( let i = 1; i <= segments; i ++ ) {
  22326. indices.push( i, i + 1, 0 );
  22327. }
  22328. // build geometry
  22329. this.setIndex( indices );
  22330. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22331. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22332. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22333. }
  22334. copy( source ) {
  22335. super.copy( source );
  22336. this.parameters = Object.assign( {}, source.parameters );
  22337. return this;
  22338. }
  22339. /**
  22340. * Factory method for creating an instance of this class from the given
  22341. * JSON object.
  22342. *
  22343. * @param {Object} data - A JSON object representing the serialized geometry.
  22344. * @return {CircleGeometry} A new instance.
  22345. */
  22346. static fromJSON( data ) {
  22347. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22348. }
  22349. }
  22350. /**
  22351. * A geometry class for representing a cylinder.
  22352. *
  22353. * ```js
  22354. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22355. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22356. * const cylinder = new THREE.Mesh( geometry, material );
  22357. * scene.add( cylinder );
  22358. * ```
  22359. *
  22360. * @augments BufferGeometry
  22361. */
  22362. class CylinderGeometry extends BufferGeometry {
  22363. /**
  22364. * Constructs a new cylinder geometry.
  22365. *
  22366. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22367. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22368. * @param {number} [height=1] - Height of the cylinder.
  22369. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22370. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22371. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22372. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22373. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22374. * The default value results in a complete cylinder.
  22375. */
  22376. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22377. super();
  22378. this.type = 'CylinderGeometry';
  22379. /**
  22380. * Holds the constructor parameters that have been
  22381. * used to generate the geometry. Any modification
  22382. * after instantiation does not change the geometry.
  22383. *
  22384. * @type {Object}
  22385. */
  22386. this.parameters = {
  22387. radiusTop: radiusTop,
  22388. radiusBottom: radiusBottom,
  22389. height: height,
  22390. radialSegments: radialSegments,
  22391. heightSegments: heightSegments,
  22392. openEnded: openEnded,
  22393. thetaStart: thetaStart,
  22394. thetaLength: thetaLength
  22395. };
  22396. const scope = this;
  22397. radialSegments = Math.floor( radialSegments );
  22398. heightSegments = Math.floor( heightSegments );
  22399. // buffers
  22400. const indices = [];
  22401. const vertices = [];
  22402. const normals = [];
  22403. const uvs = [];
  22404. // helper variables
  22405. let index = 0;
  22406. const indexArray = [];
  22407. const halfHeight = height / 2;
  22408. let groupStart = 0;
  22409. // generate geometry
  22410. generateTorso();
  22411. if ( openEnded === false ) {
  22412. if ( radiusTop > 0 ) generateCap( true );
  22413. if ( radiusBottom > 0 ) generateCap( false );
  22414. }
  22415. // build geometry
  22416. this.setIndex( indices );
  22417. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22418. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22419. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22420. function generateTorso() {
  22421. const normal = new Vector3();
  22422. const vertex = new Vector3();
  22423. let groupCount = 0;
  22424. // this will be used to calculate the normal
  22425. const slope = ( radiusBottom - radiusTop ) / height;
  22426. // generate vertices, normals and uvs
  22427. for ( let y = 0; y <= heightSegments; y ++ ) {
  22428. const indexRow = [];
  22429. const v = y / heightSegments;
  22430. // calculate the radius of the current row
  22431. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22432. for ( let x = 0; x <= radialSegments; x ++ ) {
  22433. const u = x / radialSegments;
  22434. const theta = u * thetaLength + thetaStart;
  22435. const sinTheta = Math.sin( theta );
  22436. const cosTheta = Math.cos( theta );
  22437. // vertex
  22438. vertex.x = radius * sinTheta;
  22439. vertex.y = - v * height + halfHeight;
  22440. vertex.z = radius * cosTheta;
  22441. vertices.push( vertex.x, vertex.y, vertex.z );
  22442. // normal
  22443. normal.set( sinTheta, slope, cosTheta ).normalize();
  22444. normals.push( normal.x, normal.y, normal.z );
  22445. // uv
  22446. uvs.push( u, 1 - v );
  22447. // save index of vertex in respective row
  22448. indexRow.push( index ++ );
  22449. }
  22450. // now save vertices of the row in our index array
  22451. indexArray.push( indexRow );
  22452. }
  22453. // generate indices
  22454. for ( let x = 0; x < radialSegments; x ++ ) {
  22455. for ( let y = 0; y < heightSegments; y ++ ) {
  22456. // we use the index array to access the correct indices
  22457. const a = indexArray[ y ][ x ];
  22458. const b = indexArray[ y + 1 ][ x ];
  22459. const c = indexArray[ y + 1 ][ x + 1 ];
  22460. const d = indexArray[ y ][ x + 1 ];
  22461. // faces
  22462. if ( radiusTop > 0 || y !== 0 ) {
  22463. indices.push( a, b, d );
  22464. groupCount += 3;
  22465. }
  22466. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22467. indices.push( b, c, d );
  22468. groupCount += 3;
  22469. }
  22470. }
  22471. }
  22472. // add a group to the geometry. this will ensure multi material support
  22473. scope.addGroup( groupStart, groupCount, 0 );
  22474. // calculate new start value for groups
  22475. groupStart += groupCount;
  22476. }
  22477. function generateCap( top ) {
  22478. // save the index of the first center vertex
  22479. const centerIndexStart = index;
  22480. const uv = new Vector2();
  22481. const vertex = new Vector3();
  22482. let groupCount = 0;
  22483. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22484. const sign = ( top === true ) ? 1 : -1;
  22485. // first we generate the center vertex data of the cap.
  22486. // because the geometry needs one set of uvs per face,
  22487. // we must generate a center vertex per face/segment
  22488. for ( let x = 1; x <= radialSegments; x ++ ) {
  22489. // vertex
  22490. vertices.push( 0, halfHeight * sign, 0 );
  22491. // normal
  22492. normals.push( 0, sign, 0 );
  22493. // uv
  22494. uvs.push( 0.5, 0.5 );
  22495. // increase index
  22496. index ++;
  22497. }
  22498. // save the index of the last center vertex
  22499. const centerIndexEnd = index;
  22500. // now we generate the surrounding vertices, normals and uvs
  22501. for ( let x = 0; x <= radialSegments; x ++ ) {
  22502. const u = x / radialSegments;
  22503. const theta = u * thetaLength + thetaStart;
  22504. const cosTheta = Math.cos( theta );
  22505. const sinTheta = Math.sin( theta );
  22506. // vertex
  22507. vertex.x = radius * sinTheta;
  22508. vertex.y = halfHeight * sign;
  22509. vertex.z = radius * cosTheta;
  22510. vertices.push( vertex.x, vertex.y, vertex.z );
  22511. // normal
  22512. normals.push( 0, sign, 0 );
  22513. // uv
  22514. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22515. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22516. uvs.push( uv.x, uv.y );
  22517. // increase index
  22518. index ++;
  22519. }
  22520. // generate indices
  22521. for ( let x = 0; x < radialSegments; x ++ ) {
  22522. const c = centerIndexStart + x;
  22523. const i = centerIndexEnd + x;
  22524. if ( top === true ) {
  22525. // face top
  22526. indices.push( i, i + 1, c );
  22527. } else {
  22528. // face bottom
  22529. indices.push( i + 1, i, c );
  22530. }
  22531. groupCount += 3;
  22532. }
  22533. // add a group to the geometry. this will ensure multi material support
  22534. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22535. // calculate new start value for groups
  22536. groupStart += groupCount;
  22537. }
  22538. }
  22539. copy( source ) {
  22540. super.copy( source );
  22541. this.parameters = Object.assign( {}, source.parameters );
  22542. return this;
  22543. }
  22544. /**
  22545. * Factory method for creating an instance of this class from the given
  22546. * JSON object.
  22547. *
  22548. * @param {Object} data - A JSON object representing the serialized geometry.
  22549. * @return {CylinderGeometry} A new instance.
  22550. */
  22551. static fromJSON( data ) {
  22552. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22553. }
  22554. }
  22555. /**
  22556. * A geometry class for representing a cone.
  22557. *
  22558. * ```js
  22559. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22560. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22561. * const cone = new THREE.Mesh(geometry, material );
  22562. * scene.add( cone );
  22563. * ```
  22564. *
  22565. * @augments CylinderGeometry
  22566. */
  22567. class ConeGeometry extends CylinderGeometry {
  22568. /**
  22569. * Constructs a new cone geometry.
  22570. *
  22571. * @param {number} [radius=1] - Radius of the cone base.
  22572. * @param {number} [height=1] - Height of the cone.
  22573. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22574. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22575. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22576. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22577. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22578. * The default value results in a complete cone.
  22579. */
  22580. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22581. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22582. this.type = 'ConeGeometry';
  22583. /**
  22584. * Holds the constructor parameters that have been
  22585. * used to generate the geometry. Any modification
  22586. * after instantiation does not change the geometry.
  22587. *
  22588. * @type {Object}
  22589. */
  22590. this.parameters = {
  22591. radius: radius,
  22592. height: height,
  22593. radialSegments: radialSegments,
  22594. heightSegments: heightSegments,
  22595. openEnded: openEnded,
  22596. thetaStart: thetaStart,
  22597. thetaLength: thetaLength
  22598. };
  22599. }
  22600. /**
  22601. * Factory method for creating an instance of this class from the given
  22602. * JSON object.
  22603. *
  22604. * @param {Object} data - A JSON object representing the serialized geometry.
  22605. * @return {ConeGeometry} A new instance.
  22606. */
  22607. static fromJSON( data ) {
  22608. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22609. }
  22610. }
  22611. /**
  22612. * A polyhedron is a solid in three dimensions with flat faces. This class
  22613. * will take an array of vertices, project them onto a sphere, and then
  22614. * divide them up to the desired level of detail.
  22615. *
  22616. * @augments BufferGeometry
  22617. */
  22618. class PolyhedronGeometry extends BufferGeometry {
  22619. /**
  22620. * Constructs a new polyhedron geometry.
  22621. *
  22622. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22623. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22624. * @param {number} [radius=1] - The radius of the shape.
  22625. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22626. */
  22627. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22628. super();
  22629. this.type = 'PolyhedronGeometry';
  22630. /**
  22631. * Holds the constructor parameters that have been
  22632. * used to generate the geometry. Any modification
  22633. * after instantiation does not change the geometry.
  22634. *
  22635. * @type {Object}
  22636. */
  22637. this.parameters = {
  22638. vertices: vertices,
  22639. indices: indices,
  22640. radius: radius,
  22641. detail: detail
  22642. };
  22643. // default buffer data
  22644. const vertexBuffer = [];
  22645. const uvBuffer = [];
  22646. // the subdivision creates the vertex buffer data
  22647. subdivide( detail );
  22648. // all vertices should lie on a conceptual sphere with a given radius
  22649. applyRadius( radius );
  22650. // finally, create the uv data
  22651. generateUVs();
  22652. // build non-indexed geometry
  22653. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22654. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22655. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22656. if ( detail === 0 ) {
  22657. this.computeVertexNormals(); // flat normals
  22658. } else {
  22659. this.normalizeNormals(); // smooth normals
  22660. }
  22661. // helper functions
  22662. function subdivide( detail ) {
  22663. const a = new Vector3();
  22664. const b = new Vector3();
  22665. const c = new Vector3();
  22666. // iterate over all faces and apply a subdivision with the given detail value
  22667. for ( let i = 0; i < indices.length; i += 3 ) {
  22668. // get the vertices of the face
  22669. getVertexByIndex( indices[ i + 0 ], a );
  22670. getVertexByIndex( indices[ i + 1 ], b );
  22671. getVertexByIndex( indices[ i + 2 ], c );
  22672. // perform subdivision
  22673. subdivideFace( a, b, c, detail );
  22674. }
  22675. }
  22676. function subdivideFace( a, b, c, detail ) {
  22677. const cols = detail + 1;
  22678. // we use this multidimensional array as a data structure for creating the subdivision
  22679. const v = [];
  22680. // construct all of the vertices for this subdivision
  22681. for ( let i = 0; i <= cols; i ++ ) {
  22682. v[ i ] = [];
  22683. const aj = a.clone().lerp( c, i / cols );
  22684. const bj = b.clone().lerp( c, i / cols );
  22685. const rows = cols - i;
  22686. for ( let j = 0; j <= rows; j ++ ) {
  22687. if ( j === 0 && i === cols ) {
  22688. v[ i ][ j ] = aj;
  22689. } else {
  22690. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22691. }
  22692. }
  22693. }
  22694. // construct all of the faces
  22695. for ( let i = 0; i < cols; i ++ ) {
  22696. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22697. const k = Math.floor( j / 2 );
  22698. if ( j % 2 === 0 ) {
  22699. pushVertex( v[ i ][ k + 1 ] );
  22700. pushVertex( v[ i + 1 ][ k ] );
  22701. pushVertex( v[ i ][ k ] );
  22702. } else {
  22703. pushVertex( v[ i ][ k + 1 ] );
  22704. pushVertex( v[ i + 1 ][ k + 1 ] );
  22705. pushVertex( v[ i + 1 ][ k ] );
  22706. }
  22707. }
  22708. }
  22709. }
  22710. function applyRadius( radius ) {
  22711. const vertex = new Vector3();
  22712. // iterate over the entire buffer and apply the radius to each vertex
  22713. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22714. vertex.x = vertexBuffer[ i + 0 ];
  22715. vertex.y = vertexBuffer[ i + 1 ];
  22716. vertex.z = vertexBuffer[ i + 2 ];
  22717. vertex.normalize().multiplyScalar( radius );
  22718. vertexBuffer[ i + 0 ] = vertex.x;
  22719. vertexBuffer[ i + 1 ] = vertex.y;
  22720. vertexBuffer[ i + 2 ] = vertex.z;
  22721. }
  22722. }
  22723. function generateUVs() {
  22724. const vertex = new Vector3();
  22725. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22726. vertex.x = vertexBuffer[ i + 0 ];
  22727. vertex.y = vertexBuffer[ i + 1 ];
  22728. vertex.z = vertexBuffer[ i + 2 ];
  22729. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22730. const v = inclination( vertex ) / Math.PI + 0.5;
  22731. uvBuffer.push( u, 1 - v );
  22732. }
  22733. correctUVs();
  22734. correctSeam();
  22735. }
  22736. function correctSeam() {
  22737. // handle case when face straddles the seam, see #3269
  22738. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22739. // uv data of a single face
  22740. const x0 = uvBuffer[ i + 0 ];
  22741. const x1 = uvBuffer[ i + 2 ];
  22742. const x2 = uvBuffer[ i + 4 ];
  22743. const max = Math.max( x0, x1, x2 );
  22744. const min = Math.min( x0, x1, x2 );
  22745. // 0.9 is somewhat arbitrary
  22746. if ( max > 0.9 && min < 0.1 ) {
  22747. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22748. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22749. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22750. }
  22751. }
  22752. }
  22753. function pushVertex( vertex ) {
  22754. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22755. }
  22756. function getVertexByIndex( index, vertex ) {
  22757. const stride = index * 3;
  22758. vertex.x = vertices[ stride + 0 ];
  22759. vertex.y = vertices[ stride + 1 ];
  22760. vertex.z = vertices[ stride + 2 ];
  22761. }
  22762. function correctUVs() {
  22763. const a = new Vector3();
  22764. const b = new Vector3();
  22765. const c = new Vector3();
  22766. const centroid = new Vector3();
  22767. const uvA = new Vector2();
  22768. const uvB = new Vector2();
  22769. const uvC = new Vector2();
  22770. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22771. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22772. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22773. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22774. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22775. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22776. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22777. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22778. const azi = azimuth( centroid );
  22779. correctUV( uvA, j + 0, a, azi );
  22780. correctUV( uvB, j + 2, b, azi );
  22781. correctUV( uvC, j + 4, c, azi );
  22782. }
  22783. }
  22784. function correctUV( uv, stride, vector, azimuth ) {
  22785. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22786. uvBuffer[ stride ] = uv.x - 1;
  22787. }
  22788. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22789. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22790. }
  22791. }
  22792. // Angle around the Y axis, counter-clockwise when looking from above.
  22793. function azimuth( vector ) {
  22794. return Math.atan2( vector.z, - vector.x );
  22795. }
  22796. // Angle above the XZ plane.
  22797. function inclination( vector ) {
  22798. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22799. }
  22800. }
  22801. copy( source ) {
  22802. super.copy( source );
  22803. this.parameters = Object.assign( {}, source.parameters );
  22804. return this;
  22805. }
  22806. /**
  22807. * Factory method for creating an instance of this class from the given
  22808. * JSON object.
  22809. *
  22810. * @param {Object} data - A JSON object representing the serialized geometry.
  22811. * @return {PolyhedronGeometry} A new instance.
  22812. */
  22813. static fromJSON( data ) {
  22814. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22815. }
  22816. }
  22817. /**
  22818. * A geometry class for representing a dodecahedron.
  22819. *
  22820. * ```js
  22821. * const geometry = new THREE.DodecahedronGeometry();
  22822. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22823. * const dodecahedron = new THREE.Mesh( geometry, material );
  22824. * scene.add( dodecahedron );
  22825. * ```
  22826. *
  22827. * @augments PolyhedronGeometry
  22828. */
  22829. class DodecahedronGeometry extends PolyhedronGeometry {
  22830. /**
  22831. * Constructs a new dodecahedron geometry.
  22832. *
  22833. * @param {number} [radius=1] - Radius of the dodecahedron.
  22834. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22835. */
  22836. constructor( radius = 1, detail = 0 ) {
  22837. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22838. const r = 1 / t;
  22839. const vertices = [
  22840. // (±1, ±1, ±1)
  22841. -1, -1, -1, -1, -1, 1,
  22842. -1, 1, -1, -1, 1, 1,
  22843. 1, -1, -1, 1, -1, 1,
  22844. 1, 1, -1, 1, 1, 1,
  22845. // (0, ±1/φ, ±φ)
  22846. 0, - r, - t, 0, - r, t,
  22847. 0, r, - t, 0, r, t,
  22848. // (±1/φ, ±φ, 0)
  22849. - r, - t, 0, - r, t, 0,
  22850. r, - t, 0, r, t, 0,
  22851. // (±φ, 0, ±1/φ)
  22852. - t, 0, - r, t, 0, - r,
  22853. - t, 0, r, t, 0, r
  22854. ];
  22855. const indices = [
  22856. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22857. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22858. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22859. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22860. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22861. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22862. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22863. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22864. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22865. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22866. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22867. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22868. ];
  22869. super( vertices, indices, radius, detail );
  22870. this.type = 'DodecahedronGeometry';
  22871. /**
  22872. * Holds the constructor parameters that have been
  22873. * used to generate the geometry. Any modification
  22874. * after instantiation does not change the geometry.
  22875. *
  22876. * @type {Object}
  22877. */
  22878. this.parameters = {
  22879. radius: radius,
  22880. detail: detail
  22881. };
  22882. }
  22883. /**
  22884. * Factory method for creating an instance of this class from the given
  22885. * JSON object.
  22886. *
  22887. * @param {Object} data - A JSON object representing the serialized geometry.
  22888. * @return {DodecahedronGeometry} A new instance.
  22889. */
  22890. static fromJSON( data ) {
  22891. return new DodecahedronGeometry( data.radius, data.detail );
  22892. }
  22893. }
  22894. const _v0$1 = /*@__PURE__*/ new Vector3();
  22895. const _v1$1 = /*@__PURE__*/ new Vector3();
  22896. const _normal = /*@__PURE__*/ new Vector3();
  22897. const _triangle = /*@__PURE__*/ new Triangle();
  22898. /**
  22899. * Can be used as a helper object to view the edges of a geometry.
  22900. *
  22901. * ```js
  22902. * const geometry = new THREE.BoxGeometry();
  22903. * const edges = new THREE.EdgesGeometry( geometry );
  22904. * const line = new THREE.LineSegments( edges );
  22905. * scene.add( line );
  22906. * ```
  22907. *
  22908. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22909. *
  22910. * @augments BufferGeometry
  22911. */
  22912. class EdgesGeometry extends BufferGeometry {
  22913. /**
  22914. * Constructs a new edges geometry.
  22915. *
  22916. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22917. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22918. * between the face normals of the adjoining faces exceeds this value.
  22919. */
  22920. constructor( geometry = null, thresholdAngle = 1 ) {
  22921. super();
  22922. this.type = 'EdgesGeometry';
  22923. /**
  22924. * Holds the constructor parameters that have been
  22925. * used to generate the geometry. Any modification
  22926. * after instantiation does not change the geometry.
  22927. *
  22928. * @type {Object}
  22929. */
  22930. this.parameters = {
  22931. geometry: geometry,
  22932. thresholdAngle: thresholdAngle
  22933. };
  22934. if ( geometry !== null ) {
  22935. const precisionPoints = 4;
  22936. const precision = Math.pow( 10, precisionPoints );
  22937. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22938. const indexAttr = geometry.getIndex();
  22939. const positionAttr = geometry.getAttribute( 'position' );
  22940. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22941. const indexArr = [ 0, 0, 0 ];
  22942. const vertKeys = [ 'a', 'b', 'c' ];
  22943. const hashes = new Array( 3 );
  22944. const edgeData = {};
  22945. const vertices = [];
  22946. for ( let i = 0; i < indexCount; i += 3 ) {
  22947. if ( indexAttr ) {
  22948. indexArr[ 0 ] = indexAttr.getX( i );
  22949. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22950. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22951. } else {
  22952. indexArr[ 0 ] = i;
  22953. indexArr[ 1 ] = i + 1;
  22954. indexArr[ 2 ] = i + 2;
  22955. }
  22956. const { a, b, c } = _triangle;
  22957. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22958. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22959. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22960. _triangle.getNormal( _normal );
  22961. // create hashes for the edge from the vertices
  22962. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22963. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22964. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22965. // skip degenerate triangles
  22966. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22967. continue;
  22968. }
  22969. // iterate over every edge
  22970. for ( let j = 0; j < 3; j ++ ) {
  22971. // get the first and next vertex making up the edge
  22972. const jNext = ( j + 1 ) % 3;
  22973. const vecHash0 = hashes[ j ];
  22974. const vecHash1 = hashes[ jNext ];
  22975. const v0 = _triangle[ vertKeys[ j ] ];
  22976. const v1 = _triangle[ vertKeys[ jNext ] ];
  22977. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22978. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22979. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22980. // if we found a sibling edge add it into the vertex array if
  22981. // it meets the angle threshold and delete the edge from the map.
  22982. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22983. vertices.push( v0.x, v0.y, v0.z );
  22984. vertices.push( v1.x, v1.y, v1.z );
  22985. }
  22986. edgeData[ reverseHash ] = null;
  22987. } else if ( ! ( hash in edgeData ) ) {
  22988. // if we've already got an edge here then skip adding a new one
  22989. edgeData[ hash ] = {
  22990. index0: indexArr[ j ],
  22991. index1: indexArr[ jNext ],
  22992. normal: _normal.clone(),
  22993. };
  22994. }
  22995. }
  22996. }
  22997. // iterate over all remaining, unmatched edges and add them to the vertex array
  22998. for ( const key in edgeData ) {
  22999. if ( edgeData[ key ] ) {
  23000. const { index0, index1 } = edgeData[ key ];
  23001. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23002. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23003. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23004. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23005. }
  23006. }
  23007. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23008. }
  23009. }
  23010. copy( source ) {
  23011. super.copy( source );
  23012. this.parameters = Object.assign( {}, source.parameters );
  23013. return this;
  23014. }
  23015. }
  23016. /**
  23017. * An abstract base class for creating an analytic curve object that contains methods
  23018. * for interpolation.
  23019. *
  23020. * @abstract
  23021. */
  23022. class Curve {
  23023. /**
  23024. * Constructs a new curve.
  23025. */
  23026. constructor() {
  23027. /**
  23028. * The type property is used for detecting the object type
  23029. * in context of serialization/deserialization.
  23030. *
  23031. * @type {string}
  23032. * @readonly
  23033. */
  23034. this.type = 'Curve';
  23035. /**
  23036. * This value determines the amount of divisions when calculating the
  23037. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23038. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23039. * recommended to increase the value of this property if the curve is very large.
  23040. *
  23041. * @type {number}
  23042. * @default 200
  23043. */
  23044. this.arcLengthDivisions = 200;
  23045. /**
  23046. * Must be set to `true` if the curve parameters have changed.
  23047. *
  23048. * @type {boolean}
  23049. * @default false
  23050. */
  23051. this.needsUpdate = false;
  23052. /**
  23053. * An internal cache that holds precomputed curve length values.
  23054. *
  23055. * @private
  23056. * @type {?Array<number>}
  23057. * @default null
  23058. */
  23059. this.cacheArcLengths = null;
  23060. }
  23061. /**
  23062. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23063. * for the given interpolation factor.
  23064. *
  23065. * @abstract
  23066. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23067. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23068. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23069. */
  23070. getPoint( /* t, optionalTarget */ ) {
  23071. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23072. }
  23073. /**
  23074. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23075. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23076. * of the curve which equidistant samples.
  23077. *
  23078. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23079. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23080. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23081. */
  23082. getPointAt( u, optionalTarget ) {
  23083. const t = this.getUtoTmapping( u );
  23084. return this.getPoint( t, optionalTarget );
  23085. }
  23086. /**
  23087. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23088. * the curve shape.
  23089. *
  23090. * @param {number} [divisions=5] - The number of divisions.
  23091. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23092. */
  23093. getPoints( divisions = 5 ) {
  23094. const points = [];
  23095. for ( let d = 0; d <= divisions; d ++ ) {
  23096. points.push( this.getPoint( d / divisions ) );
  23097. }
  23098. return points;
  23099. }
  23100. // Get sequence of points using getPointAt( u )
  23101. /**
  23102. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23103. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23104. * curve.
  23105. *
  23106. * @param {number} [divisions=5] - The number of divisions.
  23107. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23108. */
  23109. getSpacedPoints( divisions = 5 ) {
  23110. const points = [];
  23111. for ( let d = 0; d <= divisions; d ++ ) {
  23112. points.push( this.getPointAt( d / divisions ) );
  23113. }
  23114. return points;
  23115. }
  23116. /**
  23117. * Returns the total arc length of the curve.
  23118. *
  23119. * @return {number} The length of the curve.
  23120. */
  23121. getLength() {
  23122. const lengths = this.getLengths();
  23123. return lengths[ lengths.length - 1 ];
  23124. }
  23125. /**
  23126. * Returns an array of cumulative segment lengths of the curve.
  23127. *
  23128. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23129. * @return {Array<number>} An array holding the cumulative segment lengths.
  23130. */
  23131. getLengths( divisions = this.arcLengthDivisions ) {
  23132. if ( this.cacheArcLengths &&
  23133. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23134. ! this.needsUpdate ) {
  23135. return this.cacheArcLengths;
  23136. }
  23137. this.needsUpdate = false;
  23138. const cache = [];
  23139. let current, last = this.getPoint( 0 );
  23140. let sum = 0;
  23141. cache.push( 0 );
  23142. for ( let p = 1; p <= divisions; p ++ ) {
  23143. current = this.getPoint( p / divisions );
  23144. sum += current.distanceTo( last );
  23145. cache.push( sum );
  23146. last = current;
  23147. }
  23148. this.cacheArcLengths = cache;
  23149. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23150. }
  23151. /**
  23152. * Update the cumulative segment distance cache. The method must be called
  23153. * every time curve parameters are changed. If an updated curve is part of a
  23154. * composed curve like {@link CurvePath}, this method must be called on the
  23155. * composed curve, too.
  23156. */
  23157. updateArcLengths() {
  23158. this.needsUpdate = true;
  23159. this.getLengths();
  23160. }
  23161. /**
  23162. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23163. * interpolation factor in the same range that can be ued to sample equidistant points
  23164. * from a curve.
  23165. *
  23166. * @param {number} u - The interpolation factor.
  23167. * @param {?number} distance - An optional distance on the curve.
  23168. * @return {number} The updated interpolation factor.
  23169. */
  23170. getUtoTmapping( u, distance = null ) {
  23171. const arcLengths = this.getLengths();
  23172. let i = 0;
  23173. const il = arcLengths.length;
  23174. let targetArcLength; // The targeted u distance value to get
  23175. if ( distance ) {
  23176. targetArcLength = distance;
  23177. } else {
  23178. targetArcLength = u * arcLengths[ il - 1 ];
  23179. }
  23180. // binary search for the index with largest value smaller than target u distance
  23181. let low = 0, high = il - 1, comparison;
  23182. while ( low <= high ) {
  23183. 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
  23184. comparison = arcLengths[ i ] - targetArcLength;
  23185. if ( comparison < 0 ) {
  23186. low = i + 1;
  23187. } else if ( comparison > 0 ) {
  23188. high = i - 1;
  23189. } else {
  23190. high = i;
  23191. break;
  23192. // DONE
  23193. }
  23194. }
  23195. i = high;
  23196. if ( arcLengths[ i ] === targetArcLength ) {
  23197. return i / ( il - 1 );
  23198. }
  23199. // we could get finer grain at lengths, or use simple interpolation between two points
  23200. const lengthBefore = arcLengths[ i ];
  23201. const lengthAfter = arcLengths[ i + 1 ];
  23202. const segmentLength = lengthAfter - lengthBefore;
  23203. // determine where we are between the 'before' and 'after' points
  23204. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23205. // add that fractional amount to t
  23206. const t = ( i + segmentFraction ) / ( il - 1 );
  23207. return t;
  23208. }
  23209. /**
  23210. * Returns a unit vector tangent for the given interpolation factor.
  23211. * If the derived curve does not implement its tangent derivation,
  23212. * two points a small delta apart will be used to find its gradient
  23213. * which seems to give a reasonable approximation.
  23214. *
  23215. * @param {number} t - The interpolation factor.
  23216. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23217. * @return {(Vector2|Vector3)} The tangent vector.
  23218. */
  23219. getTangent( t, optionalTarget ) {
  23220. const delta = 0.0001;
  23221. let t1 = t - delta;
  23222. let t2 = t + delta;
  23223. // Capping in case of danger
  23224. if ( t1 < 0 ) t1 = 0;
  23225. if ( t2 > 1 ) t2 = 1;
  23226. const pt1 = this.getPoint( t1 );
  23227. const pt2 = this.getPoint( t2 );
  23228. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23229. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23230. return tangent;
  23231. }
  23232. /**
  23233. * Same as {@link Curve#getTangent} but with equidistant samples.
  23234. *
  23235. * @param {number} u - The interpolation factor.
  23236. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23237. * @return {(Vector2|Vector3)} The tangent vector.
  23238. * @see {@link Curve#getPointAt}
  23239. */
  23240. getTangentAt( u, optionalTarget ) {
  23241. const t = this.getUtoTmapping( u );
  23242. return this.getTangent( t, optionalTarget );
  23243. }
  23244. /**
  23245. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23246. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23247. *
  23248. * @param {number} segments - The number of segments.
  23249. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23250. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23251. */
  23252. computeFrenetFrames( segments, closed = false ) {
  23253. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23254. const normal = new Vector3();
  23255. const tangents = [];
  23256. const normals = [];
  23257. const binormals = [];
  23258. const vec = new Vector3();
  23259. const mat = new Matrix4();
  23260. // compute the tangent vectors for each segment on the curve
  23261. for ( let i = 0; i <= segments; i ++ ) {
  23262. const u = i / segments;
  23263. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23264. }
  23265. // select an initial normal vector perpendicular to the first tangent vector,
  23266. // and in the direction of the minimum tangent xyz component
  23267. normals[ 0 ] = new Vector3();
  23268. binormals[ 0 ] = new Vector3();
  23269. let min = Number.MAX_VALUE;
  23270. const tx = Math.abs( tangents[ 0 ].x );
  23271. const ty = Math.abs( tangents[ 0 ].y );
  23272. const tz = Math.abs( tangents[ 0 ].z );
  23273. if ( tx <= min ) {
  23274. min = tx;
  23275. normal.set( 1, 0, 0 );
  23276. }
  23277. if ( ty <= min ) {
  23278. min = ty;
  23279. normal.set( 0, 1, 0 );
  23280. }
  23281. if ( tz <= min ) {
  23282. normal.set( 0, 0, 1 );
  23283. }
  23284. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23285. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23286. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23287. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23288. for ( let i = 1; i <= segments; i ++ ) {
  23289. normals[ i ] = normals[ i - 1 ].clone();
  23290. binormals[ i ] = binormals[ i - 1 ].clone();
  23291. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23292. if ( vec.length() > Number.EPSILON ) {
  23293. vec.normalize();
  23294. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23295. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23296. }
  23297. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23298. }
  23299. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23300. if ( closed === true ) {
  23301. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23302. theta /= segments;
  23303. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23304. theta = - theta;
  23305. }
  23306. for ( let i = 1; i <= segments; i ++ ) {
  23307. // twist a little...
  23308. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23309. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23310. }
  23311. }
  23312. return {
  23313. tangents: tangents,
  23314. normals: normals,
  23315. binormals: binormals
  23316. };
  23317. }
  23318. /**
  23319. * Returns a new curve with copied values from this instance.
  23320. *
  23321. * @return {Curve} A clone of this instance.
  23322. */
  23323. clone() {
  23324. return new this.constructor().copy( this );
  23325. }
  23326. /**
  23327. * Copies the values of the given curve to this instance.
  23328. *
  23329. * @param {Curve} source - The curve to copy.
  23330. * @return {Curve} A reference to this curve.
  23331. */
  23332. copy( source ) {
  23333. this.arcLengthDivisions = source.arcLengthDivisions;
  23334. return this;
  23335. }
  23336. /**
  23337. * Serializes the curve into JSON.
  23338. *
  23339. * @return {Object} A JSON object representing the serialized curve.
  23340. * @see {@link ObjectLoader#parse}
  23341. */
  23342. toJSON() {
  23343. const data = {
  23344. metadata: {
  23345. version: 4.7,
  23346. type: 'Curve',
  23347. generator: 'Curve.toJSON'
  23348. }
  23349. };
  23350. data.arcLengthDivisions = this.arcLengthDivisions;
  23351. data.type = this.type;
  23352. return data;
  23353. }
  23354. /**
  23355. * Deserializes the curve from the given JSON.
  23356. *
  23357. * @param {Object} json - The JSON holding the serialized curve.
  23358. * @return {Curve} A reference to this curve.
  23359. */
  23360. fromJSON( json ) {
  23361. this.arcLengthDivisions = json.arcLengthDivisions;
  23362. return this;
  23363. }
  23364. }
  23365. /**
  23366. * A curve representing an ellipse.
  23367. *
  23368. * ```js
  23369. * const curve = new THREE.EllipseCurve(
  23370. * 0, 0,
  23371. * 10, 10,
  23372. * 0, 2 * Math.PI,
  23373. * false,
  23374. * 0
  23375. * );
  23376. *
  23377. * const points = curve.getPoints( 50 );
  23378. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23379. *
  23380. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23381. *
  23382. * // Create the final object to add to the scene
  23383. * const ellipse = new THREE.Line( geometry, material );
  23384. * ```
  23385. *
  23386. * @augments Curve
  23387. */
  23388. class EllipseCurve extends Curve {
  23389. /**
  23390. * Constructs a new ellipse curve.
  23391. *
  23392. * @param {number} [aX=0] - The X center of the ellipse.
  23393. * @param {number} [aY=0] - The Y center of the ellipse.
  23394. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23395. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23396. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23397. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23398. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23399. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23400. */
  23401. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23402. super();
  23403. /**
  23404. * This flag can be used for type testing.
  23405. *
  23406. * @type {boolean}
  23407. * @readonly
  23408. * @default true
  23409. */
  23410. this.isEllipseCurve = true;
  23411. this.type = 'EllipseCurve';
  23412. /**
  23413. * The X center of the ellipse.
  23414. *
  23415. * @type {number}
  23416. * @default 0
  23417. */
  23418. this.aX = aX;
  23419. /**
  23420. * The Y center of the ellipse.
  23421. *
  23422. * @type {number}
  23423. * @default 0
  23424. */
  23425. this.aY = aY;
  23426. /**
  23427. * The radius of the ellipse in the x direction.
  23428. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23429. *
  23430. * @type {number}
  23431. * @default 1
  23432. */
  23433. this.xRadius = xRadius;
  23434. /**
  23435. * The radius of the ellipse in the y direction.
  23436. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23437. *
  23438. * @type {number}
  23439. * @default 1
  23440. */
  23441. this.yRadius = yRadius;
  23442. /**
  23443. * The start angle of the curve in radians starting from the positive X axis.
  23444. *
  23445. * @type {number}
  23446. * @default 0
  23447. */
  23448. this.aStartAngle = aStartAngle;
  23449. /**
  23450. * The end angle of the curve in radians starting from the positive X axis.
  23451. *
  23452. * @type {number}
  23453. * @default Math.PI*2
  23454. */
  23455. this.aEndAngle = aEndAngle;
  23456. /**
  23457. * Whether the ellipse is drawn clockwise or not.
  23458. *
  23459. * @type {boolean}
  23460. * @default false
  23461. */
  23462. this.aClockwise = aClockwise;
  23463. /**
  23464. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23465. *
  23466. * @type {number}
  23467. * @default 0
  23468. */
  23469. this.aRotation = aRotation;
  23470. }
  23471. /**
  23472. * Returns a point on the curve.
  23473. *
  23474. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23475. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23476. * @return {Vector2} The position on the curve.
  23477. */
  23478. getPoint( t, optionalTarget = new Vector2() ) {
  23479. const point = optionalTarget;
  23480. const twoPi = Math.PI * 2;
  23481. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23482. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23483. // ensures that deltaAngle is 0 .. 2 PI
  23484. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23485. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23486. if ( deltaAngle < Number.EPSILON ) {
  23487. if ( samePoints ) {
  23488. deltaAngle = 0;
  23489. } else {
  23490. deltaAngle = twoPi;
  23491. }
  23492. }
  23493. if ( this.aClockwise === true && ! samePoints ) {
  23494. if ( deltaAngle === twoPi ) {
  23495. deltaAngle = - twoPi;
  23496. } else {
  23497. deltaAngle = deltaAngle - twoPi;
  23498. }
  23499. }
  23500. const angle = this.aStartAngle + t * deltaAngle;
  23501. let x = this.aX + this.xRadius * Math.cos( angle );
  23502. let y = this.aY + this.yRadius * Math.sin( angle );
  23503. if ( this.aRotation !== 0 ) {
  23504. const cos = Math.cos( this.aRotation );
  23505. const sin = Math.sin( this.aRotation );
  23506. const tx = x - this.aX;
  23507. const ty = y - this.aY;
  23508. // Rotate the point about the center of the ellipse.
  23509. x = tx * cos - ty * sin + this.aX;
  23510. y = tx * sin + ty * cos + this.aY;
  23511. }
  23512. return point.set( x, y );
  23513. }
  23514. copy( source ) {
  23515. super.copy( source );
  23516. this.aX = source.aX;
  23517. this.aY = source.aY;
  23518. this.xRadius = source.xRadius;
  23519. this.yRadius = source.yRadius;
  23520. this.aStartAngle = source.aStartAngle;
  23521. this.aEndAngle = source.aEndAngle;
  23522. this.aClockwise = source.aClockwise;
  23523. this.aRotation = source.aRotation;
  23524. return this;
  23525. }
  23526. toJSON() {
  23527. const data = super.toJSON();
  23528. data.aX = this.aX;
  23529. data.aY = this.aY;
  23530. data.xRadius = this.xRadius;
  23531. data.yRadius = this.yRadius;
  23532. data.aStartAngle = this.aStartAngle;
  23533. data.aEndAngle = this.aEndAngle;
  23534. data.aClockwise = this.aClockwise;
  23535. data.aRotation = this.aRotation;
  23536. return data;
  23537. }
  23538. fromJSON( json ) {
  23539. super.fromJSON( json );
  23540. this.aX = json.aX;
  23541. this.aY = json.aY;
  23542. this.xRadius = json.xRadius;
  23543. this.yRadius = json.yRadius;
  23544. this.aStartAngle = json.aStartAngle;
  23545. this.aEndAngle = json.aEndAngle;
  23546. this.aClockwise = json.aClockwise;
  23547. this.aRotation = json.aRotation;
  23548. return this;
  23549. }
  23550. }
  23551. /**
  23552. * A curve representing an arc.
  23553. *
  23554. * @augments EllipseCurve
  23555. */
  23556. class ArcCurve extends EllipseCurve {
  23557. /**
  23558. * Constructs a new arc curve.
  23559. *
  23560. * @param {number} [aX=0] - The X center of the ellipse.
  23561. * @param {number} [aY=0] - The Y center of the ellipse.
  23562. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23563. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23564. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23565. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23566. */
  23567. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23568. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23569. /**
  23570. * This flag can be used for type testing.
  23571. *
  23572. * @type {boolean}
  23573. * @readonly
  23574. * @default true
  23575. */
  23576. this.isArcCurve = true;
  23577. this.type = 'ArcCurve';
  23578. }
  23579. }
  23580. function CubicPoly() {
  23581. /**
  23582. * Centripetal CatmullRom Curve - which is useful for avoiding
  23583. * cusps and self-intersections in non-uniform catmull rom curves.
  23584. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23585. *
  23586. * curve.type accepts centripetal(default), chordal and catmullrom
  23587. * curve.tension is used for catmullrom which defaults to 0.5
  23588. */
  23589. /*
  23590. Based on an optimized c++ solution in
  23591. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23592. - http://ideone.com/NoEbVM
  23593. This CubicPoly class could be used for reusing some variables and calculations,
  23594. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23595. which can be placed in CurveUtils.
  23596. */
  23597. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23598. /*
  23599. * Compute coefficients for a cubic polynomial
  23600. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23601. * such that
  23602. * p(0) = x0, p(1) = x1
  23603. * and
  23604. * p'(0) = t0, p'(1) = t1.
  23605. */
  23606. function init( x0, x1, t0, t1 ) {
  23607. c0 = x0;
  23608. c1 = t0;
  23609. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23610. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23611. }
  23612. return {
  23613. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23614. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23615. },
  23616. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23617. // compute tangents when parameterized in [t1,t2]
  23618. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23619. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23620. // rescale tangents for parametrization in [0,1]
  23621. t1 *= dt1;
  23622. t2 *= dt1;
  23623. init( x1, x2, t1, t2 );
  23624. },
  23625. calc: function ( t ) {
  23626. const t2 = t * t;
  23627. const t3 = t2 * t;
  23628. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23629. }
  23630. };
  23631. }
  23632. //
  23633. const tmp = /*@__PURE__*/ new Vector3();
  23634. const px = /*@__PURE__*/ new CubicPoly();
  23635. const py = /*@__PURE__*/ new CubicPoly();
  23636. const pz = /*@__PURE__*/ new CubicPoly();
  23637. /**
  23638. * A curve representing a Catmull-Rom spline.
  23639. *
  23640. * ```js
  23641. * //Create a closed wavey loop
  23642. * const curve = new THREE.CatmullRomCurve3( [
  23643. * new THREE.Vector3( -10, 0, 10 ),
  23644. * new THREE.Vector3( -5, 5, 5 ),
  23645. * new THREE.Vector3( 0, 0, 0 ),
  23646. * new THREE.Vector3( 5, -5, 5 ),
  23647. * new THREE.Vector3( 10, 0, 10 )
  23648. * ] );
  23649. *
  23650. * const points = curve.getPoints( 50 );
  23651. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23652. *
  23653. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23654. *
  23655. * // Create the final object to add to the scene
  23656. * const curveObject = new THREE.Line( geometry, material );
  23657. * ```
  23658. *
  23659. * @augments Curve
  23660. */
  23661. class CatmullRomCurve3 extends Curve {
  23662. /**
  23663. * Constructs a new Catmull-Rom curve.
  23664. *
  23665. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23666. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23667. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23668. * @param {number} [tension=0.5] - Tension of the curve.
  23669. */
  23670. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23671. super();
  23672. /**
  23673. * This flag can be used for type testing.
  23674. *
  23675. * @type {boolean}
  23676. * @readonly
  23677. * @default true
  23678. */
  23679. this.isCatmullRomCurve3 = true;
  23680. this.type = 'CatmullRomCurve3';
  23681. /**
  23682. * An array of 3D points defining the curve.
  23683. *
  23684. * @type {Array<Vector3>}
  23685. */
  23686. this.points = points;
  23687. /**
  23688. * Whether the curve is closed or not.
  23689. *
  23690. * @type {boolean}
  23691. * @default false
  23692. */
  23693. this.closed = closed;
  23694. /**
  23695. * The curve type.
  23696. *
  23697. * @type {('centripetal'|'chordal'|'catmullrom')}
  23698. * @default 'centripetal'
  23699. */
  23700. this.curveType = curveType;
  23701. /**
  23702. * Tension of the curve.
  23703. *
  23704. * @type {number}
  23705. * @default 0.5
  23706. */
  23707. this.tension = tension;
  23708. }
  23709. /**
  23710. * Returns a point on the curve.
  23711. *
  23712. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23713. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23714. * @return {Vector3} The position on the curve.
  23715. */
  23716. getPoint( t, optionalTarget = new Vector3() ) {
  23717. const point = optionalTarget;
  23718. const points = this.points;
  23719. const l = points.length;
  23720. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23721. let intPoint = Math.floor( p );
  23722. let weight = p - intPoint;
  23723. if ( this.closed ) {
  23724. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23725. } else if ( weight === 0 && intPoint === l - 1 ) {
  23726. intPoint = l - 2;
  23727. weight = 1;
  23728. }
  23729. let p0, p3; // 4 points (p1 & p2 defined below)
  23730. if ( this.closed || intPoint > 0 ) {
  23731. p0 = points[ ( intPoint - 1 ) % l ];
  23732. } else {
  23733. // extrapolate first point
  23734. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23735. p0 = tmp;
  23736. }
  23737. const p1 = points[ intPoint % l ];
  23738. const p2 = points[ ( intPoint + 1 ) % l ];
  23739. if ( this.closed || intPoint + 2 < l ) {
  23740. p3 = points[ ( intPoint + 2 ) % l ];
  23741. } else {
  23742. // extrapolate last point
  23743. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23744. p3 = tmp;
  23745. }
  23746. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23747. // init Centripetal / Chordal Catmull-Rom
  23748. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23749. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23750. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23751. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23752. // safety check for repeated points
  23753. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23754. if ( dt0 < 1e-4 ) dt0 = dt1;
  23755. if ( dt2 < 1e-4 ) dt2 = dt1;
  23756. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23757. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23758. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23759. } else if ( this.curveType === 'catmullrom' ) {
  23760. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23761. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23762. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23763. }
  23764. point.set(
  23765. px.calc( weight ),
  23766. py.calc( weight ),
  23767. pz.calc( weight )
  23768. );
  23769. return point;
  23770. }
  23771. copy( source ) {
  23772. super.copy( source );
  23773. this.points = [];
  23774. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23775. const point = source.points[ i ];
  23776. this.points.push( point.clone() );
  23777. }
  23778. this.closed = source.closed;
  23779. this.curveType = source.curveType;
  23780. this.tension = source.tension;
  23781. return this;
  23782. }
  23783. toJSON() {
  23784. const data = super.toJSON();
  23785. data.points = [];
  23786. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23787. const point = this.points[ i ];
  23788. data.points.push( point.toArray() );
  23789. }
  23790. data.closed = this.closed;
  23791. data.curveType = this.curveType;
  23792. data.tension = this.tension;
  23793. return data;
  23794. }
  23795. fromJSON( json ) {
  23796. super.fromJSON( json );
  23797. this.points = [];
  23798. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23799. const point = json.points[ i ];
  23800. this.points.push( new Vector3().fromArray( point ) );
  23801. }
  23802. this.closed = json.closed;
  23803. this.curveType = json.curveType;
  23804. this.tension = json.tension;
  23805. return this;
  23806. }
  23807. }
  23808. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23809. /**
  23810. * Computes a point on a Catmull-Rom spline.
  23811. *
  23812. * @param {number} t - The interpolation factor.
  23813. * @param {number} p0 - The first control point.
  23814. * @param {number} p1 - The second control point.
  23815. * @param {number} p2 - The third control point.
  23816. * @param {number} p3 - The fourth control point.
  23817. * @return {number} The calculated point on a Catmull-Rom spline.
  23818. */
  23819. function CatmullRom( t, p0, p1, p2, p3 ) {
  23820. const v0 = ( p2 - p0 ) * 0.5;
  23821. const v1 = ( p3 - p1 ) * 0.5;
  23822. const t2 = t * t;
  23823. const t3 = t * t2;
  23824. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23825. }
  23826. //
  23827. function QuadraticBezierP0( t, p ) {
  23828. const k = 1 - t;
  23829. return k * k * p;
  23830. }
  23831. function QuadraticBezierP1( t, p ) {
  23832. return 2 * ( 1 - t ) * t * p;
  23833. }
  23834. function QuadraticBezierP2( t, p ) {
  23835. return t * t * p;
  23836. }
  23837. /**
  23838. * Computes a point on a Quadratic Bezier curve.
  23839. *
  23840. * @param {number} t - The interpolation factor.
  23841. * @param {number} p0 - The first control point.
  23842. * @param {number} p1 - The second control point.
  23843. * @param {number} p2 - The third control point.
  23844. * @return {number} The calculated point on a Quadratic Bezier curve.
  23845. */
  23846. function QuadraticBezier( t, p0, p1, p2 ) {
  23847. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23848. QuadraticBezierP2( t, p2 );
  23849. }
  23850. //
  23851. function CubicBezierP0( t, p ) {
  23852. const k = 1 - t;
  23853. return k * k * k * p;
  23854. }
  23855. function CubicBezierP1( t, p ) {
  23856. const k = 1 - t;
  23857. return 3 * k * k * t * p;
  23858. }
  23859. function CubicBezierP2( t, p ) {
  23860. return 3 * ( 1 - t ) * t * t * p;
  23861. }
  23862. function CubicBezierP3( t, p ) {
  23863. return t * t * t * p;
  23864. }
  23865. /**
  23866. * Computes a point on a Cubic Bezier curve.
  23867. *
  23868. * @param {number} t - The interpolation factor.
  23869. * @param {number} p0 - The first control point.
  23870. * @param {number} p1 - The second control point.
  23871. * @param {number} p2 - The third control point.
  23872. * @param {number} p3 - The fourth control point.
  23873. * @return {number} The calculated point on a Cubic Bezier curve.
  23874. */
  23875. function CubicBezier( t, p0, p1, p2, p3 ) {
  23876. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23877. CubicBezierP3( t, p3 );
  23878. }
  23879. /**
  23880. * A curve representing a 2D Cubic Bezier curve.
  23881. *
  23882. * ```js
  23883. * const curve = new THREE.CubicBezierCurve(
  23884. * new THREE.Vector2( - 0, 0 ),
  23885. * new THREE.Vector2( - 5, 15 ),
  23886. * new THREE.Vector2( 20, 15 ),
  23887. * new THREE.Vector2( 10, 0 )
  23888. * );
  23889. *
  23890. * const points = curve.getPoints( 50 );
  23891. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23892. *
  23893. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23894. *
  23895. * // Create the final object to add to the scene
  23896. * const curveObject = new THREE.Line( geometry, material );
  23897. * ```
  23898. *
  23899. * @augments Curve
  23900. */
  23901. class CubicBezierCurve extends Curve {
  23902. /**
  23903. * Constructs a new Cubic Bezier curve.
  23904. *
  23905. * @param {Vector2} [v0] - The start point.
  23906. * @param {Vector2} [v1] - The first control point.
  23907. * @param {Vector2} [v2] - The second control point.
  23908. * @param {Vector2} [v3] - The end point.
  23909. */
  23910. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23911. super();
  23912. /**
  23913. * This flag can be used for type testing.
  23914. *
  23915. * @type {boolean}
  23916. * @readonly
  23917. * @default true
  23918. */
  23919. this.isCubicBezierCurve = true;
  23920. this.type = 'CubicBezierCurve';
  23921. /**
  23922. * The start point.
  23923. *
  23924. * @type {Vector2}
  23925. */
  23926. this.v0 = v0;
  23927. /**
  23928. * The first control point.
  23929. *
  23930. * @type {Vector2}
  23931. */
  23932. this.v1 = v1;
  23933. /**
  23934. * The second control point.
  23935. *
  23936. * @type {Vector2}
  23937. */
  23938. this.v2 = v2;
  23939. /**
  23940. * The end point.
  23941. *
  23942. * @type {Vector2}
  23943. */
  23944. this.v3 = v3;
  23945. }
  23946. /**
  23947. * Returns a point on the curve.
  23948. *
  23949. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23950. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23951. * @return {Vector2} The position on the curve.
  23952. */
  23953. getPoint( t, optionalTarget = new Vector2() ) {
  23954. const point = optionalTarget;
  23955. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23956. point.set(
  23957. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23958. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23959. );
  23960. return point;
  23961. }
  23962. copy( source ) {
  23963. super.copy( source );
  23964. this.v0.copy( source.v0 );
  23965. this.v1.copy( source.v1 );
  23966. this.v2.copy( source.v2 );
  23967. this.v3.copy( source.v3 );
  23968. return this;
  23969. }
  23970. toJSON() {
  23971. const data = super.toJSON();
  23972. data.v0 = this.v0.toArray();
  23973. data.v1 = this.v1.toArray();
  23974. data.v2 = this.v2.toArray();
  23975. data.v3 = this.v3.toArray();
  23976. return data;
  23977. }
  23978. fromJSON( json ) {
  23979. super.fromJSON( json );
  23980. this.v0.fromArray( json.v0 );
  23981. this.v1.fromArray( json.v1 );
  23982. this.v2.fromArray( json.v2 );
  23983. this.v3.fromArray( json.v3 );
  23984. return this;
  23985. }
  23986. }
  23987. /**
  23988. * A curve representing a 3D Cubic Bezier curve.
  23989. *
  23990. * @augments Curve
  23991. */
  23992. class CubicBezierCurve3 extends Curve {
  23993. /**
  23994. * Constructs a new Cubic Bezier curve.
  23995. *
  23996. * @param {Vector3} [v0] - The start point.
  23997. * @param {Vector3} [v1] - The first control point.
  23998. * @param {Vector3} [v2] - The second control point.
  23999. * @param {Vector3} [v3] - The end point.
  24000. */
  24001. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24002. super();
  24003. /**
  24004. * This flag can be used for type testing.
  24005. *
  24006. * @type {boolean}
  24007. * @readonly
  24008. * @default true
  24009. */
  24010. this.isCubicBezierCurve3 = true;
  24011. this.type = 'CubicBezierCurve3';
  24012. /**
  24013. * The start point.
  24014. *
  24015. * @type {Vector3}
  24016. */
  24017. this.v0 = v0;
  24018. /**
  24019. * The first control point.
  24020. *
  24021. * @type {Vector3}
  24022. */
  24023. this.v1 = v1;
  24024. /**
  24025. * The second control point.
  24026. *
  24027. * @type {Vector3}
  24028. */
  24029. this.v2 = v2;
  24030. /**
  24031. * The end point.
  24032. *
  24033. * @type {Vector3}
  24034. */
  24035. this.v3 = v3;
  24036. }
  24037. /**
  24038. * Returns a point on the curve.
  24039. *
  24040. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24041. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24042. * @return {Vector3} The position on the curve.
  24043. */
  24044. getPoint( t, optionalTarget = new Vector3() ) {
  24045. const point = optionalTarget;
  24046. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24047. point.set(
  24048. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24049. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24050. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24051. );
  24052. return point;
  24053. }
  24054. copy( source ) {
  24055. super.copy( source );
  24056. this.v0.copy( source.v0 );
  24057. this.v1.copy( source.v1 );
  24058. this.v2.copy( source.v2 );
  24059. this.v3.copy( source.v3 );
  24060. return this;
  24061. }
  24062. toJSON() {
  24063. const data = super.toJSON();
  24064. data.v0 = this.v0.toArray();
  24065. data.v1 = this.v1.toArray();
  24066. data.v2 = this.v2.toArray();
  24067. data.v3 = this.v3.toArray();
  24068. return data;
  24069. }
  24070. fromJSON( json ) {
  24071. super.fromJSON( json );
  24072. this.v0.fromArray( json.v0 );
  24073. this.v1.fromArray( json.v1 );
  24074. this.v2.fromArray( json.v2 );
  24075. this.v3.fromArray( json.v3 );
  24076. return this;
  24077. }
  24078. }
  24079. /**
  24080. * A curve representing a 2D line segment.
  24081. *
  24082. * @augments Curve
  24083. */
  24084. class LineCurve extends Curve {
  24085. /**
  24086. * Constructs a new line curve.
  24087. *
  24088. * @param {Vector2} [v1] - The start point.
  24089. * @param {Vector2} [v2] - The end point.
  24090. */
  24091. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24092. super();
  24093. /**
  24094. * This flag can be used for type testing.
  24095. *
  24096. * @type {boolean}
  24097. * @readonly
  24098. * @default true
  24099. */
  24100. this.isLineCurve = true;
  24101. this.type = 'LineCurve';
  24102. /**
  24103. * The start point.
  24104. *
  24105. * @type {Vector2}
  24106. */
  24107. this.v1 = v1;
  24108. /**
  24109. * The end point.
  24110. *
  24111. * @type {Vector2}
  24112. */
  24113. this.v2 = v2;
  24114. }
  24115. /**
  24116. * Returns a point on the line.
  24117. *
  24118. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24119. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24120. * @return {Vector2} The position on the line.
  24121. */
  24122. getPoint( t, optionalTarget = new Vector2() ) {
  24123. const point = optionalTarget;
  24124. if ( t === 1 ) {
  24125. point.copy( this.v2 );
  24126. } else {
  24127. point.copy( this.v2 ).sub( this.v1 );
  24128. point.multiplyScalar( t ).add( this.v1 );
  24129. }
  24130. return point;
  24131. }
  24132. // Line curve is linear, so we can overwrite default getPointAt
  24133. getPointAt( u, optionalTarget ) {
  24134. return this.getPoint( u, optionalTarget );
  24135. }
  24136. getTangent( t, optionalTarget = new Vector2() ) {
  24137. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24138. }
  24139. getTangentAt( u, optionalTarget ) {
  24140. return this.getTangent( u, optionalTarget );
  24141. }
  24142. copy( source ) {
  24143. super.copy( source );
  24144. this.v1.copy( source.v1 );
  24145. this.v2.copy( source.v2 );
  24146. return this;
  24147. }
  24148. toJSON() {
  24149. const data = super.toJSON();
  24150. data.v1 = this.v1.toArray();
  24151. data.v2 = this.v2.toArray();
  24152. return data;
  24153. }
  24154. fromJSON( json ) {
  24155. super.fromJSON( json );
  24156. this.v1.fromArray( json.v1 );
  24157. this.v2.fromArray( json.v2 );
  24158. return this;
  24159. }
  24160. }
  24161. /**
  24162. * A curve representing a 3D line segment.
  24163. *
  24164. * @augments Curve
  24165. */
  24166. class LineCurve3 extends Curve {
  24167. /**
  24168. * Constructs a new line curve.
  24169. *
  24170. * @param {Vector3} [v1] - The start point.
  24171. * @param {Vector3} [v2] - The end point.
  24172. */
  24173. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24174. super();
  24175. /**
  24176. * This flag can be used for type testing.
  24177. *
  24178. * @type {boolean}
  24179. * @readonly
  24180. * @default true
  24181. */
  24182. this.isLineCurve3 = true;
  24183. this.type = 'LineCurve3';
  24184. /**
  24185. * The start point.
  24186. *
  24187. * @type {Vector3}
  24188. */
  24189. this.v1 = v1;
  24190. /**
  24191. * The end point.
  24192. *
  24193. * @type {Vector2}
  24194. */
  24195. this.v2 = v2;
  24196. }
  24197. /**
  24198. * Returns a point on the line.
  24199. *
  24200. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24201. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24202. * @return {Vector3} The position on the line.
  24203. */
  24204. getPoint( t, optionalTarget = new Vector3() ) {
  24205. const point = optionalTarget;
  24206. if ( t === 1 ) {
  24207. point.copy( this.v2 );
  24208. } else {
  24209. point.copy( this.v2 ).sub( this.v1 );
  24210. point.multiplyScalar( t ).add( this.v1 );
  24211. }
  24212. return point;
  24213. }
  24214. // Line curve is linear, so we can overwrite default getPointAt
  24215. getPointAt( u, optionalTarget ) {
  24216. return this.getPoint( u, optionalTarget );
  24217. }
  24218. getTangent( t, optionalTarget = new Vector3() ) {
  24219. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24220. }
  24221. getTangentAt( u, optionalTarget ) {
  24222. return this.getTangent( u, optionalTarget );
  24223. }
  24224. copy( source ) {
  24225. super.copy( source );
  24226. this.v1.copy( source.v1 );
  24227. this.v2.copy( source.v2 );
  24228. return this;
  24229. }
  24230. toJSON() {
  24231. const data = super.toJSON();
  24232. data.v1 = this.v1.toArray();
  24233. data.v2 = this.v2.toArray();
  24234. return data;
  24235. }
  24236. fromJSON( json ) {
  24237. super.fromJSON( json );
  24238. this.v1.fromArray( json.v1 );
  24239. this.v2.fromArray( json.v2 );
  24240. return this;
  24241. }
  24242. }
  24243. /**
  24244. * A curve representing a 2D Quadratic Bezier curve.
  24245. *
  24246. * ```js
  24247. * const curve = new THREE.QuadraticBezierCurve(
  24248. * new THREE.Vector2( - 10, 0 ),
  24249. * new THREE.Vector2( 20, 15 ),
  24250. * new THREE.Vector2( 10, 0 )
  24251. * )
  24252. *
  24253. * const points = curve.getPoints( 50 );
  24254. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24255. *
  24256. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24257. *
  24258. * // Create the final object to add to the scene
  24259. * const curveObject = new THREE.Line( geometry, material );
  24260. * ```
  24261. *
  24262. * @augments Curve
  24263. */
  24264. class QuadraticBezierCurve extends Curve {
  24265. /**
  24266. * Constructs a new Quadratic Bezier curve.
  24267. *
  24268. * @param {Vector2} [v0] - The start point.
  24269. * @param {Vector2} [v1] - The control point.
  24270. * @param {Vector2} [v2] - The end point.
  24271. */
  24272. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24273. super();
  24274. /**
  24275. * This flag can be used for type testing.
  24276. *
  24277. * @type {boolean}
  24278. * @readonly
  24279. * @default true
  24280. */
  24281. this.isQuadraticBezierCurve = true;
  24282. this.type = 'QuadraticBezierCurve';
  24283. /**
  24284. * The start point.
  24285. *
  24286. * @type {Vector2}
  24287. */
  24288. this.v0 = v0;
  24289. /**
  24290. * The control point.
  24291. *
  24292. * @type {Vector2}
  24293. */
  24294. this.v1 = v1;
  24295. /**
  24296. * The end point.
  24297. *
  24298. * @type {Vector2}
  24299. */
  24300. this.v2 = v2;
  24301. }
  24302. /**
  24303. * Returns a point on the curve.
  24304. *
  24305. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24306. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24307. * @return {Vector2} The position on the curve.
  24308. */
  24309. getPoint( t, optionalTarget = new Vector2() ) {
  24310. const point = optionalTarget;
  24311. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24312. point.set(
  24313. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24314. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24315. );
  24316. return point;
  24317. }
  24318. copy( source ) {
  24319. super.copy( source );
  24320. this.v0.copy( source.v0 );
  24321. this.v1.copy( source.v1 );
  24322. this.v2.copy( source.v2 );
  24323. return this;
  24324. }
  24325. toJSON() {
  24326. const data = super.toJSON();
  24327. data.v0 = this.v0.toArray();
  24328. data.v1 = this.v1.toArray();
  24329. data.v2 = this.v2.toArray();
  24330. return data;
  24331. }
  24332. fromJSON( json ) {
  24333. super.fromJSON( json );
  24334. this.v0.fromArray( json.v0 );
  24335. this.v1.fromArray( json.v1 );
  24336. this.v2.fromArray( json.v2 );
  24337. return this;
  24338. }
  24339. }
  24340. /**
  24341. * A curve representing a 3D Quadratic Bezier curve.
  24342. *
  24343. * @augments Curve
  24344. */
  24345. class QuadraticBezierCurve3 extends Curve {
  24346. /**
  24347. * Constructs a new Quadratic Bezier curve.
  24348. *
  24349. * @param {Vector3} [v0] - The start point.
  24350. * @param {Vector3} [v1] - The control point.
  24351. * @param {Vector3} [v2] - The end point.
  24352. */
  24353. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24354. super();
  24355. /**
  24356. * This flag can be used for type testing.
  24357. *
  24358. * @type {boolean}
  24359. * @readonly
  24360. * @default true
  24361. */
  24362. this.isQuadraticBezierCurve3 = true;
  24363. this.type = 'QuadraticBezierCurve3';
  24364. /**
  24365. * The start point.
  24366. *
  24367. * @type {Vector3}
  24368. */
  24369. this.v0 = v0;
  24370. /**
  24371. * The control point.
  24372. *
  24373. * @type {Vector3}
  24374. */
  24375. this.v1 = v1;
  24376. /**
  24377. * The end point.
  24378. *
  24379. * @type {Vector3}
  24380. */
  24381. this.v2 = v2;
  24382. }
  24383. /**
  24384. * Returns a point on the curve.
  24385. *
  24386. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24387. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24388. * @return {Vector3} The position on the curve.
  24389. */
  24390. getPoint( t, optionalTarget = new Vector3() ) {
  24391. const point = optionalTarget;
  24392. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24393. point.set(
  24394. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24395. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24396. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24397. );
  24398. return point;
  24399. }
  24400. copy( source ) {
  24401. super.copy( source );
  24402. this.v0.copy( source.v0 );
  24403. this.v1.copy( source.v1 );
  24404. this.v2.copy( source.v2 );
  24405. return this;
  24406. }
  24407. toJSON() {
  24408. const data = super.toJSON();
  24409. data.v0 = this.v0.toArray();
  24410. data.v1 = this.v1.toArray();
  24411. data.v2 = this.v2.toArray();
  24412. return data;
  24413. }
  24414. fromJSON( json ) {
  24415. super.fromJSON( json );
  24416. this.v0.fromArray( json.v0 );
  24417. this.v1.fromArray( json.v1 );
  24418. this.v2.fromArray( json.v2 );
  24419. return this;
  24420. }
  24421. }
  24422. /**
  24423. * A curve representing a 2D spline curve.
  24424. *
  24425. * ```js
  24426. * // Create a sine-like wave
  24427. * const curve = new THREE.SplineCurve( [
  24428. * new THREE.Vector2( -10, 0 ),
  24429. * new THREE.Vector2( -5, 5 ),
  24430. * new THREE.Vector2( 0, 0 ),
  24431. * new THREE.Vector2( 5, -5 ),
  24432. * new THREE.Vector2( 10, 0 )
  24433. * ] );
  24434. *
  24435. * const points = curve.getPoints( 50 );
  24436. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24437. *
  24438. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24439. *
  24440. * // Create the final object to add to the scene
  24441. * const splineObject = new THREE.Line( geometry, material );
  24442. * ```
  24443. *
  24444. * @augments Curve
  24445. */
  24446. class SplineCurve extends Curve {
  24447. /**
  24448. * Constructs a new 2D spline curve.
  24449. *
  24450. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24451. */
  24452. constructor( points = [] ) {
  24453. super();
  24454. /**
  24455. * This flag can be used for type testing.
  24456. *
  24457. * @type {boolean}
  24458. * @readonly
  24459. * @default true
  24460. */
  24461. this.isSplineCurve = true;
  24462. this.type = 'SplineCurve';
  24463. /**
  24464. * An array of 2D points defining the curve.
  24465. *
  24466. * @type {Array<Vector2>}
  24467. */
  24468. this.points = points;
  24469. }
  24470. /**
  24471. * Returns a point on the curve.
  24472. *
  24473. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24474. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24475. * @return {Vector2} The position on the curve.
  24476. */
  24477. getPoint( t, optionalTarget = new Vector2() ) {
  24478. const point = optionalTarget;
  24479. const points = this.points;
  24480. const p = ( points.length - 1 ) * t;
  24481. const intPoint = Math.floor( p );
  24482. const weight = p - intPoint;
  24483. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24484. const p1 = points[ intPoint ];
  24485. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24486. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24487. point.set(
  24488. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24489. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24490. );
  24491. return point;
  24492. }
  24493. copy( source ) {
  24494. super.copy( source );
  24495. this.points = [];
  24496. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24497. const point = source.points[ i ];
  24498. this.points.push( point.clone() );
  24499. }
  24500. return this;
  24501. }
  24502. toJSON() {
  24503. const data = super.toJSON();
  24504. data.points = [];
  24505. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24506. const point = this.points[ i ];
  24507. data.points.push( point.toArray() );
  24508. }
  24509. return data;
  24510. }
  24511. fromJSON( json ) {
  24512. super.fromJSON( json );
  24513. this.points = [];
  24514. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24515. const point = json.points[ i ];
  24516. this.points.push( new Vector2().fromArray( point ) );
  24517. }
  24518. return this;
  24519. }
  24520. }
  24521. var Curves = /*#__PURE__*/Object.freeze({
  24522. __proto__: null,
  24523. ArcCurve: ArcCurve,
  24524. CatmullRomCurve3: CatmullRomCurve3,
  24525. CubicBezierCurve: CubicBezierCurve,
  24526. CubicBezierCurve3: CubicBezierCurve3,
  24527. EllipseCurve: EllipseCurve,
  24528. LineCurve: LineCurve,
  24529. LineCurve3: LineCurve3,
  24530. QuadraticBezierCurve: QuadraticBezierCurve,
  24531. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24532. SplineCurve: SplineCurve
  24533. });
  24534. /**
  24535. * A base class extending {@link Curve}. `CurvePath` is simply an
  24536. * array of connected curves, but retains the API of a curve.
  24537. *
  24538. * @augments Curve
  24539. */
  24540. class CurvePath extends Curve {
  24541. /**
  24542. * Constructs a new curve path.
  24543. */
  24544. constructor() {
  24545. super();
  24546. this.type = 'CurvePath';
  24547. /**
  24548. * An array of curves defining the
  24549. * path.
  24550. *
  24551. * @type {Array<Curve>}
  24552. */
  24553. this.curves = [];
  24554. /**
  24555. * Whether the path should automatically be closed
  24556. * by a line curve.
  24557. *
  24558. * @type {boolean}
  24559. * @default false
  24560. */
  24561. this.autoClose = false;
  24562. }
  24563. /**
  24564. * Adds a curve to this curve path.
  24565. *
  24566. * @param {Curve} curve - The curve to add.
  24567. */
  24568. add( curve ) {
  24569. this.curves.push( curve );
  24570. }
  24571. /**
  24572. * Adds a line curve to close the path.
  24573. *
  24574. * @return {CurvePath} A reference to this curve path.
  24575. */
  24576. closePath() {
  24577. // Add a line curve if start and end of lines are not connected
  24578. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24579. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24580. if ( ! startPoint.equals( endPoint ) ) {
  24581. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24582. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24583. }
  24584. return this;
  24585. }
  24586. /**
  24587. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24588. * for the given interpolation factor.
  24589. *
  24590. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24591. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24592. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24593. */
  24594. getPoint( t, optionalTarget ) {
  24595. // To get accurate point with reference to
  24596. // entire path distance at time t,
  24597. // following has to be done:
  24598. // 1. Length of each sub path have to be known
  24599. // 2. Locate and identify type of curve
  24600. // 3. Get t for the curve
  24601. // 4. Return curve.getPointAt(t')
  24602. const d = t * this.getLength();
  24603. const curveLengths = this.getCurveLengths();
  24604. let i = 0;
  24605. // To think about boundaries points.
  24606. while ( i < curveLengths.length ) {
  24607. if ( curveLengths[ i ] >= d ) {
  24608. const diff = curveLengths[ i ] - d;
  24609. const curve = this.curves[ i ];
  24610. const segmentLength = curve.getLength();
  24611. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24612. return curve.getPointAt( u, optionalTarget );
  24613. }
  24614. i ++;
  24615. }
  24616. return null;
  24617. // loop where sum != 0, sum > d , sum+1 <d
  24618. }
  24619. getLength() {
  24620. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24621. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24622. // getPoint() depends on getLength
  24623. const lens = this.getCurveLengths();
  24624. return lens[ lens.length - 1 ];
  24625. }
  24626. updateArcLengths() {
  24627. // cacheLengths must be recalculated.
  24628. this.needsUpdate = true;
  24629. this.cacheLengths = null;
  24630. this.getCurveLengths();
  24631. }
  24632. /**
  24633. * Returns list of cumulative curve lengths of the defined curves.
  24634. *
  24635. * @return {Array<number>} The curve lengths.
  24636. */
  24637. getCurveLengths() {
  24638. // Compute lengths and cache them
  24639. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24640. // We use cache values if curves and cache array are same length
  24641. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24642. return this.cacheLengths;
  24643. }
  24644. // Get length of sub-curve
  24645. // Push sums into cached array
  24646. const lengths = [];
  24647. let sums = 0;
  24648. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24649. sums += this.curves[ i ].getLength();
  24650. lengths.push( sums );
  24651. }
  24652. this.cacheLengths = lengths;
  24653. return lengths;
  24654. }
  24655. getSpacedPoints( divisions = 40 ) {
  24656. const points = [];
  24657. for ( let i = 0; i <= divisions; i ++ ) {
  24658. points.push( this.getPoint( i / divisions ) );
  24659. }
  24660. if ( this.autoClose ) {
  24661. points.push( points[ 0 ] );
  24662. }
  24663. return points;
  24664. }
  24665. getPoints( divisions = 12 ) {
  24666. const points = [];
  24667. let last;
  24668. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24669. const curve = curves[ i ];
  24670. const resolution = curve.isEllipseCurve ? divisions * 2
  24671. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24672. : curve.isSplineCurve ? divisions * curve.points.length
  24673. : divisions;
  24674. const pts = curve.getPoints( resolution );
  24675. for ( let j = 0; j < pts.length; j ++ ) {
  24676. const point = pts[ j ];
  24677. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24678. points.push( point );
  24679. last = point;
  24680. }
  24681. }
  24682. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24683. points.push( points[ 0 ] );
  24684. }
  24685. return points;
  24686. }
  24687. copy( source ) {
  24688. super.copy( source );
  24689. this.curves = [];
  24690. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24691. const curve = source.curves[ i ];
  24692. this.curves.push( curve.clone() );
  24693. }
  24694. this.autoClose = source.autoClose;
  24695. return this;
  24696. }
  24697. toJSON() {
  24698. const data = super.toJSON();
  24699. data.autoClose = this.autoClose;
  24700. data.curves = [];
  24701. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24702. const curve = this.curves[ i ];
  24703. data.curves.push( curve.toJSON() );
  24704. }
  24705. return data;
  24706. }
  24707. fromJSON( json ) {
  24708. super.fromJSON( json );
  24709. this.autoClose = json.autoClose;
  24710. this.curves = [];
  24711. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24712. const curve = json.curves[ i ];
  24713. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24714. }
  24715. return this;
  24716. }
  24717. }
  24718. /**
  24719. * A 2D path representation. The class provides methods for creating paths
  24720. * and contours of 2D shapes similar to the 2D Canvas API.
  24721. *
  24722. * ```js
  24723. * const path = new THREE.Path();
  24724. *
  24725. * path.lineTo( 0, 0.8 );
  24726. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24727. * path.lineTo( 1, 1 );
  24728. *
  24729. * const points = path.getPoints();
  24730. *
  24731. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24732. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24733. *
  24734. * const line = new THREE.Line( geometry, material );
  24735. * scene.add( line );
  24736. * ```
  24737. *
  24738. * @augments CurvePath
  24739. */
  24740. class Path extends CurvePath {
  24741. /**
  24742. * Constructs a new path.
  24743. *
  24744. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24745. */
  24746. constructor( points ) {
  24747. super();
  24748. this.type = 'Path';
  24749. /**
  24750. * The current offset of the path. Any new curve added will start here.
  24751. *
  24752. * @type {Vector2}
  24753. */
  24754. this.currentPoint = new Vector2();
  24755. if ( points ) {
  24756. this.setFromPoints( points );
  24757. }
  24758. }
  24759. /**
  24760. * Creates a path from the given list of points. The points are added
  24761. * to the path as instances of {@link LineCurve}.
  24762. *
  24763. * @param {Array<Vector2>} points - An array of 2D points.
  24764. * @return {Path} A reference to this path.
  24765. */
  24766. setFromPoints( points ) {
  24767. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24768. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24769. this.lineTo( points[ i ].x, points[ i ].y );
  24770. }
  24771. return this;
  24772. }
  24773. /**
  24774. * Moves {@link Path#currentPoint} to the given point.
  24775. *
  24776. * @param {number} x - The x coordinate.
  24777. * @param {number} y - The y coordinate.
  24778. * @return {Path} A reference to this path.
  24779. */
  24780. moveTo( x, y ) {
  24781. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24782. return this;
  24783. }
  24784. /**
  24785. * Adds an instance of {@link LineCurve} to the path by connecting
  24786. * the current point with the given one.
  24787. *
  24788. * @param {number} x - The x coordinate of the end point.
  24789. * @param {number} y - The y coordinate of the end point.
  24790. * @return {Path} A reference to this path.
  24791. */
  24792. lineTo( x, y ) {
  24793. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24794. this.curves.push( curve );
  24795. this.currentPoint.set( x, y );
  24796. return this;
  24797. }
  24798. /**
  24799. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24800. * the current point with the given one.
  24801. *
  24802. * @param {number} aCPx - The x coordinate of the control point.
  24803. * @param {number} aCPy - The y coordinate of the control point.
  24804. * @param {number} aX - The x coordinate of the end point.
  24805. * @param {number} aY - The y coordinate of the end point.
  24806. * @return {Path} A reference to this path.
  24807. */
  24808. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24809. const curve = new QuadraticBezierCurve(
  24810. this.currentPoint.clone(),
  24811. new Vector2( aCPx, aCPy ),
  24812. new Vector2( aX, aY )
  24813. );
  24814. this.curves.push( curve );
  24815. this.currentPoint.set( aX, aY );
  24816. return this;
  24817. }
  24818. /**
  24819. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24820. * the current point with the given one.
  24821. *
  24822. * @param {number} aCP1x - The x coordinate of the first control point.
  24823. * @param {number} aCP1y - The y coordinate of the first control point.
  24824. * @param {number} aCP2x - The x coordinate of the second control point.
  24825. * @param {number} aCP2y - The y coordinate of the second control point.
  24826. * @param {number} aX - The x coordinate of the end point.
  24827. * @param {number} aY - The y coordinate of the end point.
  24828. * @return {Path} A reference to this path.
  24829. */
  24830. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24831. const curve = new CubicBezierCurve(
  24832. this.currentPoint.clone(),
  24833. new Vector2( aCP1x, aCP1y ),
  24834. new Vector2( aCP2x, aCP2y ),
  24835. new Vector2( aX, aY )
  24836. );
  24837. this.curves.push( curve );
  24838. this.currentPoint.set( aX, aY );
  24839. return this;
  24840. }
  24841. /**
  24842. * Adds an instance of {@link SplineCurve} to the path by connecting
  24843. * the current point with the given list of points.
  24844. *
  24845. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24846. * @return {Path} A reference to this path.
  24847. */
  24848. splineThru( pts ) {
  24849. const npts = [ this.currentPoint.clone() ].concat( pts );
  24850. const curve = new SplineCurve( npts );
  24851. this.curves.push( curve );
  24852. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24853. return this;
  24854. }
  24855. /**
  24856. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24857. * to the current point.
  24858. *
  24859. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24860. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24861. * @param {number} [aRadius=1] - The radius of the arc.
  24862. * @param {number} [aStartAngle=0] - The start angle in radians.
  24863. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24864. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24865. * @return {Path} A reference to this path.
  24866. */
  24867. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24868. const x0 = this.currentPoint.x;
  24869. const y0 = this.currentPoint.y;
  24870. this.absarc( aX + x0, aY + y0, aRadius,
  24871. aStartAngle, aEndAngle, aClockwise );
  24872. return this;
  24873. }
  24874. /**
  24875. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24876. *
  24877. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24878. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24879. * @param {number} [aRadius=1] - The radius of the arc.
  24880. * @param {number} [aStartAngle=0] - The start angle in radians.
  24881. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24882. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24883. * @return {Path} A reference to this path.
  24884. */
  24885. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24886. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24887. return this;
  24888. }
  24889. /**
  24890. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24891. * to the current point
  24892. *
  24893. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24894. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24895. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24896. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24897. * @param {number} [aStartAngle=0] - The start angle in radians.
  24898. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24899. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24900. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24901. * @return {Path} A reference to this path.
  24902. */
  24903. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24904. const x0 = this.currentPoint.x;
  24905. const y0 = this.currentPoint.y;
  24906. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24907. return this;
  24908. }
  24909. /**
  24910. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24911. *
  24912. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24913. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24914. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24915. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24916. * @param {number} [aStartAngle=0] - The start angle in radians.
  24917. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24918. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24919. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24920. * @return {Path} A reference to this path.
  24921. */
  24922. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24923. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24924. if ( this.curves.length > 0 ) {
  24925. // if a previous curve is present, attempt to join
  24926. const firstPoint = curve.getPoint( 0 );
  24927. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24928. this.lineTo( firstPoint.x, firstPoint.y );
  24929. }
  24930. }
  24931. this.curves.push( curve );
  24932. const lastPoint = curve.getPoint( 1 );
  24933. this.currentPoint.copy( lastPoint );
  24934. return this;
  24935. }
  24936. copy( source ) {
  24937. super.copy( source );
  24938. this.currentPoint.copy( source.currentPoint );
  24939. return this;
  24940. }
  24941. toJSON() {
  24942. const data = super.toJSON();
  24943. data.currentPoint = this.currentPoint.toArray();
  24944. return data;
  24945. }
  24946. fromJSON( json ) {
  24947. super.fromJSON( json );
  24948. this.currentPoint.fromArray( json.currentPoint );
  24949. return this;
  24950. }
  24951. }
  24952. /**
  24953. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24954. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24955. * points, or to get triangulated faces.
  24956. *
  24957. * ```js
  24958. * const heartShape = new THREE.Shape();
  24959. *
  24960. * heartShape.moveTo( 25, 25 );
  24961. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24962. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24963. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24964. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24965. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24966. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24967. *
  24968. * const extrudeSettings = {
  24969. * depth: 8,
  24970. * bevelEnabled: true,
  24971. * bevelSegments: 2,
  24972. * steps: 2,
  24973. * bevelSize: 1,
  24974. * bevelThickness: 1
  24975. * };
  24976. *
  24977. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24978. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24979. * ```
  24980. *
  24981. * @augments Path
  24982. */
  24983. class Shape extends Path {
  24984. /**
  24985. * Constructs a new shape.
  24986. *
  24987. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24988. */
  24989. constructor( points ) {
  24990. super( points );
  24991. /**
  24992. * The UUID of the shape.
  24993. *
  24994. * @type {string}
  24995. * @readonly
  24996. */
  24997. this.uuid = generateUUID();
  24998. this.type = 'Shape';
  24999. /**
  25000. * Defines the holes in the shape. Hole definitions must use the
  25001. * opposite winding order (CW/CCW) than the outer shape.
  25002. *
  25003. * @type {Array<Path>}
  25004. * @readonly
  25005. */
  25006. this.holes = [];
  25007. }
  25008. /**
  25009. * Returns an array representing each contour of the holes
  25010. * as a list of 2D points.
  25011. *
  25012. * @param {number} divisions - The fineness of the result.
  25013. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25014. */
  25015. getPointsHoles( divisions ) {
  25016. const holesPts = [];
  25017. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25018. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25019. }
  25020. return holesPts;
  25021. }
  25022. // get points of shape and holes (keypoints based on segments parameter)
  25023. /**
  25024. * Returns an object that holds contour data for the shape and its holes as
  25025. * arrays of 2D points.
  25026. *
  25027. * @param {number} divisions - The fineness of the result.
  25028. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25029. */
  25030. extractPoints( divisions ) {
  25031. return {
  25032. shape: this.getPoints( divisions ),
  25033. holes: this.getPointsHoles( divisions )
  25034. };
  25035. }
  25036. copy( source ) {
  25037. super.copy( source );
  25038. this.holes = [];
  25039. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25040. const hole = source.holes[ i ];
  25041. this.holes.push( hole.clone() );
  25042. }
  25043. return this;
  25044. }
  25045. toJSON() {
  25046. const data = super.toJSON();
  25047. data.uuid = this.uuid;
  25048. data.holes = [];
  25049. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25050. const hole = this.holes[ i ];
  25051. data.holes.push( hole.toJSON() );
  25052. }
  25053. return data;
  25054. }
  25055. fromJSON( json ) {
  25056. super.fromJSON( json );
  25057. this.uuid = json.uuid;
  25058. this.holes = [];
  25059. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25060. const hole = json.holes[ i ];
  25061. this.holes.push( new Path().fromJSON( hole ) );
  25062. }
  25063. return this;
  25064. }
  25065. }
  25066. /* eslint-disable */
  25067. // copy of mapbox/earcut version 3.0.1
  25068. // https://github.com/mapbox/earcut/tree/v3.0.1
  25069. function earcut(data, holeIndices, dim = 2) {
  25070. const hasHoles = holeIndices && holeIndices.length;
  25071. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25072. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25073. const triangles = [];
  25074. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25075. let minX, minY, invSize;
  25076. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25077. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25078. if (data.length > 80 * dim) {
  25079. minX = Infinity;
  25080. minY = Infinity;
  25081. let maxX = -Infinity;
  25082. let maxY = -Infinity;
  25083. for (let i = dim; i < outerLen; i += dim) {
  25084. const x = data[i];
  25085. const y = data[i + 1];
  25086. if (x < minX) minX = x;
  25087. if (y < minY) minY = y;
  25088. if (x > maxX) maxX = x;
  25089. if (y > maxY) maxY = y;
  25090. }
  25091. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25092. invSize = Math.max(maxX - minX, maxY - minY);
  25093. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25094. }
  25095. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25096. return triangles;
  25097. }
  25098. // create a circular doubly linked list from polygon points in the specified winding order
  25099. function linkedList(data, start, end, dim, clockwise) {
  25100. let last;
  25101. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25102. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25103. } else {
  25104. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25105. }
  25106. if (last && equals(last, last.next)) {
  25107. removeNode(last);
  25108. last = last.next;
  25109. }
  25110. return last;
  25111. }
  25112. // eliminate colinear or duplicate points
  25113. function filterPoints(start, end) {
  25114. if (!start) return start;
  25115. if (!end) end = start;
  25116. let p = start,
  25117. again;
  25118. do {
  25119. again = false;
  25120. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25121. removeNode(p);
  25122. p = end = p.prev;
  25123. if (p === p.next) break;
  25124. again = true;
  25125. } else {
  25126. p = p.next;
  25127. }
  25128. } while (again || p !== end);
  25129. return end;
  25130. }
  25131. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25132. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25133. if (!ear) return;
  25134. // interlink polygon nodes in z-order
  25135. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25136. let stop = ear;
  25137. // iterate through ears, slicing them one by one
  25138. while (ear.prev !== ear.next) {
  25139. const prev = ear.prev;
  25140. const next = ear.next;
  25141. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25142. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25143. removeNode(ear);
  25144. // skipping the next vertex leads to less sliver triangles
  25145. ear = next.next;
  25146. stop = next.next;
  25147. continue;
  25148. }
  25149. ear = next;
  25150. // if we looped through the whole remaining polygon and can't find any more ears
  25151. if (ear === stop) {
  25152. // try filtering points and slicing again
  25153. if (!pass) {
  25154. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25155. // if this didn't work, try curing all small self-intersections locally
  25156. } else if (pass === 1) {
  25157. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25158. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25159. // as a last resort, try splitting the remaining polygon into two
  25160. } else if (pass === 2) {
  25161. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25162. }
  25163. break;
  25164. }
  25165. }
  25166. }
  25167. // check whether a polygon node forms a valid ear with adjacent nodes
  25168. function isEar(ear) {
  25169. const a = ear.prev,
  25170. b = ear,
  25171. c = ear.next;
  25172. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25173. // now make sure we don't have other points inside the potential ear
  25174. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25175. // triangle bbox
  25176. const x0 = Math.min(ax, bx, cx),
  25177. y0 = Math.min(ay, by, cy),
  25178. x1 = Math.max(ax, bx, cx),
  25179. y1 = Math.max(ay, by, cy);
  25180. let p = c.next;
  25181. while (p !== a) {
  25182. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25183. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25184. area(p.prev, p, p.next) >= 0) return false;
  25185. p = p.next;
  25186. }
  25187. return true;
  25188. }
  25189. function isEarHashed(ear, minX, minY, invSize) {
  25190. const a = ear.prev,
  25191. b = ear,
  25192. c = ear.next;
  25193. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25194. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25195. // triangle bbox
  25196. const x0 = Math.min(ax, bx, cx),
  25197. y0 = Math.min(ay, by, cy),
  25198. x1 = Math.max(ax, bx, cx),
  25199. y1 = Math.max(ay, by, cy);
  25200. // z-order range for the current triangle bbox;
  25201. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25202. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25203. let p = ear.prevZ,
  25204. n = ear.nextZ;
  25205. // look for points inside the triangle in both directions
  25206. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25207. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25208. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25209. p = p.prevZ;
  25210. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25211. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25212. n = n.nextZ;
  25213. }
  25214. // look for remaining points in decreasing z-order
  25215. while (p && p.z >= minZ) {
  25216. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25217. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25218. p = p.prevZ;
  25219. }
  25220. // look for remaining points in increasing z-order
  25221. while (n && n.z <= maxZ) {
  25222. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25223. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25224. n = n.nextZ;
  25225. }
  25226. return true;
  25227. }
  25228. // go through all polygon nodes and cure small local self-intersections
  25229. function cureLocalIntersections(start, triangles) {
  25230. let p = start;
  25231. do {
  25232. const a = p.prev,
  25233. b = p.next.next;
  25234. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25235. triangles.push(a.i, p.i, b.i);
  25236. // remove two nodes involved
  25237. removeNode(p);
  25238. removeNode(p.next);
  25239. p = start = b;
  25240. }
  25241. p = p.next;
  25242. } while (p !== start);
  25243. return filterPoints(p);
  25244. }
  25245. // try splitting polygon into two and triangulate them independently
  25246. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25247. // look for a valid diagonal that divides the polygon into two
  25248. let a = start;
  25249. do {
  25250. let b = a.next.next;
  25251. while (b !== a.prev) {
  25252. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25253. // split the polygon in two by the diagonal
  25254. let c = splitPolygon(a, b);
  25255. // filter colinear points around the cuts
  25256. a = filterPoints(a, a.next);
  25257. c = filterPoints(c, c.next);
  25258. // run earcut on each half
  25259. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25260. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25261. return;
  25262. }
  25263. b = b.next;
  25264. }
  25265. a = a.next;
  25266. } while (a !== start);
  25267. }
  25268. // link every hole into the outer loop, producing a single-ring polygon without holes
  25269. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25270. const queue = [];
  25271. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25272. const start = holeIndices[i] * dim;
  25273. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25274. const list = linkedList(data, start, end, dim, false);
  25275. if (list === list.next) list.steiner = true;
  25276. queue.push(getLeftmost(list));
  25277. }
  25278. queue.sort(compareXYSlope);
  25279. // process holes from left to right
  25280. for (let i = 0; i < queue.length; i++) {
  25281. outerNode = eliminateHole(queue[i], outerNode);
  25282. }
  25283. return outerNode;
  25284. }
  25285. function compareXYSlope(a, b) {
  25286. let result = a.x - b.x;
  25287. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25288. // the bridge to the outer shell is always the point that they meet at.
  25289. if (result === 0) {
  25290. result = a.y - b.y;
  25291. if (result === 0) {
  25292. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25293. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25294. result = aSlope - bSlope;
  25295. }
  25296. }
  25297. return result;
  25298. }
  25299. // find a bridge between vertices that connects hole with an outer ring and and link it
  25300. function eliminateHole(hole, outerNode) {
  25301. const bridge = findHoleBridge(hole, outerNode);
  25302. if (!bridge) {
  25303. return outerNode;
  25304. }
  25305. const bridgeReverse = splitPolygon(bridge, hole);
  25306. // filter collinear points around the cuts
  25307. filterPoints(bridgeReverse, bridgeReverse.next);
  25308. return filterPoints(bridge, bridge.next);
  25309. }
  25310. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25311. function findHoleBridge(hole, outerNode) {
  25312. let p = outerNode;
  25313. const hx = hole.x;
  25314. const hy = hole.y;
  25315. let qx = -Infinity;
  25316. let m;
  25317. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25318. // segment's endpoint with lesser x will be potential connection point
  25319. // unless they intersect at a vertex, then choose the vertex
  25320. if (equals(hole, p)) return p;
  25321. do {
  25322. if (equals(hole, p.next)) return p.next;
  25323. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25324. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25325. if (x <= hx && x > qx) {
  25326. qx = x;
  25327. m = p.x < p.next.x ? p : p.next;
  25328. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25329. }
  25330. }
  25331. p = p.next;
  25332. } while (p !== outerNode);
  25333. if (!m) return null;
  25334. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25335. // if there are no points found, we have a valid connection;
  25336. // otherwise choose the point of the minimum angle with the ray as connection point
  25337. const stop = m;
  25338. const mx = m.x;
  25339. const my = m.y;
  25340. let tanMin = Infinity;
  25341. p = m;
  25342. do {
  25343. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25344. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25345. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25346. if (locallyInside(p, hole) &&
  25347. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25348. m = p;
  25349. tanMin = tan;
  25350. }
  25351. }
  25352. p = p.next;
  25353. } while (p !== stop);
  25354. return m;
  25355. }
  25356. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25357. function sectorContainsSector(m, p) {
  25358. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25359. }
  25360. // interlink polygon nodes in z-order
  25361. function indexCurve(start, minX, minY, invSize) {
  25362. let p = start;
  25363. do {
  25364. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25365. p.prevZ = p.prev;
  25366. p.nextZ = p.next;
  25367. p = p.next;
  25368. } while (p !== start);
  25369. p.prevZ.nextZ = null;
  25370. p.prevZ = null;
  25371. sortLinked(p);
  25372. }
  25373. // Simon Tatham's linked list merge sort algorithm
  25374. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25375. function sortLinked(list) {
  25376. let numMerges;
  25377. let inSize = 1;
  25378. do {
  25379. let p = list;
  25380. let e;
  25381. list = null;
  25382. let tail = null;
  25383. numMerges = 0;
  25384. while (p) {
  25385. numMerges++;
  25386. let q = p;
  25387. let pSize = 0;
  25388. for (let i = 0; i < inSize; i++) {
  25389. pSize++;
  25390. q = q.nextZ;
  25391. if (!q) break;
  25392. }
  25393. let qSize = inSize;
  25394. while (pSize > 0 || (qSize > 0 && q)) {
  25395. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25396. e = p;
  25397. p = p.nextZ;
  25398. pSize--;
  25399. } else {
  25400. e = q;
  25401. q = q.nextZ;
  25402. qSize--;
  25403. }
  25404. if (tail) tail.nextZ = e;
  25405. else list = e;
  25406. e.prevZ = tail;
  25407. tail = e;
  25408. }
  25409. p = q;
  25410. }
  25411. tail.nextZ = null;
  25412. inSize *= 2;
  25413. } while (numMerges > 1);
  25414. return list;
  25415. }
  25416. // z-order of a point given coords and inverse of the longer side of data bbox
  25417. function zOrder(x, y, minX, minY, invSize) {
  25418. // coords are transformed into non-negative 15-bit integer range
  25419. x = (x - minX) * invSize | 0;
  25420. y = (y - minY) * invSize | 0;
  25421. x = (x | (x << 8)) & 0x00FF00FF;
  25422. x = (x | (x << 4)) & 0x0F0F0F0F;
  25423. x = (x | (x << 2)) & 0x33333333;
  25424. x = (x | (x << 1)) & 0x55555555;
  25425. y = (y | (y << 8)) & 0x00FF00FF;
  25426. y = (y | (y << 4)) & 0x0F0F0F0F;
  25427. y = (y | (y << 2)) & 0x33333333;
  25428. y = (y | (y << 1)) & 0x55555555;
  25429. return x | (y << 1);
  25430. }
  25431. // find the leftmost node of a polygon ring
  25432. function getLeftmost(start) {
  25433. let p = start,
  25434. leftmost = start;
  25435. do {
  25436. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25437. p = p.next;
  25438. } while (p !== start);
  25439. return leftmost;
  25440. }
  25441. // check if a point lies within a convex triangle
  25442. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25443. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25444. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25445. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25446. }
  25447. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25448. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25449. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25450. }
  25451. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25452. function isValidDiagonal(a, b) {
  25453. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25454. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25455. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25456. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25457. }
  25458. // signed area of a triangle
  25459. function area(p, q, r) {
  25460. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25461. }
  25462. // check if two points are equal
  25463. function equals(p1, p2) {
  25464. return p1.x === p2.x && p1.y === p2.y;
  25465. }
  25466. // check if two segments intersect
  25467. function intersects(p1, q1, p2, q2) {
  25468. const o1 = sign(area(p1, q1, p2));
  25469. const o2 = sign(area(p1, q1, q2));
  25470. const o3 = sign(area(p2, q2, p1));
  25471. const o4 = sign(area(p2, q2, q1));
  25472. if (o1 !== o2 && o3 !== o4) return true; // general case
  25473. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25474. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25475. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25476. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25477. return false;
  25478. }
  25479. // for collinear points p, q, r, check if point q lies on segment pr
  25480. function onSegment(p, q, r) {
  25481. 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);
  25482. }
  25483. function sign(num) {
  25484. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25485. }
  25486. // check if a polygon diagonal intersects any polygon segments
  25487. function intersectsPolygon(a, b) {
  25488. let p = a;
  25489. do {
  25490. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25491. intersects(p, p.next, a, b)) return true;
  25492. p = p.next;
  25493. } while (p !== a);
  25494. return false;
  25495. }
  25496. // check if a polygon diagonal is locally inside the polygon
  25497. function locallyInside(a, b) {
  25498. return area(a.prev, a, a.next) < 0 ?
  25499. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25500. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25501. }
  25502. // check if the middle point of a polygon diagonal is inside the polygon
  25503. function middleInside(a, b) {
  25504. let p = a;
  25505. let inside = false;
  25506. const px = (a.x + b.x) / 2;
  25507. const py = (a.y + b.y) / 2;
  25508. do {
  25509. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25510. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25511. inside = !inside;
  25512. p = p.next;
  25513. } while (p !== a);
  25514. return inside;
  25515. }
  25516. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25517. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25518. function splitPolygon(a, b) {
  25519. const a2 = createNode(a.i, a.x, a.y),
  25520. b2 = createNode(b.i, b.x, b.y),
  25521. an = a.next,
  25522. bp = b.prev;
  25523. a.next = b;
  25524. b.prev = a;
  25525. a2.next = an;
  25526. an.prev = a2;
  25527. b2.next = a2;
  25528. a2.prev = b2;
  25529. bp.next = b2;
  25530. b2.prev = bp;
  25531. return b2;
  25532. }
  25533. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25534. function insertNode(i, x, y, last) {
  25535. const p = createNode(i, x, y);
  25536. if (!last) {
  25537. p.prev = p;
  25538. p.next = p;
  25539. } else {
  25540. p.next = last.next;
  25541. p.prev = last;
  25542. last.next.prev = p;
  25543. last.next = p;
  25544. }
  25545. return p;
  25546. }
  25547. function removeNode(p) {
  25548. p.next.prev = p.prev;
  25549. p.prev.next = p.next;
  25550. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25551. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25552. }
  25553. function createNode(i, x, y) {
  25554. return {
  25555. i, // vertex index in coordinates array
  25556. x, y, // vertex coordinates
  25557. prev: null, // previous and next vertex nodes in a polygon ring
  25558. next: null,
  25559. z: 0, // z-order curve value
  25560. prevZ: null, // previous and next nodes in z-order
  25561. nextZ: null,
  25562. steiner: false // indicates whether this is a steiner point
  25563. };
  25564. }
  25565. function signedArea(data, start, end, dim) {
  25566. let sum = 0;
  25567. for (let i = start, j = end - dim; i < end; i += dim) {
  25568. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25569. j = i;
  25570. }
  25571. return sum;
  25572. }
  25573. class Earcut {
  25574. /**
  25575. * Triangulates the given shape definition by returning an array of triangles.
  25576. *
  25577. * @param {Array<number>} data - An array with 2D points.
  25578. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25579. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25580. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25581. * representing vertex indices.
  25582. */
  25583. static triangulate( data, holeIndices, dim = 2 ) {
  25584. return earcut( data, holeIndices, dim );
  25585. }
  25586. }
  25587. /**
  25588. * A class containing utility functions for shapes.
  25589. *
  25590. * @hideconstructor
  25591. */
  25592. class ShapeUtils {
  25593. /**
  25594. * Calculate area of a ( 2D ) contour polygon.
  25595. *
  25596. * @param {Array<Vector2>} contour - An array of 2D points.
  25597. * @return {number} The area.
  25598. */
  25599. static area( contour ) {
  25600. const n = contour.length;
  25601. let a = 0.0;
  25602. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25603. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25604. }
  25605. return a * 0.5;
  25606. }
  25607. /**
  25608. * Returns `true` if the given contour uses a clockwise winding order.
  25609. *
  25610. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25611. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25612. */
  25613. static isClockWise( pts ) {
  25614. return ShapeUtils.area( pts ) < 0;
  25615. }
  25616. /**
  25617. * Triangulates the given shape definition.
  25618. *
  25619. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25620. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25621. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25622. */
  25623. static triangulateShape( contour, holes ) {
  25624. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25625. const holeIndices = []; // array of hole indices
  25626. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25627. removeDupEndPts( contour );
  25628. addContour( vertices, contour );
  25629. //
  25630. let holeIndex = contour.length;
  25631. holes.forEach( removeDupEndPts );
  25632. for ( let i = 0; i < holes.length; i ++ ) {
  25633. holeIndices.push( holeIndex );
  25634. holeIndex += holes[ i ].length;
  25635. addContour( vertices, holes[ i ] );
  25636. }
  25637. //
  25638. const triangles = Earcut.triangulate( vertices, holeIndices );
  25639. //
  25640. for ( let i = 0; i < triangles.length; i += 3 ) {
  25641. faces.push( triangles.slice( i, i + 3 ) );
  25642. }
  25643. return faces;
  25644. }
  25645. }
  25646. function removeDupEndPts( points ) {
  25647. const l = points.length;
  25648. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25649. points.pop();
  25650. }
  25651. }
  25652. function addContour( vertices, contour ) {
  25653. for ( let i = 0; i < contour.length; i ++ ) {
  25654. vertices.push( contour[ i ].x );
  25655. vertices.push( contour[ i ].y );
  25656. }
  25657. }
  25658. /**
  25659. * Creates extruded geometry from a path shape.
  25660. *
  25661. * ```js
  25662. * const length = 12, width = 8;
  25663. *
  25664. * const shape = new THREE.Shape();
  25665. * shape.moveTo( 0,0 );
  25666. * shape.lineTo( 0, width );
  25667. * shape.lineTo( length, width );
  25668. * shape.lineTo( length, 0 );
  25669. * shape.lineTo( 0, 0 );
  25670. *
  25671. * const geometry = new THREE.ExtrudeGeometry( shape );
  25672. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25673. * const mesh = new THREE.Mesh( geometry, material ) ;
  25674. * scene.add( mesh );
  25675. * ```
  25676. *
  25677. * @augments BufferGeometry
  25678. */
  25679. class ExtrudeGeometry extends BufferGeometry {
  25680. /**
  25681. * Constructs a new extrude geometry.
  25682. *
  25683. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25684. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25685. */
  25686. 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 = {} ) {
  25687. super();
  25688. this.type = 'ExtrudeGeometry';
  25689. /**
  25690. * Holds the constructor parameters that have been
  25691. * used to generate the geometry. Any modification
  25692. * after instantiation does not change the geometry.
  25693. *
  25694. * @type {Object}
  25695. */
  25696. this.parameters = {
  25697. shapes: shapes,
  25698. options: options
  25699. };
  25700. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25701. const scope = this;
  25702. const verticesArray = [];
  25703. const uvArray = [];
  25704. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25705. const shape = shapes[ i ];
  25706. addShape( shape );
  25707. }
  25708. // build geometry
  25709. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25710. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25711. this.computeVertexNormals();
  25712. // functions
  25713. function addShape( shape ) {
  25714. const placeholder = [];
  25715. // options
  25716. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25717. const steps = options.steps !== undefined ? options.steps : 1;
  25718. const depth = options.depth !== undefined ? options.depth : 1;
  25719. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25720. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25721. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25722. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25723. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25724. const extrudePath = options.extrudePath;
  25725. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25726. //
  25727. let extrudePts, extrudeByPath = false;
  25728. let splineTube, binormal, normal, position2;
  25729. if ( extrudePath ) {
  25730. extrudePts = extrudePath.getSpacedPoints( steps );
  25731. extrudeByPath = true;
  25732. bevelEnabled = false; // bevels not supported for path extrusion
  25733. // SETUP TNB variables
  25734. // TODO1 - have a .isClosed in spline?
  25735. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25736. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25737. binormal = new Vector3();
  25738. normal = new Vector3();
  25739. position2 = new Vector3();
  25740. }
  25741. // Safeguards if bevels are not enabled
  25742. if ( ! bevelEnabled ) {
  25743. bevelSegments = 0;
  25744. bevelThickness = 0;
  25745. bevelSize = 0;
  25746. bevelOffset = 0;
  25747. }
  25748. // Variables initialization
  25749. const shapePoints = shape.extractPoints( curveSegments );
  25750. let vertices = shapePoints.shape;
  25751. const holes = shapePoints.holes;
  25752. const reverse = ! ShapeUtils.isClockWise( vertices );
  25753. if ( reverse ) {
  25754. vertices = vertices.reverse();
  25755. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25756. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25757. const ahole = holes[ h ];
  25758. if ( ShapeUtils.isClockWise( ahole ) ) {
  25759. holes[ h ] = ahole.reverse();
  25760. }
  25761. }
  25762. }
  25763. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  25764. * @param {Array<Vector2>} points
  25765. */
  25766. function mergeOverlappingPoints( points ) {
  25767. const THRESHOLD = 1e-10;
  25768. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25769. let prevPos = points[ 0 ];
  25770. for ( let i = 1; i <= points.length; i ++ ) {
  25771. const currentIndex = i % points.length;
  25772. const currentPos = points[ currentIndex ];
  25773. const dx = currentPos.x - prevPos.x;
  25774. const dy = currentPos.y - prevPos.y;
  25775. const distSq = dx * dx + dy * dy;
  25776. const scalingFactorSqrt = Math.max(
  25777. Math.abs( currentPos.x ),
  25778. Math.abs( currentPos.y ),
  25779. Math.abs( prevPos.x ),
  25780. Math.abs( prevPos.y )
  25781. );
  25782. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25783. if ( distSq <= thresholdSqScaled ) {
  25784. points.splice( currentIndex, 1 );
  25785. i --;
  25786. continue;
  25787. }
  25788. prevPos = currentPos;
  25789. }
  25790. }
  25791. mergeOverlappingPoints( vertices );
  25792. holes.forEach( mergeOverlappingPoints );
  25793. const numHoles = holes.length;
  25794. /* Vertices */
  25795. const contour = vertices; // vertices has all points but contour has only points of circumference
  25796. for ( let h = 0; h < numHoles; h ++ ) {
  25797. const ahole = holes[ h ];
  25798. vertices = vertices.concat( ahole );
  25799. }
  25800. function scalePt2( pt, vec, size ) {
  25801. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25802. return pt.clone().addScaledVector( vec, size );
  25803. }
  25804. const vlen = vertices.length;
  25805. // Find directions for point movement
  25806. function getBevelVec( inPt, inPrev, inNext ) {
  25807. // computes for inPt the corresponding point inPt' on a new contour
  25808. // shifted by 1 unit (length of normalized vector) to the left
  25809. // if we walk along contour clockwise, this new contour is outside the old one
  25810. //
  25811. // inPt' is the intersection of the two lines parallel to the two
  25812. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25813. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25814. // good reading for geometry algorithms (here: line-line intersection)
  25815. // http://geomalgorithms.com/a05-_intersect-1.html
  25816. const v_prev_x = inPt.x - inPrev.x,
  25817. v_prev_y = inPt.y - inPrev.y;
  25818. const v_next_x = inNext.x - inPt.x,
  25819. v_next_y = inNext.y - inPt.y;
  25820. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25821. // check for collinear edges
  25822. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25823. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25824. // not collinear
  25825. // length of vectors for normalizing
  25826. const v_prev_len = Math.sqrt( v_prev_lensq );
  25827. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25828. // shift adjacent points by unit vectors to the left
  25829. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25830. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25831. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25832. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25833. // scaling factor for v_prev to intersection point
  25834. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25835. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25836. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25837. // vector from inPt to intersection point
  25838. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25839. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25840. // Don't normalize!, otherwise sharp corners become ugly
  25841. // but prevent crazy spikes
  25842. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25843. if ( v_trans_lensq <= 2 ) {
  25844. return new Vector2( v_trans_x, v_trans_y );
  25845. } else {
  25846. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25847. }
  25848. } else {
  25849. // handle special case of collinear edges
  25850. let direction_eq = false; // assumes: opposite
  25851. if ( v_prev_x > Number.EPSILON ) {
  25852. if ( v_next_x > Number.EPSILON ) {
  25853. direction_eq = true;
  25854. }
  25855. } else {
  25856. if ( v_prev_x < - Number.EPSILON ) {
  25857. if ( v_next_x < - Number.EPSILON ) {
  25858. direction_eq = true;
  25859. }
  25860. } else {
  25861. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25862. direction_eq = true;
  25863. }
  25864. }
  25865. }
  25866. if ( direction_eq ) {
  25867. // console.log("Warning: lines are a straight sequence");
  25868. v_trans_x = - v_prev_y;
  25869. v_trans_y = v_prev_x;
  25870. shrink_by = Math.sqrt( v_prev_lensq );
  25871. } else {
  25872. // console.log("Warning: lines are a straight spike");
  25873. v_trans_x = v_prev_x;
  25874. v_trans_y = v_prev_y;
  25875. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25876. }
  25877. }
  25878. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25879. }
  25880. const contourMovements = [];
  25881. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25882. if ( j === il ) j = 0;
  25883. if ( k === il ) k = 0;
  25884. // (j)---(i)---(k)
  25885. // console.log('i,j,k', i, j , k)
  25886. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25887. }
  25888. const holesMovements = [];
  25889. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25890. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25891. const ahole = holes[ h ];
  25892. oneHoleMovements = [];
  25893. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25894. if ( j === il ) j = 0;
  25895. if ( k === il ) k = 0;
  25896. // (j)---(i)---(k)
  25897. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25898. }
  25899. holesMovements.push( oneHoleMovements );
  25900. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25901. }
  25902. let faces;
  25903. if ( bevelSegments === 0 ) {
  25904. faces = ShapeUtils.triangulateShape( contour, holes );
  25905. } else {
  25906. const contractedContourVertices = [];
  25907. const expandedHoleVertices = [];
  25908. // Loop bevelSegments, 1 for the front, 1 for the back
  25909. for ( let b = 0; b < bevelSegments; b ++ ) {
  25910. //for ( b = bevelSegments; b > 0; b -- ) {
  25911. const t = b / bevelSegments;
  25912. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25913. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25914. // contract shape
  25915. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25916. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25917. v( vert.x, vert.y, - z );
  25918. if ( t === 0 ) contractedContourVertices.push( vert );
  25919. }
  25920. // expand holes
  25921. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25922. const ahole = holes[ h ];
  25923. oneHoleMovements = holesMovements[ h ];
  25924. const oneHoleVertices = [];
  25925. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25926. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25927. v( vert.x, vert.y, - z );
  25928. if ( t === 0 ) oneHoleVertices.push( vert );
  25929. }
  25930. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25931. }
  25932. }
  25933. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25934. }
  25935. const flen = faces.length;
  25936. const bs = bevelSize + bevelOffset;
  25937. // Back facing vertices
  25938. for ( let i = 0; i < vlen; i ++ ) {
  25939. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25940. if ( ! extrudeByPath ) {
  25941. v( vert.x, vert.y, 0 );
  25942. } else {
  25943. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25944. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25945. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25946. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25947. v( position2.x, position2.y, position2.z );
  25948. }
  25949. }
  25950. // Add stepped vertices...
  25951. // Including front facing vertices
  25952. for ( let s = 1; s <= steps; s ++ ) {
  25953. for ( let i = 0; i < vlen; i ++ ) {
  25954. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25955. if ( ! extrudeByPath ) {
  25956. v( vert.x, vert.y, depth / steps * s );
  25957. } else {
  25958. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25959. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25960. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25961. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25962. v( position2.x, position2.y, position2.z );
  25963. }
  25964. }
  25965. }
  25966. // Add bevel segments planes
  25967. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25968. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25969. const t = b / bevelSegments;
  25970. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25971. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25972. // contract shape
  25973. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25974. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25975. v( vert.x, vert.y, depth + z );
  25976. }
  25977. // expand holes
  25978. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25979. const ahole = holes[ h ];
  25980. oneHoleMovements = holesMovements[ h ];
  25981. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25982. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25983. if ( ! extrudeByPath ) {
  25984. v( vert.x, vert.y, depth + z );
  25985. } else {
  25986. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25987. }
  25988. }
  25989. }
  25990. }
  25991. /* Faces */
  25992. // Top and bottom faces
  25993. buildLidFaces();
  25994. // Sides faces
  25995. buildSideFaces();
  25996. ///// Internal functions
  25997. function buildLidFaces() {
  25998. const start = verticesArray.length / 3;
  25999. if ( bevelEnabled ) {
  26000. let layer = 0; // steps + 1
  26001. let offset = vlen * layer;
  26002. // Bottom faces
  26003. for ( let i = 0; i < flen; i ++ ) {
  26004. const face = faces[ i ];
  26005. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26006. }
  26007. layer = steps + bevelSegments * 2;
  26008. offset = vlen * layer;
  26009. // Top faces
  26010. for ( let i = 0; i < flen; i ++ ) {
  26011. const face = faces[ i ];
  26012. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26013. }
  26014. } else {
  26015. // Bottom faces
  26016. for ( let i = 0; i < flen; i ++ ) {
  26017. const face = faces[ i ];
  26018. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26019. }
  26020. // Top faces
  26021. for ( let i = 0; i < flen; i ++ ) {
  26022. const face = faces[ i ];
  26023. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26024. }
  26025. }
  26026. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26027. }
  26028. // Create faces for the z-sides of the shape
  26029. function buildSideFaces() {
  26030. const start = verticesArray.length / 3;
  26031. let layeroffset = 0;
  26032. sidewalls( contour, layeroffset );
  26033. layeroffset += contour.length;
  26034. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26035. const ahole = holes[ h ];
  26036. sidewalls( ahole, layeroffset );
  26037. //, true
  26038. layeroffset += ahole.length;
  26039. }
  26040. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26041. }
  26042. function sidewalls( contour, layeroffset ) {
  26043. let i = contour.length;
  26044. while ( -- i >= 0 ) {
  26045. const j = i;
  26046. let k = i - 1;
  26047. if ( k < 0 ) k = contour.length - 1;
  26048. //console.log('b', i,j, i-1, k,vertices.length);
  26049. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26050. const slen1 = vlen * s;
  26051. const slen2 = vlen * ( s + 1 );
  26052. const a = layeroffset + j + slen1,
  26053. b = layeroffset + k + slen1,
  26054. c = layeroffset + k + slen2,
  26055. d = layeroffset + j + slen2;
  26056. f4( a, b, c, d );
  26057. }
  26058. }
  26059. }
  26060. function v( x, y, z ) {
  26061. placeholder.push( x );
  26062. placeholder.push( y );
  26063. placeholder.push( z );
  26064. }
  26065. function f3( a, b, c ) {
  26066. addVertex( a );
  26067. addVertex( b );
  26068. addVertex( c );
  26069. const nextIndex = verticesArray.length / 3;
  26070. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26071. addUV( uvs[ 0 ] );
  26072. addUV( uvs[ 1 ] );
  26073. addUV( uvs[ 2 ] );
  26074. }
  26075. function f4( a, b, c, d ) {
  26076. addVertex( a );
  26077. addVertex( b );
  26078. addVertex( d );
  26079. addVertex( b );
  26080. addVertex( c );
  26081. addVertex( d );
  26082. const nextIndex = verticesArray.length / 3;
  26083. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26084. addUV( uvs[ 0 ] );
  26085. addUV( uvs[ 1 ] );
  26086. addUV( uvs[ 3 ] );
  26087. addUV( uvs[ 1 ] );
  26088. addUV( uvs[ 2 ] );
  26089. addUV( uvs[ 3 ] );
  26090. }
  26091. function addVertex( index ) {
  26092. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26093. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26094. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26095. }
  26096. function addUV( vector2 ) {
  26097. uvArray.push( vector2.x );
  26098. uvArray.push( vector2.y );
  26099. }
  26100. }
  26101. }
  26102. copy( source ) {
  26103. super.copy( source );
  26104. this.parameters = Object.assign( {}, source.parameters );
  26105. return this;
  26106. }
  26107. toJSON() {
  26108. const data = super.toJSON();
  26109. const shapes = this.parameters.shapes;
  26110. const options = this.parameters.options;
  26111. return toJSON$1( shapes, options, data );
  26112. }
  26113. /**
  26114. * Factory method for creating an instance of this class from the given
  26115. * JSON object.
  26116. *
  26117. * @param {Object} data - A JSON object representing the serialized geometry.
  26118. * @param {Array<Shape>} shapes - An array of shapes.
  26119. * @return {ExtrudeGeometry} A new instance.
  26120. */
  26121. static fromJSON( data, shapes ) {
  26122. const geometryShapes = [];
  26123. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26124. const shape = shapes[ data.shapes[ j ] ];
  26125. geometryShapes.push( shape );
  26126. }
  26127. const extrudePath = data.options.extrudePath;
  26128. if ( extrudePath !== undefined ) {
  26129. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26130. }
  26131. return new ExtrudeGeometry( geometryShapes, data.options );
  26132. }
  26133. }
  26134. const WorldUVGenerator = {
  26135. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26136. const a_x = vertices[ indexA * 3 ];
  26137. const a_y = vertices[ indexA * 3 + 1 ];
  26138. const b_x = vertices[ indexB * 3 ];
  26139. const b_y = vertices[ indexB * 3 + 1 ];
  26140. const c_x = vertices[ indexC * 3 ];
  26141. const c_y = vertices[ indexC * 3 + 1 ];
  26142. return [
  26143. new Vector2( a_x, a_y ),
  26144. new Vector2( b_x, b_y ),
  26145. new Vector2( c_x, c_y )
  26146. ];
  26147. },
  26148. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26149. const a_x = vertices[ indexA * 3 ];
  26150. const a_y = vertices[ indexA * 3 + 1 ];
  26151. const a_z = vertices[ indexA * 3 + 2 ];
  26152. const b_x = vertices[ indexB * 3 ];
  26153. const b_y = vertices[ indexB * 3 + 1 ];
  26154. const b_z = vertices[ indexB * 3 + 2 ];
  26155. const c_x = vertices[ indexC * 3 ];
  26156. const c_y = vertices[ indexC * 3 + 1 ];
  26157. const c_z = vertices[ indexC * 3 + 2 ];
  26158. const d_x = vertices[ indexD * 3 ];
  26159. const d_y = vertices[ indexD * 3 + 1 ];
  26160. const d_z = vertices[ indexD * 3 + 2 ];
  26161. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26162. return [
  26163. new Vector2( a_x, 1 - a_z ),
  26164. new Vector2( b_x, 1 - b_z ),
  26165. new Vector2( c_x, 1 - c_z ),
  26166. new Vector2( d_x, 1 - d_z )
  26167. ];
  26168. } else {
  26169. return [
  26170. new Vector2( a_y, 1 - a_z ),
  26171. new Vector2( b_y, 1 - b_z ),
  26172. new Vector2( c_y, 1 - c_z ),
  26173. new Vector2( d_y, 1 - d_z )
  26174. ];
  26175. }
  26176. }
  26177. };
  26178. function toJSON$1( shapes, options, data ) {
  26179. data.shapes = [];
  26180. if ( Array.isArray( shapes ) ) {
  26181. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26182. const shape = shapes[ i ];
  26183. data.shapes.push( shape.uuid );
  26184. }
  26185. } else {
  26186. data.shapes.push( shapes.uuid );
  26187. }
  26188. data.options = Object.assign( {}, options );
  26189. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26190. return data;
  26191. }
  26192. /**
  26193. * A geometry class for representing an icosahedron.
  26194. *
  26195. * ```js
  26196. * const geometry = new THREE.IcosahedronGeometry();
  26197. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26198. * const icosahedron = new THREE.Mesh( geometry, material );
  26199. * scene.add( icosahedron );
  26200. * ```
  26201. *
  26202. * @augments PolyhedronGeometry
  26203. */
  26204. class IcosahedronGeometry extends PolyhedronGeometry {
  26205. /**
  26206. * Constructs a new icosahedron geometry.
  26207. *
  26208. * @param {number} [radius=1] - Radius of the icosahedron.
  26209. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26210. */
  26211. constructor( radius = 1, detail = 0 ) {
  26212. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26213. const vertices = [
  26214. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26215. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26216. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26217. ];
  26218. const indices = [
  26219. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26220. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26221. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26222. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26223. ];
  26224. super( vertices, indices, radius, detail );
  26225. this.type = 'IcosahedronGeometry';
  26226. /**
  26227. * Holds the constructor parameters that have been
  26228. * used to generate the geometry. Any modification
  26229. * after instantiation does not change the geometry.
  26230. *
  26231. * @type {Object}
  26232. */
  26233. this.parameters = {
  26234. radius: radius,
  26235. detail: detail
  26236. };
  26237. }
  26238. /**
  26239. * Factory method for creating an instance of this class from the given
  26240. * JSON object.
  26241. *
  26242. * @param {Object} data - A JSON object representing the serialized geometry.
  26243. * @return {IcosahedronGeometry} A new instance.
  26244. */
  26245. static fromJSON( data ) {
  26246. return new IcosahedronGeometry( data.radius, data.detail );
  26247. }
  26248. }
  26249. /**
  26250. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26251. *
  26252. * ```js
  26253. * const points = [];
  26254. * for ( let i = 0; i < 10; i ++ ) {
  26255. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26256. * }
  26257. * const geometry = new THREE.LatheGeometry( points );
  26258. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26259. * const lathe = new THREE.Mesh( geometry, material );
  26260. * scene.add( lathe );
  26261. * ```
  26262. *
  26263. * @augments BufferGeometry
  26264. */
  26265. class LatheGeometry extends BufferGeometry {
  26266. /**
  26267. * Constructs a new lathe geometry.
  26268. *
  26269. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26270. * must be greater than zero.
  26271. * @param {number} [segments=12] - The number of circumference segments to generate.
  26272. * @param {number} [phiStart=0] - The starting angle in radians.
  26273. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26274. * closed lathe, less than 2PI is a portion.
  26275. */
  26276. 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 ) {
  26277. super();
  26278. this.type = 'LatheGeometry';
  26279. /**
  26280. * Holds the constructor parameters that have been
  26281. * used to generate the geometry. Any modification
  26282. * after instantiation does not change the geometry.
  26283. *
  26284. * @type {Object}
  26285. */
  26286. this.parameters = {
  26287. points: points,
  26288. segments: segments,
  26289. phiStart: phiStart,
  26290. phiLength: phiLength
  26291. };
  26292. segments = Math.floor( segments );
  26293. // clamp phiLength so it's in range of [ 0, 2PI ]
  26294. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26295. // buffers
  26296. const indices = [];
  26297. const vertices = [];
  26298. const uvs = [];
  26299. const initNormals = [];
  26300. const normals = [];
  26301. // helper variables
  26302. const inverseSegments = 1.0 / segments;
  26303. const vertex = new Vector3();
  26304. const uv = new Vector2();
  26305. const normal = new Vector3();
  26306. const curNormal = new Vector3();
  26307. const prevNormal = new Vector3();
  26308. let dx = 0;
  26309. let dy = 0;
  26310. // pre-compute normals for initial "meridian"
  26311. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26312. switch ( j ) {
  26313. case 0: // special handling for 1st vertex on path
  26314. dx = points[ j + 1 ].x - points[ j ].x;
  26315. dy = points[ j + 1 ].y - points[ j ].y;
  26316. normal.x = dy * 1.0;
  26317. normal.y = - dx;
  26318. normal.z = dy * 0.0;
  26319. prevNormal.copy( normal );
  26320. normal.normalize();
  26321. initNormals.push( normal.x, normal.y, normal.z );
  26322. break;
  26323. case ( points.length - 1 ): // special handling for last Vertex on path
  26324. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26325. break;
  26326. default: // default handling for all vertices in between
  26327. dx = points[ j + 1 ].x - points[ j ].x;
  26328. dy = points[ j + 1 ].y - points[ j ].y;
  26329. normal.x = dy * 1.0;
  26330. normal.y = - dx;
  26331. normal.z = dy * 0.0;
  26332. curNormal.copy( normal );
  26333. normal.x += prevNormal.x;
  26334. normal.y += prevNormal.y;
  26335. normal.z += prevNormal.z;
  26336. normal.normalize();
  26337. initNormals.push( normal.x, normal.y, normal.z );
  26338. prevNormal.copy( curNormal );
  26339. }
  26340. }
  26341. // generate vertices, uvs and normals
  26342. for ( let i = 0; i <= segments; i ++ ) {
  26343. const phi = phiStart + i * inverseSegments * phiLength;
  26344. const sin = Math.sin( phi );
  26345. const cos = Math.cos( phi );
  26346. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26347. // vertex
  26348. vertex.x = points[ j ].x * sin;
  26349. vertex.y = points[ j ].y;
  26350. vertex.z = points[ j ].x * cos;
  26351. vertices.push( vertex.x, vertex.y, vertex.z );
  26352. // uv
  26353. uv.x = i / segments;
  26354. uv.y = j / ( points.length - 1 );
  26355. uvs.push( uv.x, uv.y );
  26356. // normal
  26357. const x = initNormals[ 3 * j + 0 ] * sin;
  26358. const y = initNormals[ 3 * j + 1 ];
  26359. const z = initNormals[ 3 * j + 0 ] * cos;
  26360. normals.push( x, y, z );
  26361. }
  26362. }
  26363. // indices
  26364. for ( let i = 0; i < segments; i ++ ) {
  26365. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26366. const base = j + i * points.length;
  26367. const a = base;
  26368. const b = base + points.length;
  26369. const c = base + points.length + 1;
  26370. const d = base + 1;
  26371. // faces
  26372. indices.push( a, b, d );
  26373. indices.push( c, d, b );
  26374. }
  26375. }
  26376. // build geometry
  26377. this.setIndex( indices );
  26378. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26379. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26380. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26381. }
  26382. copy( source ) {
  26383. super.copy( source );
  26384. this.parameters = Object.assign( {}, source.parameters );
  26385. return this;
  26386. }
  26387. /**
  26388. * Factory method for creating an instance of this class from the given
  26389. * JSON object.
  26390. *
  26391. * @param {Object} data - A JSON object representing the serialized geometry.
  26392. * @return {LatheGeometry} A new instance.
  26393. */
  26394. static fromJSON( data ) {
  26395. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26396. }
  26397. }
  26398. /**
  26399. * A geometry class for representing an octahedron.
  26400. *
  26401. * ```js
  26402. * const geometry = new THREE.OctahedronGeometry();
  26403. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26404. * const octahedron = new THREE.Mesh( geometry, material );
  26405. * scene.add( octahedron );
  26406. * ```
  26407. *
  26408. * @augments PolyhedronGeometry
  26409. */
  26410. class OctahedronGeometry extends PolyhedronGeometry {
  26411. /**
  26412. * Constructs a new octahedron geometry.
  26413. *
  26414. * @param {number} [radius=1] - Radius of the octahedron.
  26415. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26416. */
  26417. constructor( radius = 1, detail = 0 ) {
  26418. const vertices = [
  26419. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26420. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26421. ];
  26422. const indices = [
  26423. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26424. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26425. 1, 3, 4, 1, 4, 2
  26426. ];
  26427. super( vertices, indices, radius, detail );
  26428. this.type = 'OctahedronGeometry';
  26429. /**
  26430. * Holds the constructor parameters that have been
  26431. * used to generate the geometry. Any modification
  26432. * after instantiation does not change the geometry.
  26433. *
  26434. * @type {Object}
  26435. */
  26436. this.parameters = {
  26437. radius: radius,
  26438. detail: detail
  26439. };
  26440. }
  26441. /**
  26442. * Factory method for creating an instance of this class from the given
  26443. * JSON object.
  26444. *
  26445. * @param {Object} data - A JSON object representing the serialized geometry.
  26446. * @return {OctahedronGeometry} A new instance.
  26447. */
  26448. static fromJSON( data ) {
  26449. return new OctahedronGeometry( data.radius, data.detail );
  26450. }
  26451. }
  26452. /**
  26453. * A geometry class for representing a plane.
  26454. *
  26455. * ```js
  26456. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26457. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26458. * const plane = new THREE.Mesh( geometry, material );
  26459. * scene.add( plane );
  26460. * ```
  26461. *
  26462. * @augments BufferGeometry
  26463. */
  26464. class PlaneGeometry extends BufferGeometry {
  26465. /**
  26466. * Constructs a new plane geometry.
  26467. *
  26468. * @param {number} [width=1] - The width along the X axis.
  26469. * @param {number} [height=1] - The height along the Y axis
  26470. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26471. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26472. */
  26473. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26474. super();
  26475. this.type = 'PlaneGeometry';
  26476. /**
  26477. * Holds the constructor parameters that have been
  26478. * used to generate the geometry. Any modification
  26479. * after instantiation does not change the geometry.
  26480. *
  26481. * @type {Object}
  26482. */
  26483. this.parameters = {
  26484. width: width,
  26485. height: height,
  26486. widthSegments: widthSegments,
  26487. heightSegments: heightSegments
  26488. };
  26489. const width_half = width / 2;
  26490. const height_half = height / 2;
  26491. const gridX = Math.floor( widthSegments );
  26492. const gridY = Math.floor( heightSegments );
  26493. const gridX1 = gridX + 1;
  26494. const gridY1 = gridY + 1;
  26495. const segment_width = width / gridX;
  26496. const segment_height = height / gridY;
  26497. //
  26498. const indices = [];
  26499. const vertices = [];
  26500. const normals = [];
  26501. const uvs = [];
  26502. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26503. const y = iy * segment_height - height_half;
  26504. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26505. const x = ix * segment_width - width_half;
  26506. vertices.push( x, - y, 0 );
  26507. normals.push( 0, 0, 1 );
  26508. uvs.push( ix / gridX );
  26509. uvs.push( 1 - ( iy / gridY ) );
  26510. }
  26511. }
  26512. for ( let iy = 0; iy < gridY; iy ++ ) {
  26513. for ( let ix = 0; ix < gridX; ix ++ ) {
  26514. const a = ix + gridX1 * iy;
  26515. const b = ix + gridX1 * ( iy + 1 );
  26516. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26517. const d = ( ix + 1 ) + gridX1 * iy;
  26518. indices.push( a, b, d );
  26519. indices.push( b, c, d );
  26520. }
  26521. }
  26522. this.setIndex( indices );
  26523. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26524. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26525. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26526. }
  26527. copy( source ) {
  26528. super.copy( source );
  26529. this.parameters = Object.assign( {}, source.parameters );
  26530. return this;
  26531. }
  26532. /**
  26533. * Factory method for creating an instance of this class from the given
  26534. * JSON object.
  26535. *
  26536. * @param {Object} data - A JSON object representing the serialized geometry.
  26537. * @return {PlaneGeometry} A new instance.
  26538. */
  26539. static fromJSON( data ) {
  26540. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26541. }
  26542. }
  26543. /**
  26544. * A class for generating a two-dimensional ring geometry.
  26545. *
  26546. * ```js
  26547. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26548. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26549. * const mesh = new THREE.Mesh( geometry, material );
  26550. * scene.add( mesh );
  26551. * ```
  26552. *
  26553. * @augments BufferGeometry
  26554. */
  26555. class RingGeometry extends BufferGeometry {
  26556. /**
  26557. * Constructs a new ring geometry.
  26558. *
  26559. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26560. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26561. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26562. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26563. * @param {number} [thetaStart=0] - Starting angle in radians.
  26564. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26565. */
  26566. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26567. super();
  26568. this.type = 'RingGeometry';
  26569. /**
  26570. * Holds the constructor parameters that have been
  26571. * used to generate the geometry. Any modification
  26572. * after instantiation does not change the geometry.
  26573. *
  26574. * @type {Object}
  26575. */
  26576. this.parameters = {
  26577. innerRadius: innerRadius,
  26578. outerRadius: outerRadius,
  26579. thetaSegments: thetaSegments,
  26580. phiSegments: phiSegments,
  26581. thetaStart: thetaStart,
  26582. thetaLength: thetaLength
  26583. };
  26584. thetaSegments = Math.max( 3, thetaSegments );
  26585. phiSegments = Math.max( 1, phiSegments );
  26586. // buffers
  26587. const indices = [];
  26588. const vertices = [];
  26589. const normals = [];
  26590. const uvs = [];
  26591. // some helper variables
  26592. let radius = innerRadius;
  26593. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26594. const vertex = new Vector3();
  26595. const uv = new Vector2();
  26596. // generate vertices, normals and uvs
  26597. for ( let j = 0; j <= phiSegments; j ++ ) {
  26598. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26599. // values are generate from the inside of the ring to the outside
  26600. const segment = thetaStart + i / thetaSegments * thetaLength;
  26601. // vertex
  26602. vertex.x = radius * Math.cos( segment );
  26603. vertex.y = radius * Math.sin( segment );
  26604. vertices.push( vertex.x, vertex.y, vertex.z );
  26605. // normal
  26606. normals.push( 0, 0, 1 );
  26607. // uv
  26608. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26609. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26610. uvs.push( uv.x, uv.y );
  26611. }
  26612. // increase the radius for next row of vertices
  26613. radius += radiusStep;
  26614. }
  26615. // indices
  26616. for ( let j = 0; j < phiSegments; j ++ ) {
  26617. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26618. for ( let i = 0; i < thetaSegments; i ++ ) {
  26619. const segment = i + thetaSegmentLevel;
  26620. const a = segment;
  26621. const b = segment + thetaSegments + 1;
  26622. const c = segment + thetaSegments + 2;
  26623. const d = segment + 1;
  26624. // faces
  26625. indices.push( a, b, d );
  26626. indices.push( b, c, d );
  26627. }
  26628. }
  26629. // build geometry
  26630. this.setIndex( indices );
  26631. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26632. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26633. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26634. }
  26635. copy( source ) {
  26636. super.copy( source );
  26637. this.parameters = Object.assign( {}, source.parameters );
  26638. return this;
  26639. }
  26640. /**
  26641. * Factory method for creating an instance of this class from the given
  26642. * JSON object.
  26643. *
  26644. * @param {Object} data - A JSON object representing the serialized geometry.
  26645. * @return {RingGeometry} A new instance.
  26646. */
  26647. static fromJSON( data ) {
  26648. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26649. }
  26650. }
  26651. /**
  26652. * Creates an one-sided polygonal geometry from one or more path shapes.
  26653. *
  26654. * ```js
  26655. * const arcShape = new THREE.Shape()
  26656. * .moveTo( 5, 1 )
  26657. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26658. *
  26659. * const geometry = new THREE.ShapeGeometry( arcShape );
  26660. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26661. * const mesh = new THREE.Mesh( geometry, material ) ;
  26662. * scene.add( mesh );
  26663. * ```
  26664. *
  26665. * @augments BufferGeometry
  26666. */
  26667. class ShapeGeometry extends BufferGeometry {
  26668. /**
  26669. * Constructs a new shape geometry.
  26670. *
  26671. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26672. * @param {number} [curveSegments=12] - Number of segments per shape.
  26673. */
  26674. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26675. super();
  26676. this.type = 'ShapeGeometry';
  26677. /**
  26678. * Holds the constructor parameters that have been
  26679. * used to generate the geometry. Any modification
  26680. * after instantiation does not change the geometry.
  26681. *
  26682. * @type {Object}
  26683. */
  26684. this.parameters = {
  26685. shapes: shapes,
  26686. curveSegments: curveSegments
  26687. };
  26688. // buffers
  26689. const indices = [];
  26690. const vertices = [];
  26691. const normals = [];
  26692. const uvs = [];
  26693. // helper variables
  26694. let groupStart = 0;
  26695. let groupCount = 0;
  26696. // allow single and array values for "shapes" parameter
  26697. if ( Array.isArray( shapes ) === false ) {
  26698. addShape( shapes );
  26699. } else {
  26700. for ( let i = 0; i < shapes.length; i ++ ) {
  26701. addShape( shapes[ i ] );
  26702. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26703. groupStart += groupCount;
  26704. groupCount = 0;
  26705. }
  26706. }
  26707. // build geometry
  26708. this.setIndex( indices );
  26709. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26710. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26711. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26712. // helper functions
  26713. function addShape( shape ) {
  26714. const indexOffset = vertices.length / 3;
  26715. const points = shape.extractPoints( curveSegments );
  26716. let shapeVertices = points.shape;
  26717. const shapeHoles = points.holes;
  26718. // check direction of vertices
  26719. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26720. shapeVertices = shapeVertices.reverse();
  26721. }
  26722. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26723. const shapeHole = shapeHoles[ i ];
  26724. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26725. shapeHoles[ i ] = shapeHole.reverse();
  26726. }
  26727. }
  26728. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26729. // join vertices of inner and outer paths to a single array
  26730. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26731. const shapeHole = shapeHoles[ i ];
  26732. shapeVertices = shapeVertices.concat( shapeHole );
  26733. }
  26734. // vertices, normals, uvs
  26735. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26736. const vertex = shapeVertices[ i ];
  26737. vertices.push( vertex.x, vertex.y, 0 );
  26738. normals.push( 0, 0, 1 );
  26739. uvs.push( vertex.x, vertex.y ); // world uvs
  26740. }
  26741. // indices
  26742. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26743. const face = faces[ i ];
  26744. const a = face[ 0 ] + indexOffset;
  26745. const b = face[ 1 ] + indexOffset;
  26746. const c = face[ 2 ] + indexOffset;
  26747. indices.push( a, b, c );
  26748. groupCount += 3;
  26749. }
  26750. }
  26751. }
  26752. copy( source ) {
  26753. super.copy( source );
  26754. this.parameters = Object.assign( {}, source.parameters );
  26755. return this;
  26756. }
  26757. toJSON() {
  26758. const data = super.toJSON();
  26759. const shapes = this.parameters.shapes;
  26760. return toJSON( shapes, data );
  26761. }
  26762. /**
  26763. * Factory method for creating an instance of this class from the given
  26764. * JSON object.
  26765. *
  26766. * @param {Object} data - A JSON object representing the serialized geometry.
  26767. * @param {Array<Shape>} shapes - An array of shapes.
  26768. * @return {ShapeGeometry} A new instance.
  26769. */
  26770. static fromJSON( data, shapes ) {
  26771. const geometryShapes = [];
  26772. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26773. const shape = shapes[ data.shapes[ j ] ];
  26774. geometryShapes.push( shape );
  26775. }
  26776. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26777. }
  26778. }
  26779. function toJSON( shapes, data ) {
  26780. data.shapes = [];
  26781. if ( Array.isArray( shapes ) ) {
  26782. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26783. const shape = shapes[ i ];
  26784. data.shapes.push( shape.uuid );
  26785. }
  26786. } else {
  26787. data.shapes.push( shapes.uuid );
  26788. }
  26789. return data;
  26790. }
  26791. /**
  26792. * A class for generating a sphere geometry.
  26793. *
  26794. * ```js
  26795. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26796. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26797. * const sphere = new THREE.Mesh( geometry, material );
  26798. * scene.add( sphere );
  26799. * ```
  26800. *
  26801. * @augments BufferGeometry
  26802. */
  26803. class SphereGeometry extends BufferGeometry {
  26804. /**
  26805. * Constructs a new sphere geometry.
  26806. *
  26807. * @param {number} [radius=1] - The sphere radius.
  26808. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26809. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26810. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26811. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26812. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26813. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26814. */
  26815. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26816. super();
  26817. this.type = 'SphereGeometry';
  26818. /**
  26819. * Holds the constructor parameters that have been
  26820. * used to generate the geometry. Any modification
  26821. * after instantiation does not change the geometry.
  26822. *
  26823. * @type {Object}
  26824. */
  26825. this.parameters = {
  26826. radius: radius,
  26827. widthSegments: widthSegments,
  26828. heightSegments: heightSegments,
  26829. phiStart: phiStart,
  26830. phiLength: phiLength,
  26831. thetaStart: thetaStart,
  26832. thetaLength: thetaLength
  26833. };
  26834. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26835. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26836. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26837. let index = 0;
  26838. const grid = [];
  26839. const vertex = new Vector3();
  26840. const normal = new Vector3();
  26841. // buffers
  26842. const indices = [];
  26843. const vertices = [];
  26844. const normals = [];
  26845. const uvs = [];
  26846. // generate vertices, normals and uvs
  26847. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26848. const verticesRow = [];
  26849. const v = iy / heightSegments;
  26850. // special case for the poles
  26851. let uOffset = 0;
  26852. if ( iy === 0 && thetaStart === 0 ) {
  26853. uOffset = 0.5 / widthSegments;
  26854. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26855. uOffset = -0.5 / widthSegments;
  26856. }
  26857. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26858. const u = ix / widthSegments;
  26859. // vertex
  26860. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26861. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26862. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26863. vertices.push( vertex.x, vertex.y, vertex.z );
  26864. // normal
  26865. normal.copy( vertex ).normalize();
  26866. normals.push( normal.x, normal.y, normal.z );
  26867. // uv
  26868. uvs.push( u + uOffset, 1 - v );
  26869. verticesRow.push( index ++ );
  26870. }
  26871. grid.push( verticesRow );
  26872. }
  26873. // indices
  26874. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26875. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26876. const a = grid[ iy ][ ix + 1 ];
  26877. const b = grid[ iy ][ ix ];
  26878. const c = grid[ iy + 1 ][ ix ];
  26879. const d = grid[ iy + 1 ][ ix + 1 ];
  26880. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26881. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26882. }
  26883. }
  26884. // build geometry
  26885. this.setIndex( indices );
  26886. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26887. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26888. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26889. }
  26890. copy( source ) {
  26891. super.copy( source );
  26892. this.parameters = Object.assign( {}, source.parameters );
  26893. return this;
  26894. }
  26895. /**
  26896. * Factory method for creating an instance of this class from the given
  26897. * JSON object.
  26898. *
  26899. * @param {Object} data - A JSON object representing the serialized geometry.
  26900. * @return {SphereGeometry} A new instance.
  26901. */
  26902. static fromJSON( data ) {
  26903. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26904. }
  26905. }
  26906. /**
  26907. * A geometry class for representing an tetrahedron.
  26908. *
  26909. * ```js
  26910. * const geometry = new THREE.TetrahedronGeometry();
  26911. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26912. * const tetrahedron = new THREE.Mesh( geometry, material );
  26913. * scene.add( tetrahedron );
  26914. * ```
  26915. *
  26916. * @augments PolyhedronGeometry
  26917. */
  26918. class TetrahedronGeometry extends PolyhedronGeometry {
  26919. /**
  26920. * Constructs a new tetrahedron geometry.
  26921. *
  26922. * @param {number} [radius=1] - Radius of the tetrahedron.
  26923. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26924. */
  26925. constructor( radius = 1, detail = 0 ) {
  26926. const vertices = [
  26927. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26928. ];
  26929. const indices = [
  26930. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26931. ];
  26932. super( vertices, indices, radius, detail );
  26933. this.type = 'TetrahedronGeometry';
  26934. /**
  26935. * Holds the constructor parameters that have been
  26936. * used to generate the geometry. Any modification
  26937. * after instantiation does not change the geometry.
  26938. *
  26939. * @type {Object}
  26940. */
  26941. this.parameters = {
  26942. radius: radius,
  26943. detail: detail
  26944. };
  26945. }
  26946. /**
  26947. * Factory method for creating an instance of this class from the given
  26948. * JSON object.
  26949. *
  26950. * @param {Object} data - A JSON object representing the serialized geometry.
  26951. * @return {TetrahedronGeometry} A new instance.
  26952. */
  26953. static fromJSON( data ) {
  26954. return new TetrahedronGeometry( data.radius, data.detail );
  26955. }
  26956. }
  26957. /**
  26958. * A geometry class for representing an torus.
  26959. *
  26960. * ```js
  26961. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26962. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26963. * const torus = new THREE.Mesh( geometry, material );
  26964. * scene.add( torus );
  26965. * ```
  26966. *
  26967. * @augments BufferGeometry
  26968. */
  26969. class TorusGeometry extends BufferGeometry {
  26970. /**
  26971. * Constructs a new torus geometry.
  26972. *
  26973. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26974. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26975. * @param {number} [radialSegments=12] - The number of radial segments.
  26976. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26977. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26978. */
  26979. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26980. super();
  26981. this.type = 'TorusGeometry';
  26982. /**
  26983. * Holds the constructor parameters that have been
  26984. * used to generate the geometry. Any modification
  26985. * after instantiation does not change the geometry.
  26986. *
  26987. * @type {Object}
  26988. */
  26989. this.parameters = {
  26990. radius: radius,
  26991. tube: tube,
  26992. radialSegments: radialSegments,
  26993. tubularSegments: tubularSegments,
  26994. arc: arc
  26995. };
  26996. radialSegments = Math.floor( radialSegments );
  26997. tubularSegments = Math.floor( tubularSegments );
  26998. // buffers
  26999. const indices = [];
  27000. const vertices = [];
  27001. const normals = [];
  27002. const uvs = [];
  27003. // helper variables
  27004. const center = new Vector3();
  27005. const vertex = new Vector3();
  27006. const normal = new Vector3();
  27007. // generate vertices, normals and uvs
  27008. for ( let j = 0; j <= radialSegments; j ++ ) {
  27009. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27010. const u = i / tubularSegments * arc;
  27011. const v = j / radialSegments * Math.PI * 2;
  27012. // vertex
  27013. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27014. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27015. vertex.z = tube * Math.sin( v );
  27016. vertices.push( vertex.x, vertex.y, vertex.z );
  27017. // normal
  27018. center.x = radius * Math.cos( u );
  27019. center.y = radius * Math.sin( u );
  27020. normal.subVectors( vertex, center ).normalize();
  27021. normals.push( normal.x, normal.y, normal.z );
  27022. // uv
  27023. uvs.push( i / tubularSegments );
  27024. uvs.push( j / radialSegments );
  27025. }
  27026. }
  27027. // generate indices
  27028. for ( let j = 1; j <= radialSegments; j ++ ) {
  27029. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27030. // indices
  27031. const a = ( tubularSegments + 1 ) * j + i - 1;
  27032. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27033. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27034. const d = ( tubularSegments + 1 ) * j + i;
  27035. // faces
  27036. indices.push( a, b, d );
  27037. indices.push( b, c, d );
  27038. }
  27039. }
  27040. // build geometry
  27041. this.setIndex( indices );
  27042. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27043. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27044. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27045. }
  27046. copy( source ) {
  27047. super.copy( source );
  27048. this.parameters = Object.assign( {}, source.parameters );
  27049. return this;
  27050. }
  27051. /**
  27052. * Factory method for creating an instance of this class from the given
  27053. * JSON object.
  27054. *
  27055. * @param {Object} data - A JSON object representing the serialized geometry.
  27056. * @return {TorusGeometry} A new instance.
  27057. */
  27058. static fromJSON( data ) {
  27059. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27060. }
  27061. }
  27062. /**
  27063. * Creates a torus knot, the particular shape of which is defined by a pair
  27064. * of coprime integers, p and q. If p and q are not coprime, the result will
  27065. * be a torus link.
  27066. *
  27067. * ```js
  27068. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27069. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27070. * const torusKnot = new THREE.Mesh( geometry, material );
  27071. * scene.add( torusKnot );
  27072. * ```
  27073. *
  27074. * @augments BufferGeometry
  27075. */
  27076. class TorusKnotGeometry extends BufferGeometry {
  27077. /**
  27078. * Constructs a new torus knot geometry.
  27079. *
  27080. * @param {number} [radius=1] - Radius of the torus knot.
  27081. * @param {number} [tube=0.4] - Radius of the tube.
  27082. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27083. * @param {number} [radialSegments=8] - The number of radial segments.
  27084. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27085. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27086. */
  27087. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27088. super();
  27089. this.type = 'TorusKnotGeometry';
  27090. /**
  27091. * Holds the constructor parameters that have been
  27092. * used to generate the geometry. Any modification
  27093. * after instantiation does not change the geometry.
  27094. *
  27095. * @type {Object}
  27096. */
  27097. this.parameters = {
  27098. radius: radius,
  27099. tube: tube,
  27100. tubularSegments: tubularSegments,
  27101. radialSegments: radialSegments,
  27102. p: p,
  27103. q: q
  27104. };
  27105. tubularSegments = Math.floor( tubularSegments );
  27106. radialSegments = Math.floor( radialSegments );
  27107. // buffers
  27108. const indices = [];
  27109. const vertices = [];
  27110. const normals = [];
  27111. const uvs = [];
  27112. // helper variables
  27113. const vertex = new Vector3();
  27114. const normal = new Vector3();
  27115. const P1 = new Vector3();
  27116. const P2 = new Vector3();
  27117. const B = new Vector3();
  27118. const T = new Vector3();
  27119. const N = new Vector3();
  27120. // generate vertices, normals and uvs
  27121. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27122. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27123. const u = i / tubularSegments * p * Math.PI * 2;
  27124. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27125. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27126. calculatePositionOnCurve( u, p, q, radius, P1 );
  27127. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27128. // calculate orthonormal basis
  27129. T.subVectors( P2, P1 );
  27130. N.addVectors( P2, P1 );
  27131. B.crossVectors( T, N );
  27132. N.crossVectors( B, T );
  27133. // normalize B, N. T can be ignored, we don't use it
  27134. B.normalize();
  27135. N.normalize();
  27136. for ( let j = 0; j <= radialSegments; ++ j ) {
  27137. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27138. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27139. const v = j / radialSegments * Math.PI * 2;
  27140. const cx = - tube * Math.cos( v );
  27141. const cy = tube * Math.sin( v );
  27142. // now calculate the final vertex position.
  27143. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27144. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27145. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27146. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27147. vertices.push( vertex.x, vertex.y, vertex.z );
  27148. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27149. normal.subVectors( vertex, P1 ).normalize();
  27150. normals.push( normal.x, normal.y, normal.z );
  27151. // uv
  27152. uvs.push( i / tubularSegments );
  27153. uvs.push( j / radialSegments );
  27154. }
  27155. }
  27156. // generate indices
  27157. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27158. for ( let i = 1; i <= radialSegments; i ++ ) {
  27159. // indices
  27160. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27161. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27162. const c = ( radialSegments + 1 ) * j + i;
  27163. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27164. // faces
  27165. indices.push( a, b, d );
  27166. indices.push( b, c, d );
  27167. }
  27168. }
  27169. // build geometry
  27170. this.setIndex( indices );
  27171. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27172. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27173. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27174. // this function calculates the current position on the torus curve
  27175. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27176. const cu = Math.cos( u );
  27177. const su = Math.sin( u );
  27178. const quOverP = q / p * u;
  27179. const cs = Math.cos( quOverP );
  27180. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27181. position.y = radius * ( 2 + cs ) * su * 0.5;
  27182. position.z = radius * Math.sin( quOverP ) * 0.5;
  27183. }
  27184. }
  27185. copy( source ) {
  27186. super.copy( source );
  27187. this.parameters = Object.assign( {}, source.parameters );
  27188. return this;
  27189. }
  27190. /**
  27191. * Factory method for creating an instance of this class from the given
  27192. * JSON object.
  27193. *
  27194. * @param {Object} data - A JSON object representing the serialized geometry.
  27195. * @return {TorusKnotGeometry} A new instance.
  27196. */
  27197. static fromJSON( data ) {
  27198. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27199. }
  27200. }
  27201. /**
  27202. * Creates a tube that extrudes along a 3D curve.
  27203. *
  27204. * ```js
  27205. * class CustomSinCurve extends THREE.Curve {
  27206. *
  27207. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27208. *
  27209. * const tx = t * 3 - 1.5;
  27210. * const ty = Math.sin( 2 * Math.PI * t );
  27211. * const tz = 0;
  27212. *
  27213. * return optionalTarget.set( tx, ty, tz );
  27214. * }
  27215. *
  27216. * }
  27217. *
  27218. * const path = new CustomSinCurve( 10 );
  27219. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27220. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27221. * const mesh = new THREE.Mesh( geometry, material );
  27222. * scene.add( mesh );
  27223. * ```
  27224. *
  27225. * @augments BufferGeometry
  27226. */
  27227. class TubeGeometry extends BufferGeometry {
  27228. /**
  27229. * Constructs a new tube geometry.
  27230. *
  27231. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27232. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27233. * @param {number} [radius=1] -The radius of the tube.
  27234. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27235. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27236. */
  27237. 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 ) {
  27238. super();
  27239. this.type = 'TubeGeometry';
  27240. /**
  27241. * Holds the constructor parameters that have been
  27242. * used to generate the geometry. Any modification
  27243. * after instantiation does not change the geometry.
  27244. *
  27245. * @type {Object}
  27246. */
  27247. this.parameters = {
  27248. path: path,
  27249. tubularSegments: tubularSegments,
  27250. radius: radius,
  27251. radialSegments: radialSegments,
  27252. closed: closed
  27253. };
  27254. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27255. // expose internals
  27256. this.tangents = frames.tangents;
  27257. this.normals = frames.normals;
  27258. this.binormals = frames.binormals;
  27259. // helper variables
  27260. const vertex = new Vector3();
  27261. const normal = new Vector3();
  27262. const uv = new Vector2();
  27263. let P = new Vector3();
  27264. // buffer
  27265. const vertices = [];
  27266. const normals = [];
  27267. const uvs = [];
  27268. const indices = [];
  27269. // create buffer data
  27270. generateBufferData();
  27271. // build geometry
  27272. this.setIndex( indices );
  27273. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27274. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27275. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27276. // functions
  27277. function generateBufferData() {
  27278. for ( let i = 0; i < tubularSegments; i ++ ) {
  27279. generateSegment( i );
  27280. }
  27281. // if the geometry is not closed, generate the last row of vertices and normals
  27282. // at the regular position on the given path
  27283. //
  27284. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27285. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27286. // uvs are generated in a separate function.
  27287. // this makes it easy compute correct values for closed geometries
  27288. generateUVs();
  27289. // finally create faces
  27290. generateIndices();
  27291. }
  27292. function generateSegment( i ) {
  27293. // we use getPointAt to sample evenly distributed points from the given path
  27294. P = path.getPointAt( i / tubularSegments, P );
  27295. // retrieve corresponding normal and binormal
  27296. const N = frames.normals[ i ];
  27297. const B = frames.binormals[ i ];
  27298. // generate normals and vertices for the current segment
  27299. for ( let j = 0; j <= radialSegments; j ++ ) {
  27300. const v = j / radialSegments * Math.PI * 2;
  27301. const sin = Math.sin( v );
  27302. const cos = - Math.cos( v );
  27303. // normal
  27304. normal.x = ( cos * N.x + sin * B.x );
  27305. normal.y = ( cos * N.y + sin * B.y );
  27306. normal.z = ( cos * N.z + sin * B.z );
  27307. normal.normalize();
  27308. normals.push( normal.x, normal.y, normal.z );
  27309. // vertex
  27310. vertex.x = P.x + radius * normal.x;
  27311. vertex.y = P.y + radius * normal.y;
  27312. vertex.z = P.z + radius * normal.z;
  27313. vertices.push( vertex.x, vertex.y, vertex.z );
  27314. }
  27315. }
  27316. function generateIndices() {
  27317. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27318. for ( let i = 1; i <= radialSegments; i ++ ) {
  27319. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27320. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27321. const c = ( radialSegments + 1 ) * j + i;
  27322. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27323. // faces
  27324. indices.push( a, b, d );
  27325. indices.push( b, c, d );
  27326. }
  27327. }
  27328. }
  27329. function generateUVs() {
  27330. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27331. for ( let j = 0; j <= radialSegments; j ++ ) {
  27332. uv.x = i / tubularSegments;
  27333. uv.y = j / radialSegments;
  27334. uvs.push( uv.x, uv.y );
  27335. }
  27336. }
  27337. }
  27338. }
  27339. copy( source ) {
  27340. super.copy( source );
  27341. this.parameters = Object.assign( {}, source.parameters );
  27342. return this;
  27343. }
  27344. toJSON() {
  27345. const data = super.toJSON();
  27346. data.path = this.parameters.path.toJSON();
  27347. return data;
  27348. }
  27349. /**
  27350. * Factory method for creating an instance of this class from the given
  27351. * JSON object.
  27352. *
  27353. * @param {Object} data - A JSON object representing the serialized geometry.
  27354. * @return {TubeGeometry} A new instance.
  27355. */
  27356. static fromJSON( data ) {
  27357. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27358. // User defined curves or instances of CurvePath will not be deserialized.
  27359. return new TubeGeometry(
  27360. new Curves[ data.path.type ]().fromJSON( data.path ),
  27361. data.tubularSegments,
  27362. data.radius,
  27363. data.radialSegments,
  27364. data.closed
  27365. );
  27366. }
  27367. }
  27368. /**
  27369. * Can be used as a helper object to visualize a geometry as a wireframe.
  27370. *
  27371. * ```js
  27372. * const geometry = new THREE.SphereGeometry();
  27373. *
  27374. * const wireframe = new THREE.WireframeGeometry( geometry );
  27375. *
  27376. * const line = new THREE.LineSegments( wireframe );
  27377. * line.material.depthWrite = false;
  27378. * line.material.opacity = 0.25;
  27379. * line.material.transparent = true;
  27380. *
  27381. * scene.add( line );
  27382. * ```
  27383. *
  27384. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27385. *
  27386. * @augments BufferGeometry
  27387. */
  27388. class WireframeGeometry extends BufferGeometry {
  27389. /**
  27390. * Constructs a new wireframe geometry.
  27391. *
  27392. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27393. */
  27394. constructor( geometry = null ) {
  27395. super();
  27396. this.type = 'WireframeGeometry';
  27397. /**
  27398. * Holds the constructor parameters that have been
  27399. * used to generate the geometry. Any modification
  27400. * after instantiation does not change the geometry.
  27401. *
  27402. * @type {Object}
  27403. */
  27404. this.parameters = {
  27405. geometry: geometry
  27406. };
  27407. if ( geometry !== null ) {
  27408. // buffer
  27409. const vertices = [];
  27410. const edges = new Set();
  27411. // helper variables
  27412. const start = new Vector3();
  27413. const end = new Vector3();
  27414. if ( geometry.index !== null ) {
  27415. // indexed BufferGeometry
  27416. const position = geometry.attributes.position;
  27417. const indices = geometry.index;
  27418. let groups = geometry.groups;
  27419. if ( groups.length === 0 ) {
  27420. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27421. }
  27422. // create a data structure that contains all edges without duplicates
  27423. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27424. const group = groups[ o ];
  27425. const groupStart = group.start;
  27426. const groupCount = group.count;
  27427. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27428. for ( let j = 0; j < 3; j ++ ) {
  27429. const index1 = indices.getX( i + j );
  27430. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27431. start.fromBufferAttribute( position, index1 );
  27432. end.fromBufferAttribute( position, index2 );
  27433. if ( isUniqueEdge( start, end, edges ) === true ) {
  27434. vertices.push( start.x, start.y, start.z );
  27435. vertices.push( end.x, end.y, end.z );
  27436. }
  27437. }
  27438. }
  27439. }
  27440. } else {
  27441. // non-indexed BufferGeometry
  27442. const position = geometry.attributes.position;
  27443. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27444. for ( let j = 0; j < 3; j ++ ) {
  27445. // three edges per triangle, an edge is represented as (index1, index2)
  27446. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27447. const index1 = 3 * i + j;
  27448. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27449. start.fromBufferAttribute( position, index1 );
  27450. end.fromBufferAttribute( position, index2 );
  27451. if ( isUniqueEdge( start, end, edges ) === true ) {
  27452. vertices.push( start.x, start.y, start.z );
  27453. vertices.push( end.x, end.y, end.z );
  27454. }
  27455. }
  27456. }
  27457. }
  27458. // build geometry
  27459. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27460. }
  27461. }
  27462. copy( source ) {
  27463. super.copy( source );
  27464. this.parameters = Object.assign( {}, source.parameters );
  27465. return this;
  27466. }
  27467. }
  27468. function isUniqueEdge( start, end, edges ) {
  27469. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27470. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27471. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27472. return false;
  27473. } else {
  27474. edges.add( hash1 );
  27475. edges.add( hash2 );
  27476. return true;
  27477. }
  27478. }
  27479. var Geometries = /*#__PURE__*/Object.freeze({
  27480. __proto__: null,
  27481. BoxGeometry: BoxGeometry,
  27482. CapsuleGeometry: CapsuleGeometry,
  27483. CircleGeometry: CircleGeometry,
  27484. ConeGeometry: ConeGeometry,
  27485. CylinderGeometry: CylinderGeometry,
  27486. DodecahedronGeometry: DodecahedronGeometry,
  27487. EdgesGeometry: EdgesGeometry,
  27488. ExtrudeGeometry: ExtrudeGeometry,
  27489. IcosahedronGeometry: IcosahedronGeometry,
  27490. LatheGeometry: LatheGeometry,
  27491. OctahedronGeometry: OctahedronGeometry,
  27492. PlaneGeometry: PlaneGeometry,
  27493. PolyhedronGeometry: PolyhedronGeometry,
  27494. RingGeometry: RingGeometry,
  27495. ShapeGeometry: ShapeGeometry,
  27496. SphereGeometry: SphereGeometry,
  27497. TetrahedronGeometry: TetrahedronGeometry,
  27498. TorusGeometry: TorusGeometry,
  27499. TorusKnotGeometry: TorusKnotGeometry,
  27500. TubeGeometry: TubeGeometry,
  27501. WireframeGeometry: WireframeGeometry
  27502. });
  27503. /**
  27504. * This material can receive shadows, but otherwise is completely transparent.
  27505. *
  27506. * ```js
  27507. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27508. * geometry.rotateX( - Math.PI / 2 );
  27509. *
  27510. * const material = new THREE.ShadowMaterial();
  27511. * material.opacity = 0.2;
  27512. *
  27513. * const plane = new THREE.Mesh( geometry, material );
  27514. * plane.position.y = -200;
  27515. * plane.receiveShadow = true;
  27516. * scene.add( plane );
  27517. * ```
  27518. *
  27519. * @augments Material
  27520. */
  27521. class ShadowMaterial extends Material {
  27522. /**
  27523. * Constructs a new shadow material.
  27524. *
  27525. * @param {Object} [parameters] - An object with one or more properties
  27526. * defining the material's appearance. Any property of the material
  27527. * (including any property from inherited materials) can be passed
  27528. * in here. Color values can be passed any type of value accepted
  27529. * by {@link Color#set}.
  27530. */
  27531. constructor( parameters ) {
  27532. super();
  27533. /**
  27534. * This flag can be used for type testing.
  27535. *
  27536. * @type {boolean}
  27537. * @readonly
  27538. * @default true
  27539. */
  27540. this.isShadowMaterial = true;
  27541. this.type = 'ShadowMaterial';
  27542. /**
  27543. * Color of the material.
  27544. *
  27545. * @type {Color}
  27546. * @default (0,0,0)
  27547. */
  27548. this.color = new Color( 0x000000 );
  27549. /**
  27550. * Overwritten since shadow materials are transparent
  27551. * by default.
  27552. *
  27553. * @type {boolean}
  27554. * @default true
  27555. */
  27556. this.transparent = true;
  27557. /**
  27558. * Whether the material is affected by fog or not.
  27559. *
  27560. * @type {boolean}
  27561. * @default true
  27562. */
  27563. this.fog = true;
  27564. this.setValues( parameters );
  27565. }
  27566. copy( source ) {
  27567. super.copy( source );
  27568. this.color.copy( source.color );
  27569. this.fog = source.fog;
  27570. return this;
  27571. }
  27572. }
  27573. /**
  27574. * This class works just like {@link ShaderMaterial}, except that definitions
  27575. * of built-in uniforms and attributes are not automatically prepended to the
  27576. * GLSL shader code.
  27577. *
  27578. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27579. *
  27580. * @augments ShaderMaterial
  27581. */
  27582. class RawShaderMaterial extends ShaderMaterial {
  27583. /**
  27584. * Constructs a new raw shader material.
  27585. *
  27586. * @param {Object} [parameters] - An object with one or more properties
  27587. * defining the material's appearance. Any property of the material
  27588. * (including any property from inherited materials) can be passed
  27589. * in here. Color values can be passed any type of value accepted
  27590. * by {@link Color#set}.
  27591. */
  27592. constructor( parameters ) {
  27593. super( parameters );
  27594. /**
  27595. * This flag can be used for type testing.
  27596. *
  27597. * @type {boolean}
  27598. * @readonly
  27599. * @default true
  27600. */
  27601. this.isRawShaderMaterial = true;
  27602. this.type = 'RawShaderMaterial';
  27603. }
  27604. }
  27605. /**
  27606. * A standard physically based material, using Metallic-Roughness workflow.
  27607. *
  27608. * Physically based rendering (PBR) has recently become the standard in many
  27609. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27610. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27611. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27612. *
  27613. * This approach differs from older approaches in that instead of using
  27614. * approximations for the way in which light interacts with a surface, a
  27615. * physically correct model is used. The idea is that, instead of tweaking
  27616. * materials to look good under specific lighting, a material can be created
  27617. * that will react 'correctly' under all lighting scenarios.
  27618. *
  27619. * In practice this gives a more accurate and realistic looking result than
  27620. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27621. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27622. * shading.
  27623. *
  27624. * Note that for best results you should always specify an environment map when using this material.
  27625. *
  27626. * For a non-technical introduction to the concept of PBR and how to set up a
  27627. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27628. *
  27629. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27630. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27631. *
  27632. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27633. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27634. * (pdf), by Brent Burley.
  27635. *
  27636. * @augments Material
  27637. */
  27638. class MeshStandardMaterial extends Material {
  27639. /**
  27640. * Constructs a new mesh standard material.
  27641. *
  27642. * @param {Object} [parameters] - An object with one or more properties
  27643. * defining the material's appearance. Any property of the material
  27644. * (including any property from inherited materials) can be passed
  27645. * in here. Color values can be passed any type of value accepted
  27646. * by {@link Color#set}.
  27647. */
  27648. constructor( parameters ) {
  27649. super();
  27650. /**
  27651. * This flag can be used for type testing.
  27652. *
  27653. * @type {boolean}
  27654. * @readonly
  27655. * @default true
  27656. */
  27657. this.isMeshStandardMaterial = true;
  27658. this.type = 'MeshStandardMaterial';
  27659. this.defines = { 'STANDARD': '' };
  27660. /**
  27661. * Color of the material.
  27662. *
  27663. * @type {Color}
  27664. * @default (1,1,1)
  27665. */
  27666. this.color = new Color( 0xffffff ); // diffuse
  27667. /**
  27668. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27669. * means fully diffuse. If `roughnessMap` is also provided,
  27670. * both values are multiplied.
  27671. *
  27672. * @type {number}
  27673. * @default 1
  27674. */
  27675. this.roughness = 1.0;
  27676. /**
  27677. * How much the material is like a metal. Non-metallic materials such as wood
  27678. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27679. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27680. * If `metalnessMap` is also provided, both values are multiplied.
  27681. *
  27682. * @type {number}
  27683. * @default 0
  27684. */
  27685. this.metalness = 0.0;
  27686. /**
  27687. * The color map. May optionally include an alpha channel, typically combined
  27688. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27689. * color is modulated by the diffuse `color`.
  27690. *
  27691. * @type {?Texture}
  27692. * @default null
  27693. */
  27694. this.map = null;
  27695. /**
  27696. * The light map. Requires a second set of UVs.
  27697. *
  27698. * @type {?Texture}
  27699. * @default null
  27700. */
  27701. this.lightMap = null;
  27702. /**
  27703. * Intensity of the baked light.
  27704. *
  27705. * @type {number}
  27706. * @default 1
  27707. */
  27708. this.lightMapIntensity = 1.0;
  27709. /**
  27710. * The red channel of this texture is used as the ambient occlusion map.
  27711. * Requires a second set of UVs.
  27712. *
  27713. * @type {?Texture}
  27714. * @default null
  27715. */
  27716. this.aoMap = null;
  27717. /**
  27718. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27719. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27720. * red channel is also `1`, ambient light is fully occluded on a surface.
  27721. *
  27722. * @type {number}
  27723. * @default 1
  27724. */
  27725. this.aoMapIntensity = 1.0;
  27726. /**
  27727. * Emissive (light) color of the material, essentially a solid color
  27728. * unaffected by other lighting.
  27729. *
  27730. * @type {Color}
  27731. * @default (0,0,0)
  27732. */
  27733. this.emissive = new Color( 0x000000 );
  27734. /**
  27735. * Intensity of the emissive light. Modulates the emissive color.
  27736. *
  27737. * @type {number}
  27738. * @default 1
  27739. */
  27740. this.emissiveIntensity = 1.0;
  27741. /**
  27742. * Set emissive (glow) map. The emissive map color is modulated by the
  27743. * emissive color and the emissive intensity. If you have an emissive map,
  27744. * be sure to set the emissive color to something other than black.
  27745. *
  27746. * @type {?Texture}
  27747. * @default null
  27748. */
  27749. this.emissiveMap = null;
  27750. /**
  27751. * The texture to create a bump map. The black and white values map to the
  27752. * perceived depth in relation to the lights. Bump doesn't actually affect
  27753. * the geometry of the object, only the lighting. If a normal map is defined
  27754. * this will be ignored.
  27755. *
  27756. * @type {?Texture}
  27757. * @default null
  27758. */
  27759. this.bumpMap = null;
  27760. /**
  27761. * How much the bump map affects the material. Typical range is `[0,1]`.
  27762. *
  27763. * @type {number}
  27764. * @default 1
  27765. */
  27766. this.bumpScale = 1;
  27767. /**
  27768. * The texture to create a normal map. The RGB values affect the surface
  27769. * normal for each pixel fragment and change the way the color is lit. Normal
  27770. * maps do not change the actual shape of the surface, only the lighting. In
  27771. * case the material has a normal map authored using the left handed
  27772. * convention, the `y` component of `normalScale` should be negated to compensate
  27773. * for the different handedness.
  27774. *
  27775. * @type {?Texture}
  27776. * @default null
  27777. */
  27778. this.normalMap = null;
  27779. /**
  27780. * The type of normal map.
  27781. *
  27782. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27783. * @default TangentSpaceNormalMap
  27784. */
  27785. this.normalMapType = TangentSpaceNormalMap;
  27786. /**
  27787. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27788. *
  27789. * @type {Vector2}
  27790. * @default (1,1)
  27791. */
  27792. this.normalScale = new Vector2( 1, 1 );
  27793. /**
  27794. * The displacement map affects the position of the mesh's vertices. Unlike
  27795. * other maps which only affect the light and shade of the material the
  27796. * displaced vertices can cast shadows, block other objects, and otherwise
  27797. * act as real geometry. The displacement texture is an image where the value
  27798. * of each pixel (white being the highest) is mapped against, and
  27799. * repositions, the vertices of the mesh.
  27800. *
  27801. * @type {?Texture}
  27802. * @default null
  27803. */
  27804. this.displacementMap = null;
  27805. /**
  27806. * How much the displacement map affects the mesh (where black is no
  27807. * displacement, and white is maximum displacement). Without a displacement
  27808. * map set, this value is not applied.
  27809. *
  27810. * @type {number}
  27811. * @default 0
  27812. */
  27813. this.displacementScale = 1;
  27814. /**
  27815. * The offset of the displacement map's values on the mesh's vertices.
  27816. * The bias is added to the scaled sample of the displacement map.
  27817. * Without a displacement map set, this value is not applied.
  27818. *
  27819. * @type {number}
  27820. * @default 0
  27821. */
  27822. this.displacementBias = 0;
  27823. /**
  27824. * The green channel of this texture is used to alter the roughness of the
  27825. * material.
  27826. *
  27827. * @type {?Texture}
  27828. * @default null
  27829. */
  27830. this.roughnessMap = null;
  27831. /**
  27832. * The blue channel of this texture is used to alter the metalness of the
  27833. * material.
  27834. *
  27835. * @type {?Texture}
  27836. * @default null
  27837. */
  27838. this.metalnessMap = null;
  27839. /**
  27840. * The alpha map is a grayscale texture that controls the opacity across the
  27841. * surface (black: fully transparent; white: fully opaque).
  27842. *
  27843. * Only the color of the texture is used, ignoring the alpha channel if one
  27844. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27845. * when sampling this texture due to the extra bit of precision provided for
  27846. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27847. * luminance/alpha textures will also still work as expected.
  27848. *
  27849. * @type {?Texture}
  27850. * @default null
  27851. */
  27852. this.alphaMap = null;
  27853. /**
  27854. * The environment map. To ensure a physically correct rendering, environment maps
  27855. * are internally pre-processed with {@link PMREMGenerator}.
  27856. *
  27857. * @type {?Texture}
  27858. * @default null
  27859. */
  27860. this.envMap = null;
  27861. /**
  27862. * The rotation of the environment map in radians.
  27863. *
  27864. * @type {Euler}
  27865. * @default (0,0,0)
  27866. */
  27867. this.envMapRotation = new Euler();
  27868. /**
  27869. * Scales the effect of the environment map by multiplying its color.
  27870. *
  27871. * @type {number}
  27872. * @default 1
  27873. */
  27874. this.envMapIntensity = 1.0;
  27875. /**
  27876. * Renders the geometry as a wireframe.
  27877. *
  27878. * @type {boolean}
  27879. * @default false
  27880. */
  27881. this.wireframe = false;
  27882. /**
  27883. * Controls the thickness of the wireframe.
  27884. *
  27885. * Can only be used with {@link SVGRenderer}.
  27886. *
  27887. * @type {number}
  27888. * @default 1
  27889. */
  27890. this.wireframeLinewidth = 1;
  27891. /**
  27892. * Defines appearance of wireframe ends.
  27893. *
  27894. * Can only be used with {@link SVGRenderer}.
  27895. *
  27896. * @type {('round'|'bevel'|'miter')}
  27897. * @default 'round'
  27898. */
  27899. this.wireframeLinecap = 'round';
  27900. /**
  27901. * Defines appearance of wireframe joints.
  27902. *
  27903. * Can only be used with {@link SVGRenderer}.
  27904. *
  27905. * @type {('round'|'bevel'|'miter')}
  27906. * @default 'round'
  27907. */
  27908. this.wireframeLinejoin = 'round';
  27909. /**
  27910. * Whether the material is rendered with flat shading or not.
  27911. *
  27912. * @type {boolean}
  27913. * @default false
  27914. */
  27915. this.flatShading = false;
  27916. /**
  27917. * Whether the material is affected by fog or not.
  27918. *
  27919. * @type {boolean}
  27920. * @default true
  27921. */
  27922. this.fog = true;
  27923. this.setValues( parameters );
  27924. }
  27925. copy( source ) {
  27926. super.copy( source );
  27927. this.defines = { 'STANDARD': '' };
  27928. this.color.copy( source.color );
  27929. this.roughness = source.roughness;
  27930. this.metalness = source.metalness;
  27931. this.map = source.map;
  27932. this.lightMap = source.lightMap;
  27933. this.lightMapIntensity = source.lightMapIntensity;
  27934. this.aoMap = source.aoMap;
  27935. this.aoMapIntensity = source.aoMapIntensity;
  27936. this.emissive.copy( source.emissive );
  27937. this.emissiveMap = source.emissiveMap;
  27938. this.emissiveIntensity = source.emissiveIntensity;
  27939. this.bumpMap = source.bumpMap;
  27940. this.bumpScale = source.bumpScale;
  27941. this.normalMap = source.normalMap;
  27942. this.normalMapType = source.normalMapType;
  27943. this.normalScale.copy( source.normalScale );
  27944. this.displacementMap = source.displacementMap;
  27945. this.displacementScale = source.displacementScale;
  27946. this.displacementBias = source.displacementBias;
  27947. this.roughnessMap = source.roughnessMap;
  27948. this.metalnessMap = source.metalnessMap;
  27949. this.alphaMap = source.alphaMap;
  27950. this.envMap = source.envMap;
  27951. this.envMapRotation.copy( source.envMapRotation );
  27952. this.envMapIntensity = source.envMapIntensity;
  27953. this.wireframe = source.wireframe;
  27954. this.wireframeLinewidth = source.wireframeLinewidth;
  27955. this.wireframeLinecap = source.wireframeLinecap;
  27956. this.wireframeLinejoin = source.wireframeLinejoin;
  27957. this.flatShading = source.flatShading;
  27958. this.fog = source.fog;
  27959. return this;
  27960. }
  27961. }
  27962. /**
  27963. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27964. * physically-based rendering properties:
  27965. *
  27966. * - Anisotropy: Ability to represent the anisotropic property of materials
  27967. * as observable with brushed metals.
  27968. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27969. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27970. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27971. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27972. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27973. * wings of many insects.
  27974. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27975. * transparent materials are less reflective. Physically-based transmission provides a more
  27976. * realistic option for thin, transparent surfaces like glass.
  27977. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27978. * - Sheen: Can be used for representing cloth and fabric materials.
  27979. *
  27980. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27981. * higher performance cost, per pixel, than other three.js materials. Most
  27982. * effects are disabled by default, and add cost as they are enabled. For
  27983. * best results, always specify an environment map when using this material.
  27984. *
  27985. * @augments MeshStandardMaterial
  27986. */
  27987. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27988. /**
  27989. * Constructs a new mesh physical material.
  27990. *
  27991. * @param {Object} [parameters] - An object with one or more properties
  27992. * defining the material's appearance. Any property of the material
  27993. * (including any property from inherited materials) can be passed
  27994. * in here. Color values can be passed any type of value accepted
  27995. * by {@link Color#set}.
  27996. */
  27997. constructor( parameters ) {
  27998. super();
  27999. /**
  28000. * This flag can be used for type testing.
  28001. *
  28002. * @type {boolean}
  28003. * @readonly
  28004. * @default true
  28005. */
  28006. this.isMeshPhysicalMaterial = true;
  28007. this.defines = {
  28008. 'STANDARD': '',
  28009. 'PHYSICAL': ''
  28010. };
  28011. this.type = 'MeshPhysicalMaterial';
  28012. /**
  28013. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28014. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28015. * property provides additional rotation to the vectors in the texture.
  28016. *
  28017. * @type {number}
  28018. * @default 1
  28019. */
  28020. this.anisotropyRotation = 0;
  28021. /**
  28022. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28023. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28024. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28025. *
  28026. * @type {?Texture}
  28027. * @default null
  28028. */
  28029. this.anisotropyMap = null;
  28030. /**
  28031. * The red channel of this texture is multiplied against `clearcoat`,
  28032. * for per-pixel control over a coating's intensity.
  28033. *
  28034. * @type {?Texture}
  28035. * @default null
  28036. */
  28037. this.clearcoatMap = null;
  28038. /**
  28039. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28040. *
  28041. * @type {number}
  28042. * @default 0
  28043. */
  28044. this.clearcoatRoughness = 0.0;
  28045. /**
  28046. * The green channel of this texture is multiplied against
  28047. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28048. *
  28049. * @type {?Texture}
  28050. * @default null
  28051. */
  28052. this.clearcoatRoughnessMap = null;
  28053. /**
  28054. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28055. * `(0,0)` to `(1,1)`.
  28056. *
  28057. * @type {Vector2}
  28058. * @default (1,1)
  28059. */
  28060. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28061. /**
  28062. * Can be used to enable independent normals for the clear coat layer.
  28063. *
  28064. * @type {?Texture}
  28065. * @default null
  28066. */
  28067. this.clearcoatNormalMap = null;
  28068. /**
  28069. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28070. *
  28071. * @type {number}
  28072. * @default 1.5
  28073. */
  28074. this.ior = 1.5;
  28075. /**
  28076. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28077. * corresponds to an index-of-refraction of `1.5`.
  28078. *
  28079. * This models the reflectivity of non-metallic materials. It has no effect
  28080. * when `metalness` is `1.0`
  28081. *
  28082. * @name MeshPhysicalMaterial#reflectivity
  28083. * @type {number}
  28084. * @default 0.5
  28085. */
  28086. Object.defineProperty( this, 'reflectivity', {
  28087. get: function () {
  28088. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28089. },
  28090. set: function ( reflectivity ) {
  28091. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28092. }
  28093. } );
  28094. /**
  28095. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28096. * control over iridescence.
  28097. *
  28098. * @type {?Texture}
  28099. * @default null
  28100. */
  28101. this.iridescenceMap = null;
  28102. /**
  28103. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28104. * Between `1.0` to `2.333`.
  28105. *
  28106. * @type {number}
  28107. * @default 1.3
  28108. */
  28109. this.iridescenceIOR = 1.3;
  28110. /**
  28111. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28112. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28113. *
  28114. * @type {Array<number,number>}
  28115. * @default [100,400]
  28116. */
  28117. this.iridescenceThicknessRange = [ 100, 400 ];
  28118. /**
  28119. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28120. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28121. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28122. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28123. * - Values in-between will linearly interpolate between the elements of the array.
  28124. *
  28125. * @type {?Texture}
  28126. * @default null
  28127. */
  28128. this.iridescenceThicknessMap = null;
  28129. /**
  28130. * The sheen tint.
  28131. *
  28132. * @type {Color}
  28133. * @default (0,0,0)
  28134. */
  28135. this.sheenColor = new Color( 0x000000 );
  28136. /**
  28137. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28138. * over sheen tint.
  28139. *
  28140. * @type {?Texture}
  28141. * @default null
  28142. */
  28143. this.sheenColorMap = null;
  28144. /**
  28145. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28146. *
  28147. * @type {number}
  28148. * @default 1
  28149. */
  28150. this.sheenRoughness = 1.0;
  28151. /**
  28152. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28153. * over sheen roughness.
  28154. *
  28155. * @type {?Texture}
  28156. * @default null
  28157. */
  28158. this.sheenRoughnessMap = null;
  28159. /**
  28160. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28161. * optical transparency.
  28162. *
  28163. * @type {?Texture}
  28164. * @default null
  28165. */
  28166. this.transmissionMap = null;
  28167. /**
  28168. * The thickness of the volume beneath the surface. The value is given in the
  28169. * coordinate space of the mesh. If the value is `0` the material is
  28170. * thin-walled. Otherwise the material is a volume boundary.
  28171. *
  28172. * @type {number}
  28173. * @default 0
  28174. */
  28175. this.thickness = 0;
  28176. /**
  28177. * A texture that defines the thickness, stored in the green channel. This will
  28178. * be multiplied by `thickness`.
  28179. *
  28180. * @type {?Texture}
  28181. * @default null
  28182. */
  28183. this.thicknessMap = null;
  28184. /**
  28185. * Density of the medium given as the average distance that light travels in
  28186. * the medium before interacting with a particle. The value is given in world
  28187. * space units, and must be greater than zero.
  28188. *
  28189. * @type {number}
  28190. * @default Infinity
  28191. */
  28192. this.attenuationDistance = Infinity;
  28193. /**
  28194. * The color that white light turns into due to absorption when reaching the
  28195. * attenuation distance.
  28196. *
  28197. * @type {Color}
  28198. * @default (1,1,1)
  28199. */
  28200. this.attenuationColor = new Color( 1, 1, 1 );
  28201. /**
  28202. * A float that scales the amount of specular reflection for non-metals only.
  28203. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28204. *
  28205. * @type {number}
  28206. * @default 1
  28207. */
  28208. this.specularIntensity = 1.0;
  28209. /**
  28210. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28211. * for per-pixel control over specular intensity.
  28212. *
  28213. * @type {?Texture}
  28214. * @default null
  28215. */
  28216. this.specularIntensityMap = null;
  28217. /**
  28218. * Tints the specular reflection at normal incidence for non-metals only.
  28219. *
  28220. * @type {Color}
  28221. * @default (1,1,1)
  28222. */
  28223. this.specularColor = new Color( 1, 1, 1 );
  28224. /**
  28225. * The RGB channels of this texture are multiplied against `specularColor`,
  28226. * for per-pixel control over specular color.
  28227. *
  28228. * @type {?Texture}
  28229. * @default null
  28230. */
  28231. this.specularColorMap = null;
  28232. this._anisotropy = 0;
  28233. this._clearcoat = 0;
  28234. this._dispersion = 0;
  28235. this._iridescence = 0;
  28236. this._sheen = 0.0;
  28237. this._transmission = 0;
  28238. this.setValues( parameters );
  28239. }
  28240. /**
  28241. * The anisotropy strength.
  28242. *
  28243. * @type {number}
  28244. * @default 0
  28245. */
  28246. get anisotropy() {
  28247. return this._anisotropy;
  28248. }
  28249. set anisotropy( value ) {
  28250. if ( this._anisotropy > 0 !== value > 0 ) {
  28251. this.version ++;
  28252. }
  28253. this._anisotropy = value;
  28254. }
  28255. /**
  28256. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28257. * clear coat related properties to enable multilayer materials that have a
  28258. * thin translucent layer over the base layer.
  28259. *
  28260. * @type {number}
  28261. * @default 0
  28262. */
  28263. get clearcoat() {
  28264. return this._clearcoat;
  28265. }
  28266. set clearcoat( value ) {
  28267. if ( this._clearcoat > 0 !== value > 0 ) {
  28268. this.version ++;
  28269. }
  28270. this._clearcoat = value;
  28271. }
  28272. /**
  28273. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28274. * the surface and the viewer, from `0.0` to `1.0`.
  28275. *
  28276. * @type {number}
  28277. * @default 0
  28278. */
  28279. get iridescence() {
  28280. return this._iridescence;
  28281. }
  28282. set iridescence( value ) {
  28283. if ( this._iridescence > 0 !== value > 0 ) {
  28284. this.version ++;
  28285. }
  28286. this._iridescence = value;
  28287. }
  28288. /**
  28289. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28290. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28291. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28292. *
  28293. * @type {number}
  28294. * @default 0
  28295. */
  28296. get dispersion() {
  28297. return this._dispersion;
  28298. }
  28299. set dispersion( value ) {
  28300. if ( this._dispersion > 0 !== value > 0 ) {
  28301. this.version ++;
  28302. }
  28303. this._dispersion = value;
  28304. }
  28305. /**
  28306. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28307. *
  28308. * @type {number}
  28309. * @default 0
  28310. */
  28311. get sheen() {
  28312. return this._sheen;
  28313. }
  28314. set sheen( value ) {
  28315. if ( this._sheen > 0 !== value > 0 ) {
  28316. this.version ++;
  28317. }
  28318. this._sheen = value;
  28319. }
  28320. /**
  28321. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28322. *
  28323. * Thin, transparent or semitransparent, plastic or glass materials remain
  28324. * largely reflective even if they are fully transmissive. The transmission
  28325. * property can be used to model these materials.
  28326. *
  28327. * When transmission is non-zero, `opacity` should be set to `1`.
  28328. *
  28329. * @type {number}
  28330. * @default 0
  28331. */
  28332. get transmission() {
  28333. return this._transmission;
  28334. }
  28335. set transmission( value ) {
  28336. if ( this._transmission > 0 !== value > 0 ) {
  28337. this.version ++;
  28338. }
  28339. this._transmission = value;
  28340. }
  28341. copy( source ) {
  28342. super.copy( source );
  28343. this.defines = {
  28344. 'STANDARD': '',
  28345. 'PHYSICAL': ''
  28346. };
  28347. this.anisotropy = source.anisotropy;
  28348. this.anisotropyRotation = source.anisotropyRotation;
  28349. this.anisotropyMap = source.anisotropyMap;
  28350. this.clearcoat = source.clearcoat;
  28351. this.clearcoatMap = source.clearcoatMap;
  28352. this.clearcoatRoughness = source.clearcoatRoughness;
  28353. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28354. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28355. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28356. this.dispersion = source.dispersion;
  28357. this.ior = source.ior;
  28358. this.iridescence = source.iridescence;
  28359. this.iridescenceMap = source.iridescenceMap;
  28360. this.iridescenceIOR = source.iridescenceIOR;
  28361. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28362. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28363. this.sheen = source.sheen;
  28364. this.sheenColor.copy( source.sheenColor );
  28365. this.sheenColorMap = source.sheenColorMap;
  28366. this.sheenRoughness = source.sheenRoughness;
  28367. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28368. this.transmission = source.transmission;
  28369. this.transmissionMap = source.transmissionMap;
  28370. this.thickness = source.thickness;
  28371. this.thicknessMap = source.thicknessMap;
  28372. this.attenuationDistance = source.attenuationDistance;
  28373. this.attenuationColor.copy( source.attenuationColor );
  28374. this.specularIntensity = source.specularIntensity;
  28375. this.specularIntensityMap = source.specularIntensityMap;
  28376. this.specularColor.copy( source.specularColor );
  28377. this.specularColorMap = source.specularColorMap;
  28378. return this;
  28379. }
  28380. }
  28381. /**
  28382. * A material for shiny surfaces with specular highlights.
  28383. *
  28384. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28385. * model for calculating reflectance. Unlike the Lambertian model used in the
  28386. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28387. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28388. *
  28389. * Performance will generally be greater when using this material over the
  28390. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28391. * some graphical accuracy.
  28392. *
  28393. * @augments Material
  28394. */
  28395. class MeshPhongMaterial extends Material {
  28396. /**
  28397. * Constructs a new mesh phong material.
  28398. *
  28399. * @param {Object} [parameters] - An object with one or more properties
  28400. * defining the material's appearance. Any property of the material
  28401. * (including any property from inherited materials) can be passed
  28402. * in here. Color values can be passed any type of value accepted
  28403. * by {@link Color#set}.
  28404. */
  28405. constructor( parameters ) {
  28406. super();
  28407. /**
  28408. * This flag can be used for type testing.
  28409. *
  28410. * @type {boolean}
  28411. * @readonly
  28412. * @default true
  28413. */
  28414. this.isMeshPhongMaterial = true;
  28415. this.type = 'MeshPhongMaterial';
  28416. /**
  28417. * Color of the material.
  28418. *
  28419. * @type {Color}
  28420. * @default (1,1,1)
  28421. */
  28422. this.color = new Color( 0xffffff ); // diffuse
  28423. /**
  28424. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28425. *
  28426. * This defines how shiny the material is and the color of its shine.
  28427. *
  28428. * @type {Color}
  28429. */
  28430. this.specular = new Color( 0x111111 );
  28431. /**
  28432. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28433. *
  28434. * @type {number}
  28435. * @default 30
  28436. */
  28437. this.shininess = 30;
  28438. /**
  28439. * The color map. May optionally include an alpha channel, typically combined
  28440. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28441. * color is modulated by the diffuse `color`.
  28442. *
  28443. * @type {?Texture}
  28444. * @default null
  28445. */
  28446. this.map = null;
  28447. /**
  28448. * The light map. Requires a second set of UVs.
  28449. *
  28450. * @type {?Texture}
  28451. * @default null
  28452. */
  28453. this.lightMap = null;
  28454. /**
  28455. * Intensity of the baked light.
  28456. *
  28457. * @type {number}
  28458. * @default 1
  28459. */
  28460. this.lightMapIntensity = 1.0;
  28461. /**
  28462. * The red channel of this texture is used as the ambient occlusion map.
  28463. * Requires a second set of UVs.
  28464. *
  28465. * @type {?Texture}
  28466. * @default null
  28467. */
  28468. this.aoMap = null;
  28469. /**
  28470. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28471. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28472. * red channel is also `1`, ambient light is fully occluded on a surface.
  28473. *
  28474. * @type {number}
  28475. * @default 1
  28476. */
  28477. this.aoMapIntensity = 1.0;
  28478. /**
  28479. * Emissive (light) color of the material, essentially a solid color
  28480. * unaffected by other lighting.
  28481. *
  28482. * @type {Color}
  28483. * @default (0,0,0)
  28484. */
  28485. this.emissive = new Color( 0x000000 );
  28486. /**
  28487. * Intensity of the emissive light. Modulates the emissive color.
  28488. *
  28489. * @type {number}
  28490. * @default 1
  28491. */
  28492. this.emissiveIntensity = 1.0;
  28493. /**
  28494. * Set emissive (glow) map. The emissive map color is modulated by the
  28495. * emissive color and the emissive intensity. If you have an emissive map,
  28496. * be sure to set the emissive color to something other than black.
  28497. *
  28498. * @type {?Texture}
  28499. * @default null
  28500. */
  28501. this.emissiveMap = null;
  28502. /**
  28503. * The texture to create a bump map. The black and white values map to the
  28504. * perceived depth in relation to the lights. Bump doesn't actually affect
  28505. * the geometry of the object, only the lighting. If a normal map is defined
  28506. * this will be ignored.
  28507. *
  28508. * @type {?Texture}
  28509. * @default null
  28510. */
  28511. this.bumpMap = null;
  28512. /**
  28513. * How much the bump map affects the material. Typical range is `[0,1]`.
  28514. *
  28515. * @type {number}
  28516. * @default 1
  28517. */
  28518. this.bumpScale = 1;
  28519. /**
  28520. * The texture to create a normal map. The RGB values affect the surface
  28521. * normal for each pixel fragment and change the way the color is lit. Normal
  28522. * maps do not change the actual shape of the surface, only the lighting. In
  28523. * case the material has a normal map authored using the left handed
  28524. * convention, the `y` component of `normalScale` should be negated to compensate
  28525. * for the different handedness.
  28526. *
  28527. * @type {?Texture}
  28528. * @default null
  28529. */
  28530. this.normalMap = null;
  28531. /**
  28532. * The type of normal map.
  28533. *
  28534. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28535. * @default TangentSpaceNormalMap
  28536. */
  28537. this.normalMapType = TangentSpaceNormalMap;
  28538. /**
  28539. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28540. *
  28541. * @type {Vector2}
  28542. * @default (1,1)
  28543. */
  28544. this.normalScale = new Vector2( 1, 1 );
  28545. /**
  28546. * The displacement map affects the position of the mesh's vertices. Unlike
  28547. * other maps which only affect the light and shade of the material the
  28548. * displaced vertices can cast shadows, block other objects, and otherwise
  28549. * act as real geometry. The displacement texture is an image where the value
  28550. * of each pixel (white being the highest) is mapped against, and
  28551. * repositions, the vertices of the mesh.
  28552. *
  28553. * @type {?Texture}
  28554. * @default null
  28555. */
  28556. this.displacementMap = null;
  28557. /**
  28558. * How much the displacement map affects the mesh (where black is no
  28559. * displacement, and white is maximum displacement). Without a displacement
  28560. * map set, this value is not applied.
  28561. *
  28562. * @type {number}
  28563. * @default 0
  28564. */
  28565. this.displacementScale = 1;
  28566. /**
  28567. * The offset of the displacement map's values on the mesh's vertices.
  28568. * The bias is added to the scaled sample of the displacement map.
  28569. * Without a displacement map set, this value is not applied.
  28570. *
  28571. * @type {number}
  28572. * @default 0
  28573. */
  28574. this.displacementBias = 0;
  28575. /**
  28576. * The specular map value affects both how much the specular surface
  28577. * highlight contributes and how much of the environment map affects the
  28578. * surface.
  28579. *
  28580. * @type {?Texture}
  28581. * @default null
  28582. */
  28583. this.specularMap = null;
  28584. /**
  28585. * The alpha map is a grayscale texture that controls the opacity across the
  28586. * surface (black: fully transparent; white: fully opaque).
  28587. *
  28588. * Only the color of the texture is used, ignoring the alpha channel if one
  28589. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28590. * when sampling this texture due to the extra bit of precision provided for
  28591. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28592. * luminance/alpha textures will also still work as expected.
  28593. *
  28594. * @type {?Texture}
  28595. * @default null
  28596. */
  28597. this.alphaMap = null;
  28598. /**
  28599. * The environment map.
  28600. *
  28601. * @type {?Texture}
  28602. * @default null
  28603. */
  28604. this.envMap = null;
  28605. /**
  28606. * The rotation of the environment map in radians.
  28607. *
  28608. * @type {Euler}
  28609. * @default (0,0,0)
  28610. */
  28611. this.envMapRotation = new Euler();
  28612. /**
  28613. * How to combine the result of the surface's color with the environment map, if any.
  28614. *
  28615. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28616. * blend between the two colors.
  28617. *
  28618. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28619. * @default MultiplyOperation
  28620. */
  28621. this.combine = MultiplyOperation;
  28622. /**
  28623. * How much the environment map affects the surface.
  28624. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28625. *
  28626. * @type {number}
  28627. * @default 1
  28628. */
  28629. this.reflectivity = 1;
  28630. /**
  28631. * The index of refraction (IOR) of air (approximately 1) divided by the
  28632. * index of refraction of the material. It is used with environment mapping
  28633. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28634. * The refraction ratio should not exceed `1`.
  28635. *
  28636. * @type {number}
  28637. * @default 0.98
  28638. */
  28639. this.refractionRatio = 0.98;
  28640. /**
  28641. * Renders the geometry as a wireframe.
  28642. *
  28643. * @type {boolean}
  28644. * @default false
  28645. */
  28646. this.wireframe = false;
  28647. /**
  28648. * Controls the thickness of the wireframe.
  28649. *
  28650. * Can only be used with {@link SVGRenderer}.
  28651. *
  28652. * @type {number}
  28653. * @default 1
  28654. */
  28655. this.wireframeLinewidth = 1;
  28656. /**
  28657. * Defines appearance of wireframe ends.
  28658. *
  28659. * Can only be used with {@link SVGRenderer}.
  28660. *
  28661. * @type {('round'|'bevel'|'miter')}
  28662. * @default 'round'
  28663. */
  28664. this.wireframeLinecap = 'round';
  28665. /**
  28666. * Defines appearance of wireframe joints.
  28667. *
  28668. * Can only be used with {@link SVGRenderer}.
  28669. *
  28670. * @type {('round'|'bevel'|'miter')}
  28671. * @default 'round'
  28672. */
  28673. this.wireframeLinejoin = 'round';
  28674. /**
  28675. * Whether the material is rendered with flat shading or not.
  28676. *
  28677. * @type {boolean}
  28678. * @default false
  28679. */
  28680. this.flatShading = false;
  28681. /**
  28682. * Whether the material is affected by fog or not.
  28683. *
  28684. * @type {boolean}
  28685. * @default true
  28686. */
  28687. this.fog = true;
  28688. this.setValues( parameters );
  28689. }
  28690. copy( source ) {
  28691. super.copy( source );
  28692. this.color.copy( source.color );
  28693. this.specular.copy( source.specular );
  28694. this.shininess = source.shininess;
  28695. this.map = source.map;
  28696. this.lightMap = source.lightMap;
  28697. this.lightMapIntensity = source.lightMapIntensity;
  28698. this.aoMap = source.aoMap;
  28699. this.aoMapIntensity = source.aoMapIntensity;
  28700. this.emissive.copy( source.emissive );
  28701. this.emissiveMap = source.emissiveMap;
  28702. this.emissiveIntensity = source.emissiveIntensity;
  28703. this.bumpMap = source.bumpMap;
  28704. this.bumpScale = source.bumpScale;
  28705. this.normalMap = source.normalMap;
  28706. this.normalMapType = source.normalMapType;
  28707. this.normalScale.copy( source.normalScale );
  28708. this.displacementMap = source.displacementMap;
  28709. this.displacementScale = source.displacementScale;
  28710. this.displacementBias = source.displacementBias;
  28711. this.specularMap = source.specularMap;
  28712. this.alphaMap = source.alphaMap;
  28713. this.envMap = source.envMap;
  28714. this.envMapRotation.copy( source.envMapRotation );
  28715. this.combine = source.combine;
  28716. this.reflectivity = source.reflectivity;
  28717. this.refractionRatio = source.refractionRatio;
  28718. this.wireframe = source.wireframe;
  28719. this.wireframeLinewidth = source.wireframeLinewidth;
  28720. this.wireframeLinecap = source.wireframeLinecap;
  28721. this.wireframeLinejoin = source.wireframeLinejoin;
  28722. this.flatShading = source.flatShading;
  28723. this.fog = source.fog;
  28724. return this;
  28725. }
  28726. }
  28727. /**
  28728. * A material implementing toon shading.
  28729. *
  28730. * @augments Material
  28731. */
  28732. class MeshToonMaterial extends Material {
  28733. /**
  28734. * Constructs a new mesh toon material.
  28735. *
  28736. * @param {Object} [parameters] - An object with one or more properties
  28737. * defining the material's appearance. Any property of the material
  28738. * (including any property from inherited materials) can be passed
  28739. * in here. Color values can be passed any type of value accepted
  28740. * by {@link Color#set}.
  28741. */
  28742. constructor( parameters ) {
  28743. super();
  28744. /**
  28745. * This flag can be used for type testing.
  28746. *
  28747. * @type {boolean}
  28748. * @readonly
  28749. * @default true
  28750. */
  28751. this.isMeshToonMaterial = true;
  28752. this.defines = { 'TOON': '' };
  28753. this.type = 'MeshToonMaterial';
  28754. /**
  28755. * Color of the material.
  28756. *
  28757. * @type {Color}
  28758. * @default (1,1,1)
  28759. */
  28760. this.color = new Color( 0xffffff );
  28761. /**
  28762. * The color map. May optionally include an alpha channel, typically combined
  28763. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28764. * color is modulated by the diffuse `color`.
  28765. *
  28766. * @type {?Texture}
  28767. * @default null
  28768. */
  28769. this.map = null;
  28770. /**
  28771. * Gradient map for toon shading. It's required to set
  28772. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28773. * when using this type of texture.
  28774. *
  28775. * @type {?Texture}
  28776. * @default null
  28777. */
  28778. this.gradientMap = null;
  28779. /**
  28780. * The light map. Requires a second set of UVs.
  28781. *
  28782. * @type {?Texture}
  28783. * @default null
  28784. */
  28785. this.lightMap = null;
  28786. /**
  28787. * Intensity of the baked light.
  28788. *
  28789. * @type {number}
  28790. * @default 1
  28791. */
  28792. this.lightMapIntensity = 1.0;
  28793. /**
  28794. * The red channel of this texture is used as the ambient occlusion map.
  28795. * Requires a second set of UVs.
  28796. *
  28797. * @type {?Texture}
  28798. * @default null
  28799. */
  28800. this.aoMap = null;
  28801. /**
  28802. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28803. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28804. * red channel is also `1`, ambient light is fully occluded on a surface.
  28805. *
  28806. * @type {number}
  28807. * @default 1
  28808. */
  28809. this.aoMapIntensity = 1.0;
  28810. /**
  28811. * Emissive (light) color of the material, essentially a solid color
  28812. * unaffected by other lighting.
  28813. *
  28814. * @type {Color}
  28815. * @default (0,0,0)
  28816. */
  28817. this.emissive = new Color( 0x000000 );
  28818. /**
  28819. * Intensity of the emissive light. Modulates the emissive color.
  28820. *
  28821. * @type {number}
  28822. * @default 1
  28823. */
  28824. this.emissiveIntensity = 1.0;
  28825. /**
  28826. * Set emissive (glow) map. The emissive map color is modulated by the
  28827. * emissive color and the emissive intensity. If you have an emissive map,
  28828. * be sure to set the emissive color to something other than black.
  28829. *
  28830. * @type {?Texture}
  28831. * @default null
  28832. */
  28833. this.emissiveMap = null;
  28834. /**
  28835. * The texture to create a bump map. The black and white values map to the
  28836. * perceived depth in relation to the lights. Bump doesn't actually affect
  28837. * the geometry of the object, only the lighting. If a normal map is defined
  28838. * this will be ignored.
  28839. *
  28840. * @type {?Texture}
  28841. * @default null
  28842. */
  28843. this.bumpMap = null;
  28844. /**
  28845. * How much the bump map affects the material. Typical range is `[0,1]`.
  28846. *
  28847. * @type {number}
  28848. * @default 1
  28849. */
  28850. this.bumpScale = 1;
  28851. /**
  28852. * The texture to create a normal map. The RGB values affect the surface
  28853. * normal for each pixel fragment and change the way the color is lit. Normal
  28854. * maps do not change the actual shape of the surface, only the lighting. In
  28855. * case the material has a normal map authored using the left handed
  28856. * convention, the `y` component of `normalScale` should be negated to compensate
  28857. * for the different handedness.
  28858. *
  28859. * @type {?Texture}
  28860. * @default null
  28861. */
  28862. this.normalMap = null;
  28863. /**
  28864. * The type of normal map.
  28865. *
  28866. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28867. * @default TangentSpaceNormalMap
  28868. */
  28869. this.normalMapType = TangentSpaceNormalMap;
  28870. /**
  28871. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28872. *
  28873. * @type {Vector2}
  28874. * @default (1,1)
  28875. */
  28876. this.normalScale = new Vector2( 1, 1 );
  28877. /**
  28878. * The displacement map affects the position of the mesh's vertices. Unlike
  28879. * other maps which only affect the light and shade of the material the
  28880. * displaced vertices can cast shadows, block other objects, and otherwise
  28881. * act as real geometry. The displacement texture is an image where the value
  28882. * of each pixel (white being the highest) is mapped against, and
  28883. * repositions, the vertices of the mesh.
  28884. *
  28885. * @type {?Texture}
  28886. * @default null
  28887. */
  28888. this.displacementMap = null;
  28889. /**
  28890. * How much the displacement map affects the mesh (where black is no
  28891. * displacement, and white is maximum displacement). Without a displacement
  28892. * map set, this value is not applied.
  28893. *
  28894. * @type {number}
  28895. * @default 0
  28896. */
  28897. this.displacementScale = 1;
  28898. /**
  28899. * The offset of the displacement map's values on the mesh's vertices.
  28900. * The bias is added to the scaled sample of the displacement map.
  28901. * Without a displacement map set, this value is not applied.
  28902. *
  28903. * @type {number}
  28904. * @default 0
  28905. */
  28906. this.displacementBias = 0;
  28907. /**
  28908. * The alpha map is a grayscale texture that controls the opacity across the
  28909. * surface (black: fully transparent; white: fully opaque).
  28910. *
  28911. * Only the color of the texture is used, ignoring the alpha channel if one
  28912. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28913. * when sampling this texture due to the extra bit of precision provided for
  28914. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28915. * luminance/alpha textures will also still work as expected.
  28916. *
  28917. * @type {?Texture}
  28918. * @default null
  28919. */
  28920. this.alphaMap = null;
  28921. /**
  28922. * Renders the geometry as a wireframe.
  28923. *
  28924. * @type {boolean}
  28925. * @default false
  28926. */
  28927. this.wireframe = false;
  28928. /**
  28929. * Controls the thickness of the wireframe.
  28930. *
  28931. * Can only be used with {@link SVGRenderer}.
  28932. *
  28933. * @type {number}
  28934. * @default 1
  28935. */
  28936. this.wireframeLinewidth = 1;
  28937. /**
  28938. * Defines appearance of wireframe ends.
  28939. *
  28940. * Can only be used with {@link SVGRenderer}.
  28941. *
  28942. * @type {('round'|'bevel'|'miter')}
  28943. * @default 'round'
  28944. */
  28945. this.wireframeLinecap = 'round';
  28946. /**
  28947. * Defines appearance of wireframe joints.
  28948. *
  28949. * Can only be used with {@link SVGRenderer}.
  28950. *
  28951. * @type {('round'|'bevel'|'miter')}
  28952. * @default 'round'
  28953. */
  28954. this.wireframeLinejoin = 'round';
  28955. /**
  28956. * Whether the material is affected by fog or not.
  28957. *
  28958. * @type {boolean}
  28959. * @default true
  28960. */
  28961. this.fog = true;
  28962. this.setValues( parameters );
  28963. }
  28964. copy( source ) {
  28965. super.copy( source );
  28966. this.color.copy( source.color );
  28967. this.map = source.map;
  28968. this.gradientMap = source.gradientMap;
  28969. this.lightMap = source.lightMap;
  28970. this.lightMapIntensity = source.lightMapIntensity;
  28971. this.aoMap = source.aoMap;
  28972. this.aoMapIntensity = source.aoMapIntensity;
  28973. this.emissive.copy( source.emissive );
  28974. this.emissiveMap = source.emissiveMap;
  28975. this.emissiveIntensity = source.emissiveIntensity;
  28976. this.bumpMap = source.bumpMap;
  28977. this.bumpScale = source.bumpScale;
  28978. this.normalMap = source.normalMap;
  28979. this.normalMapType = source.normalMapType;
  28980. this.normalScale.copy( source.normalScale );
  28981. this.displacementMap = source.displacementMap;
  28982. this.displacementScale = source.displacementScale;
  28983. this.displacementBias = source.displacementBias;
  28984. this.alphaMap = source.alphaMap;
  28985. this.wireframe = source.wireframe;
  28986. this.wireframeLinewidth = source.wireframeLinewidth;
  28987. this.wireframeLinecap = source.wireframeLinecap;
  28988. this.wireframeLinejoin = source.wireframeLinejoin;
  28989. this.fog = source.fog;
  28990. return this;
  28991. }
  28992. }
  28993. /**
  28994. * A material that maps the normal vectors to RGB colors.
  28995. *
  28996. * @augments Material
  28997. */
  28998. class MeshNormalMaterial extends Material {
  28999. /**
  29000. * Constructs a new mesh normal material.
  29001. *
  29002. * @param {Object} [parameters] - An object with one or more properties
  29003. * defining the material's appearance. Any property of the material
  29004. * (including any property from inherited materials) can be passed
  29005. * in here. Color values can be passed any type of value accepted
  29006. * by {@link Color#set}.
  29007. */
  29008. constructor( parameters ) {
  29009. super();
  29010. /**
  29011. * This flag can be used for type testing.
  29012. *
  29013. * @type {boolean}
  29014. * @readonly
  29015. * @default true
  29016. */
  29017. this.isMeshNormalMaterial = true;
  29018. this.type = 'MeshNormalMaterial';
  29019. /**
  29020. * The texture to create a bump map. The black and white values map to the
  29021. * perceived depth in relation to the lights. Bump doesn't actually affect
  29022. * the geometry of the object, only the lighting. If a normal map is defined
  29023. * this will be ignored.
  29024. *
  29025. * @type {?Texture}
  29026. * @default null
  29027. */
  29028. this.bumpMap = null;
  29029. /**
  29030. * How much the bump map affects the material. Typical range is `[0,1]`.
  29031. *
  29032. * @type {number}
  29033. * @default 1
  29034. */
  29035. this.bumpScale = 1;
  29036. /**
  29037. * The texture to create a normal map. The RGB values affect the surface
  29038. * normal for each pixel fragment and change the way the color is lit. Normal
  29039. * maps do not change the actual shape of the surface, only the lighting. In
  29040. * case the material has a normal map authored using the left handed
  29041. * convention, the `y` component of `normalScale` should be negated to compensate
  29042. * for the different handedness.
  29043. *
  29044. * @type {?Texture}
  29045. * @default null
  29046. */
  29047. this.normalMap = null;
  29048. /**
  29049. * The type of normal map.
  29050. *
  29051. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29052. * @default TangentSpaceNormalMap
  29053. */
  29054. this.normalMapType = TangentSpaceNormalMap;
  29055. /**
  29056. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29057. *
  29058. * @type {Vector2}
  29059. * @default (1,1)
  29060. */
  29061. this.normalScale = new Vector2( 1, 1 );
  29062. /**
  29063. * The displacement map affects the position of the mesh's vertices. Unlike
  29064. * other maps which only affect the light and shade of the material the
  29065. * displaced vertices can cast shadows, block other objects, and otherwise
  29066. * act as real geometry. The displacement texture is an image where the value
  29067. * of each pixel (white being the highest) is mapped against, and
  29068. * repositions, the vertices of the mesh.
  29069. *
  29070. * @type {?Texture}
  29071. * @default null
  29072. */
  29073. this.displacementMap = null;
  29074. /**
  29075. * How much the displacement map affects the mesh (where black is no
  29076. * displacement, and white is maximum displacement). Without a displacement
  29077. * map set, this value is not applied.
  29078. *
  29079. * @type {number}
  29080. * @default 0
  29081. */
  29082. this.displacementScale = 1;
  29083. /**
  29084. * The offset of the displacement map's values on the mesh's vertices.
  29085. * The bias is added to the scaled sample of the displacement map.
  29086. * Without a displacement map set, this value is not applied.
  29087. *
  29088. * @type {number}
  29089. * @default 0
  29090. */
  29091. this.displacementBias = 0;
  29092. /**
  29093. * Renders the geometry as a wireframe.
  29094. *
  29095. * @type {boolean}
  29096. * @default false
  29097. */
  29098. this.wireframe = false;
  29099. /**
  29100. * Controls the thickness of the wireframe.
  29101. *
  29102. * WebGL and WebGPU ignore this property and always render
  29103. * 1 pixel wide lines.
  29104. *
  29105. * @type {number}
  29106. * @default 1
  29107. */
  29108. this.wireframeLinewidth = 1;
  29109. /**
  29110. * Whether the material is rendered with flat shading or not.
  29111. *
  29112. * @type {boolean}
  29113. * @default false
  29114. */
  29115. this.flatShading = false;
  29116. this.setValues( parameters );
  29117. }
  29118. copy( source ) {
  29119. super.copy( source );
  29120. this.bumpMap = source.bumpMap;
  29121. this.bumpScale = source.bumpScale;
  29122. this.normalMap = source.normalMap;
  29123. this.normalMapType = source.normalMapType;
  29124. this.normalScale.copy( source.normalScale );
  29125. this.displacementMap = source.displacementMap;
  29126. this.displacementScale = source.displacementScale;
  29127. this.displacementBias = source.displacementBias;
  29128. this.wireframe = source.wireframe;
  29129. this.wireframeLinewidth = source.wireframeLinewidth;
  29130. this.flatShading = source.flatShading;
  29131. return this;
  29132. }
  29133. }
  29134. /**
  29135. * A material for non-shiny surfaces, without specular highlights.
  29136. *
  29137. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29138. * model for calculating reflectance. This can simulate some surfaces (such
  29139. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29140. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29141. * shading.
  29142. *
  29143. * Due to the simplicity of the reflectance and illumination models,
  29144. * performance will be greater when using this material over the
  29145. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29146. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29147. *
  29148. * @augments Material
  29149. */
  29150. class MeshLambertMaterial extends Material {
  29151. /**
  29152. * Constructs a new mesh lambert material.
  29153. *
  29154. * @param {Object} [parameters] - An object with one or more properties
  29155. * defining the material's appearance. Any property of the material
  29156. * (including any property from inherited materials) can be passed
  29157. * in here. Color values can be passed any type of value accepted
  29158. * by {@link Color#set}.
  29159. */
  29160. constructor( parameters ) {
  29161. super();
  29162. /**
  29163. * This flag can be used for type testing.
  29164. *
  29165. * @type {boolean}
  29166. * @readonly
  29167. * @default true
  29168. */
  29169. this.isMeshLambertMaterial = true;
  29170. this.type = 'MeshLambertMaterial';
  29171. /**
  29172. * Color of the material.
  29173. *
  29174. * @type {Color}
  29175. * @default (1,1,1)
  29176. */
  29177. this.color = new Color( 0xffffff ); // diffuse
  29178. /**
  29179. * The color map. May optionally include an alpha channel, typically combined
  29180. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29181. * color is modulated by the diffuse `color`.
  29182. *
  29183. * @type {?Texture}
  29184. * @default null
  29185. */
  29186. this.map = null;
  29187. /**
  29188. * The light map. Requires a second set of UVs.
  29189. *
  29190. * @type {?Texture}
  29191. * @default null
  29192. */
  29193. this.lightMap = null;
  29194. /**
  29195. * Intensity of the baked light.
  29196. *
  29197. * @type {number}
  29198. * @default 1
  29199. */
  29200. this.lightMapIntensity = 1.0;
  29201. /**
  29202. * The red channel of this texture is used as the ambient occlusion map.
  29203. * Requires a second set of UVs.
  29204. *
  29205. * @type {?Texture}
  29206. * @default null
  29207. */
  29208. this.aoMap = null;
  29209. /**
  29210. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29211. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29212. * red channel is also `1`, ambient light is fully occluded on a surface.
  29213. *
  29214. * @type {number}
  29215. * @default 1
  29216. */
  29217. this.aoMapIntensity = 1.0;
  29218. /**
  29219. * Emissive (light) color of the material, essentially a solid color
  29220. * unaffected by other lighting.
  29221. *
  29222. * @type {Color}
  29223. * @default (0,0,0)
  29224. */
  29225. this.emissive = new Color( 0x000000 );
  29226. /**
  29227. * Intensity of the emissive light. Modulates the emissive color.
  29228. *
  29229. * @type {number}
  29230. * @default 1
  29231. */
  29232. this.emissiveIntensity = 1.0;
  29233. /**
  29234. * Set emissive (glow) map. The emissive map color is modulated by the
  29235. * emissive color and the emissive intensity. If you have an emissive map,
  29236. * be sure to set the emissive color to something other than black.
  29237. *
  29238. * @type {?Texture}
  29239. * @default null
  29240. */
  29241. this.emissiveMap = null;
  29242. /**
  29243. * The texture to create a bump map. The black and white values map to the
  29244. * perceived depth in relation to the lights. Bump doesn't actually affect
  29245. * the geometry of the object, only the lighting. If a normal map is defined
  29246. * this will be ignored.
  29247. *
  29248. * @type {?Texture}
  29249. * @default null
  29250. */
  29251. this.bumpMap = null;
  29252. /**
  29253. * How much the bump map affects the material. Typical range is `[0,1]`.
  29254. *
  29255. * @type {number}
  29256. * @default 1
  29257. */
  29258. this.bumpScale = 1;
  29259. /**
  29260. * The texture to create a normal map. The RGB values affect the surface
  29261. * normal for each pixel fragment and change the way the color is lit. Normal
  29262. * maps do not change the actual shape of the surface, only the lighting. In
  29263. * case the material has a normal map authored using the left handed
  29264. * convention, the `y` component of `normalScale` should be negated to compensate
  29265. * for the different handedness.
  29266. *
  29267. * @type {?Texture}
  29268. * @default null
  29269. */
  29270. this.normalMap = null;
  29271. /**
  29272. * The type of normal map.
  29273. *
  29274. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29275. * @default TangentSpaceNormalMap
  29276. */
  29277. this.normalMapType = TangentSpaceNormalMap;
  29278. /**
  29279. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29280. *
  29281. * @type {Vector2}
  29282. * @default (1,1)
  29283. */
  29284. this.normalScale = new Vector2( 1, 1 );
  29285. /**
  29286. * The displacement map affects the position of the mesh's vertices. Unlike
  29287. * other maps which only affect the light and shade of the material the
  29288. * displaced vertices can cast shadows, block other objects, and otherwise
  29289. * act as real geometry. The displacement texture is an image where the value
  29290. * of each pixel (white being the highest) is mapped against, and
  29291. * repositions, the vertices of the mesh.
  29292. *
  29293. * @type {?Texture}
  29294. * @default null
  29295. */
  29296. this.displacementMap = null;
  29297. /**
  29298. * How much the displacement map affects the mesh (where black is no
  29299. * displacement, and white is maximum displacement). Without a displacement
  29300. * map set, this value is not applied.
  29301. *
  29302. * @type {number}
  29303. * @default 0
  29304. */
  29305. this.displacementScale = 1;
  29306. /**
  29307. * The offset of the displacement map's values on the mesh's vertices.
  29308. * The bias is added to the scaled sample of the displacement map.
  29309. * Without a displacement map set, this value is not applied.
  29310. *
  29311. * @type {number}
  29312. * @default 0
  29313. */
  29314. this.displacementBias = 0;
  29315. /**
  29316. * Specular map used by the material.
  29317. *
  29318. * @type {?Texture}
  29319. * @default null
  29320. */
  29321. this.specularMap = null;
  29322. /**
  29323. * The alpha map is a grayscale texture that controls the opacity across the
  29324. * surface (black: fully transparent; white: fully opaque).
  29325. *
  29326. * Only the color of the texture is used, ignoring the alpha channel if one
  29327. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29328. * when sampling this texture due to the extra bit of precision provided for
  29329. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29330. * luminance/alpha textures will also still work as expected.
  29331. *
  29332. * @type {?Texture}
  29333. * @default null
  29334. */
  29335. this.alphaMap = null;
  29336. /**
  29337. * The environment map.
  29338. *
  29339. * @type {?Texture}
  29340. * @default null
  29341. */
  29342. this.envMap = null;
  29343. /**
  29344. * The rotation of the environment map in radians.
  29345. *
  29346. * @type {Euler}
  29347. * @default (0,0,0)
  29348. */
  29349. this.envMapRotation = new Euler();
  29350. /**
  29351. * How to combine the result of the surface's color with the environment map, if any.
  29352. *
  29353. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29354. * blend between the two colors.
  29355. *
  29356. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29357. * @default MultiplyOperation
  29358. */
  29359. this.combine = MultiplyOperation;
  29360. /**
  29361. * How much the environment map affects the surface.
  29362. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29363. *
  29364. * @type {number}
  29365. * @default 1
  29366. */
  29367. this.reflectivity = 1;
  29368. /**
  29369. * The index of refraction (IOR) of air (approximately 1) divided by the
  29370. * index of refraction of the material. It is used with environment mapping
  29371. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29372. * The refraction ratio should not exceed `1`.
  29373. *
  29374. * @type {number}
  29375. * @default 0.98
  29376. */
  29377. this.refractionRatio = 0.98;
  29378. /**
  29379. * Renders the geometry as a wireframe.
  29380. *
  29381. * @type {boolean}
  29382. * @default false
  29383. */
  29384. this.wireframe = false;
  29385. /**
  29386. * Controls the thickness of the wireframe.
  29387. *
  29388. * Can only be used with {@link SVGRenderer}.
  29389. *
  29390. * @type {number}
  29391. * @default 1
  29392. */
  29393. this.wireframeLinewidth = 1;
  29394. /**
  29395. * Defines appearance of wireframe ends.
  29396. *
  29397. * Can only be used with {@link SVGRenderer}.
  29398. *
  29399. * @type {('round'|'bevel'|'miter')}
  29400. * @default 'round'
  29401. */
  29402. this.wireframeLinecap = 'round';
  29403. /**
  29404. * Defines appearance of wireframe joints.
  29405. *
  29406. * Can only be used with {@link SVGRenderer}.
  29407. *
  29408. * @type {('round'|'bevel'|'miter')}
  29409. * @default 'round'
  29410. */
  29411. this.wireframeLinejoin = 'round';
  29412. /**
  29413. * Whether the material is rendered with flat shading or not.
  29414. *
  29415. * @type {boolean}
  29416. * @default false
  29417. */
  29418. this.flatShading = false;
  29419. /**
  29420. * Whether the material is affected by fog or not.
  29421. *
  29422. * @type {boolean}
  29423. * @default true
  29424. */
  29425. this.fog = true;
  29426. this.setValues( parameters );
  29427. }
  29428. copy( source ) {
  29429. super.copy( source );
  29430. this.color.copy( source.color );
  29431. this.map = source.map;
  29432. this.lightMap = source.lightMap;
  29433. this.lightMapIntensity = source.lightMapIntensity;
  29434. this.aoMap = source.aoMap;
  29435. this.aoMapIntensity = source.aoMapIntensity;
  29436. this.emissive.copy( source.emissive );
  29437. this.emissiveMap = source.emissiveMap;
  29438. this.emissiveIntensity = source.emissiveIntensity;
  29439. this.bumpMap = source.bumpMap;
  29440. this.bumpScale = source.bumpScale;
  29441. this.normalMap = source.normalMap;
  29442. this.normalMapType = source.normalMapType;
  29443. this.normalScale.copy( source.normalScale );
  29444. this.displacementMap = source.displacementMap;
  29445. this.displacementScale = source.displacementScale;
  29446. this.displacementBias = source.displacementBias;
  29447. this.specularMap = source.specularMap;
  29448. this.alphaMap = source.alphaMap;
  29449. this.envMap = source.envMap;
  29450. this.envMapRotation.copy( source.envMapRotation );
  29451. this.combine = source.combine;
  29452. this.reflectivity = source.reflectivity;
  29453. this.refractionRatio = source.refractionRatio;
  29454. this.wireframe = source.wireframe;
  29455. this.wireframeLinewidth = source.wireframeLinewidth;
  29456. this.wireframeLinecap = source.wireframeLinecap;
  29457. this.wireframeLinejoin = source.wireframeLinejoin;
  29458. this.flatShading = source.flatShading;
  29459. this.fog = source.fog;
  29460. return this;
  29461. }
  29462. }
  29463. /**
  29464. * A material for drawing geometry by depth. Depth is based off of the camera
  29465. * near and far plane. White is nearest, black is farthest.
  29466. *
  29467. * @augments Material
  29468. */
  29469. class MeshDepthMaterial extends Material {
  29470. /**
  29471. * Constructs a new mesh depth material.
  29472. *
  29473. * @param {Object} [parameters] - An object with one or more properties
  29474. * defining the material's appearance. Any property of the material
  29475. * (including any property from inherited materials) can be passed
  29476. * in here. Color values can be passed any type of value accepted
  29477. * by {@link Color#set}.
  29478. */
  29479. constructor( parameters ) {
  29480. super();
  29481. /**
  29482. * This flag can be used for type testing.
  29483. *
  29484. * @type {boolean}
  29485. * @readonly
  29486. * @default true
  29487. */
  29488. this.isMeshDepthMaterial = true;
  29489. this.type = 'MeshDepthMaterial';
  29490. /**
  29491. * Type for depth packing.
  29492. *
  29493. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29494. * @default BasicDepthPacking
  29495. */
  29496. this.depthPacking = BasicDepthPacking;
  29497. /**
  29498. * The color map. May optionally include an alpha channel, typically combined
  29499. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29500. *
  29501. * @type {?Texture}
  29502. * @default null
  29503. */
  29504. this.map = null;
  29505. /**
  29506. * The alpha map is a grayscale texture that controls the opacity across the
  29507. * surface (black: fully transparent; white: fully opaque).
  29508. *
  29509. * Only the color of the texture is used, ignoring the alpha channel if one
  29510. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29511. * when sampling this texture due to the extra bit of precision provided for
  29512. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29513. * luminance/alpha textures will also still work as expected.
  29514. *
  29515. * @type {?Texture}
  29516. * @default null
  29517. */
  29518. this.alphaMap = null;
  29519. /**
  29520. * The displacement map affects the position of the mesh's vertices. Unlike
  29521. * other maps which only affect the light and shade of the material the
  29522. * displaced vertices can cast shadows, block other objects, and otherwise
  29523. * act as real geometry. The displacement texture is an image where the value
  29524. * of each pixel (white being the highest) is mapped against, and
  29525. * repositions, the vertices of the mesh.
  29526. *
  29527. * @type {?Texture}
  29528. * @default null
  29529. */
  29530. this.displacementMap = null;
  29531. /**
  29532. * How much the displacement map affects the mesh (where black is no
  29533. * displacement, and white is maximum displacement). Without a displacement
  29534. * map set, this value is not applied.
  29535. *
  29536. * @type {number}
  29537. * @default 0
  29538. */
  29539. this.displacementScale = 1;
  29540. /**
  29541. * The offset of the displacement map's values on the mesh's vertices.
  29542. * The bias is added to the scaled sample of the displacement map.
  29543. * Without a displacement map set, this value is not applied.
  29544. *
  29545. * @type {number}
  29546. * @default 0
  29547. */
  29548. this.displacementBias = 0;
  29549. /**
  29550. * Renders the geometry as a wireframe.
  29551. *
  29552. * @type {boolean}
  29553. * @default false
  29554. */
  29555. this.wireframe = false;
  29556. /**
  29557. * Controls the thickness of the wireframe.
  29558. *
  29559. * WebGL and WebGPU ignore this property and always render
  29560. * 1 pixel wide lines.
  29561. *
  29562. * @type {number}
  29563. * @default 1
  29564. */
  29565. this.wireframeLinewidth = 1;
  29566. this.setValues( parameters );
  29567. }
  29568. copy( source ) {
  29569. super.copy( source );
  29570. this.depthPacking = source.depthPacking;
  29571. this.map = source.map;
  29572. this.alphaMap = source.alphaMap;
  29573. this.displacementMap = source.displacementMap;
  29574. this.displacementScale = source.displacementScale;
  29575. this.displacementBias = source.displacementBias;
  29576. this.wireframe = source.wireframe;
  29577. this.wireframeLinewidth = source.wireframeLinewidth;
  29578. return this;
  29579. }
  29580. }
  29581. /**
  29582. * A material used internally for implementing shadow mapping with
  29583. * point lights.
  29584. *
  29585. * Can also be used to customize the shadow casting of an object by assigning
  29586. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29587. * The following examples demonstrates this approach in order to ensure
  29588. * transparent parts of objects do no cast shadows.
  29589. *
  29590. * @augments Material
  29591. */
  29592. class MeshDistanceMaterial extends Material {
  29593. /**
  29594. * Constructs a new mesh distance material.
  29595. *
  29596. * @param {Object} [parameters] - An object with one or more properties
  29597. * defining the material's appearance. Any property of the material
  29598. * (including any property from inherited materials) can be passed
  29599. * in here. Color values can be passed any type of value accepted
  29600. * by {@link Color#set}.
  29601. */
  29602. constructor( parameters ) {
  29603. super();
  29604. /**
  29605. * This flag can be used for type testing.
  29606. *
  29607. * @type {boolean}
  29608. * @readonly
  29609. * @default true
  29610. */
  29611. this.isMeshDistanceMaterial = true;
  29612. this.type = 'MeshDistanceMaterial';
  29613. /**
  29614. * The color map. May optionally include an alpha channel, typically combined
  29615. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29616. *
  29617. * @type {?Texture}
  29618. * @default null
  29619. */
  29620. this.map = null;
  29621. /**
  29622. * The alpha map is a grayscale texture that controls the opacity across the
  29623. * surface (black: fully transparent; white: fully opaque).
  29624. *
  29625. * Only the color of the texture is used, ignoring the alpha channel if one
  29626. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29627. * when sampling this texture due to the extra bit of precision provided for
  29628. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29629. * luminance/alpha textures will also still work as expected.
  29630. *
  29631. * @type {?Texture}
  29632. * @default null
  29633. */
  29634. this.alphaMap = null;
  29635. /**
  29636. * The displacement map affects the position of the mesh's vertices. Unlike
  29637. * other maps which only affect the light and shade of the material the
  29638. * displaced vertices can cast shadows, block other objects, and otherwise
  29639. * act as real geometry. The displacement texture is an image where the value
  29640. * of each pixel (white being the highest) is mapped against, and
  29641. * repositions, the vertices of the mesh.
  29642. *
  29643. * @type {?Texture}
  29644. * @default null
  29645. */
  29646. this.displacementMap = null;
  29647. /**
  29648. * How much the displacement map affects the mesh (where black is no
  29649. * displacement, and white is maximum displacement). Without a displacement
  29650. * map set, this value is not applied.
  29651. *
  29652. * @type {number}
  29653. * @default 0
  29654. */
  29655. this.displacementScale = 1;
  29656. /**
  29657. * The offset of the displacement map's values on the mesh's vertices.
  29658. * The bias is added to the scaled sample of the displacement map.
  29659. * Without a displacement map set, this value is not applied.
  29660. *
  29661. * @type {number}
  29662. * @default 0
  29663. */
  29664. this.displacementBias = 0;
  29665. this.setValues( parameters );
  29666. }
  29667. copy( source ) {
  29668. super.copy( source );
  29669. this.map = source.map;
  29670. this.alphaMap = source.alphaMap;
  29671. this.displacementMap = source.displacementMap;
  29672. this.displacementScale = source.displacementScale;
  29673. this.displacementBias = source.displacementBias;
  29674. return this;
  29675. }
  29676. }
  29677. /**
  29678. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29679. * material color and shading.
  29680. *
  29681. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29682. * baked lighting. It will cast a shadow onto an object that receives shadows
  29683. * (and shadow clipping works), but it will not self-shadow or receive
  29684. * shadows.
  29685. *
  29686. * @augments Material
  29687. */
  29688. class MeshMatcapMaterial extends Material {
  29689. /**
  29690. * Constructs a new mesh matcap material.
  29691. *
  29692. * @param {Object} [parameters] - An object with one or more properties
  29693. * defining the material's appearance. Any property of the material
  29694. * (including any property from inherited materials) can be passed
  29695. * in here. Color values can be passed any type of value accepted
  29696. * by {@link Color#set}.
  29697. */
  29698. constructor( parameters ) {
  29699. super();
  29700. /**
  29701. * This flag can be used for type testing.
  29702. *
  29703. * @type {boolean}
  29704. * @readonly
  29705. * @default true
  29706. */
  29707. this.isMeshMatcapMaterial = true;
  29708. this.defines = { 'MATCAP': '' };
  29709. this.type = 'MeshMatcapMaterial';
  29710. /**
  29711. * Color of the material.
  29712. *
  29713. * @type {Color}
  29714. * @default (1,1,1)
  29715. */
  29716. this.color = new Color( 0xffffff ); // diffuse
  29717. /**
  29718. * The matcap map.
  29719. *
  29720. * @type {?Texture}
  29721. * @default null
  29722. */
  29723. this.matcap = null;
  29724. /**
  29725. * The color map. May optionally include an alpha channel, typically combined
  29726. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29727. * color is modulated by the diffuse `color`.
  29728. *
  29729. * @type {?Texture}
  29730. * @default null
  29731. */
  29732. this.map = null;
  29733. /**
  29734. * The texture to create a bump map. The black and white values map to the
  29735. * perceived depth in relation to the lights. Bump doesn't actually affect
  29736. * the geometry of the object, only the lighting. If a normal map is defined
  29737. * this will be ignored.
  29738. *
  29739. * @type {?Texture}
  29740. * @default null
  29741. */
  29742. this.bumpMap = null;
  29743. /**
  29744. * How much the bump map affects the material. Typical range is `[0,1]`.
  29745. *
  29746. * @type {number}
  29747. * @default 1
  29748. */
  29749. this.bumpScale = 1;
  29750. /**
  29751. * The texture to create a normal map. The RGB values affect the surface
  29752. * normal for each pixel fragment and change the way the color is lit. Normal
  29753. * maps do not change the actual shape of the surface, only the lighting. In
  29754. * case the material has a normal map authored using the left handed
  29755. * convention, the `y` component of `normalScale` should be negated to compensate
  29756. * for the different handedness.
  29757. *
  29758. * @type {?Texture}
  29759. * @default null
  29760. */
  29761. this.normalMap = null;
  29762. /**
  29763. * The type of normal map.
  29764. *
  29765. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29766. * @default TangentSpaceNormalMap
  29767. */
  29768. this.normalMapType = TangentSpaceNormalMap;
  29769. /**
  29770. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29771. *
  29772. * @type {Vector2}
  29773. * @default (1,1)
  29774. */
  29775. this.normalScale = new Vector2( 1, 1 );
  29776. /**
  29777. * The displacement map affects the position of the mesh's vertices. Unlike
  29778. * other maps which only affect the light and shade of the material the
  29779. * displaced vertices can cast shadows, block other objects, and otherwise
  29780. * act as real geometry. The displacement texture is an image where the value
  29781. * of each pixel (white being the highest) is mapped against, and
  29782. * repositions, the vertices of the mesh.
  29783. *
  29784. * @type {?Texture}
  29785. * @default null
  29786. */
  29787. this.displacementMap = null;
  29788. /**
  29789. * How much the displacement map affects the mesh (where black is no
  29790. * displacement, and white is maximum displacement). Without a displacement
  29791. * map set, this value is not applied.
  29792. *
  29793. * @type {number}
  29794. * @default 0
  29795. */
  29796. this.displacementScale = 1;
  29797. /**
  29798. * The offset of the displacement map's values on the mesh's vertices.
  29799. * The bias is added to the scaled sample of the displacement map.
  29800. * Without a displacement map set, this value is not applied.
  29801. *
  29802. * @type {number}
  29803. * @default 0
  29804. */
  29805. this.displacementBias = 0;
  29806. /**
  29807. * The alpha map is a grayscale texture that controls the opacity across the
  29808. * surface (black: fully transparent; white: fully opaque).
  29809. *
  29810. * Only the color of the texture is used, ignoring the alpha channel if one
  29811. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29812. * when sampling this texture due to the extra bit of precision provided for
  29813. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29814. * luminance/alpha textures will also still work as expected.
  29815. *
  29816. * @type {?Texture}
  29817. * @default null
  29818. */
  29819. this.alphaMap = null;
  29820. /**
  29821. * Whether the material is rendered with flat shading or not.
  29822. *
  29823. * @type {boolean}
  29824. * @default false
  29825. */
  29826. this.flatShading = false;
  29827. /**
  29828. * Whether the material is affected by fog or not.
  29829. *
  29830. * @type {boolean}
  29831. * @default true
  29832. */
  29833. this.fog = true;
  29834. this.setValues( parameters );
  29835. }
  29836. copy( source ) {
  29837. super.copy( source );
  29838. this.defines = { 'MATCAP': '' };
  29839. this.color.copy( source.color );
  29840. this.matcap = source.matcap;
  29841. this.map = source.map;
  29842. this.bumpMap = source.bumpMap;
  29843. this.bumpScale = source.bumpScale;
  29844. this.normalMap = source.normalMap;
  29845. this.normalMapType = source.normalMapType;
  29846. this.normalScale.copy( source.normalScale );
  29847. this.displacementMap = source.displacementMap;
  29848. this.displacementScale = source.displacementScale;
  29849. this.displacementBias = source.displacementBias;
  29850. this.alphaMap = source.alphaMap;
  29851. this.flatShading = source.flatShading;
  29852. this.fog = source.fog;
  29853. return this;
  29854. }
  29855. }
  29856. /**
  29857. * A material for rendering line primitives.
  29858. *
  29859. * Materials define the appearance of renderable 3D objects.
  29860. *
  29861. * ```js
  29862. * const material = new THREE.LineDashedMaterial( {
  29863. * color: 0xffffff,
  29864. * scale: 1,
  29865. * dashSize: 3,
  29866. * gapSize: 1,
  29867. * } );
  29868. * ```
  29869. *
  29870. * @augments LineBasicMaterial
  29871. */
  29872. class LineDashedMaterial extends LineBasicMaterial {
  29873. /**
  29874. * Constructs a new line dashed material.
  29875. *
  29876. * @param {Object} [parameters] - An object with one or more properties
  29877. * defining the material's appearance. Any property of the material
  29878. * (including any property from inherited materials) can be passed
  29879. * in here. Color values can be passed any type of value accepted
  29880. * by {@link Color#set}.
  29881. */
  29882. constructor( parameters ) {
  29883. super();
  29884. /**
  29885. * This flag can be used for type testing.
  29886. *
  29887. * @type {boolean}
  29888. * @readonly
  29889. * @default true
  29890. */
  29891. this.isLineDashedMaterial = true;
  29892. this.type = 'LineDashedMaterial';
  29893. /**
  29894. * The scale of the dashed part of a line.
  29895. *
  29896. * @type {number}
  29897. * @default 1
  29898. */
  29899. this.scale = 1;
  29900. /**
  29901. * The size of the dash. This is both the gap with the stroke.
  29902. *
  29903. * @type {number}
  29904. * @default 3
  29905. */
  29906. this.dashSize = 3;
  29907. /**
  29908. * The size of the gap.
  29909. *
  29910. * @type {number}
  29911. * @default 1
  29912. */
  29913. this.gapSize = 1;
  29914. this.setValues( parameters );
  29915. }
  29916. copy( source ) {
  29917. super.copy( source );
  29918. this.scale = source.scale;
  29919. this.dashSize = source.dashSize;
  29920. this.gapSize = source.gapSize;
  29921. return this;
  29922. }
  29923. }
  29924. /**
  29925. * Converts an array to a specific type.
  29926. *
  29927. * @param {TypedArray|Array} array - The array to convert.
  29928. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29929. * @return {TypedArray} The converted array.
  29930. */
  29931. function convertArray( array, type ) {
  29932. if ( ! array || array.constructor === type ) return array;
  29933. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29934. return new type( array ); // create typed array
  29935. }
  29936. return Array.prototype.slice.call( array ); // create Array
  29937. }
  29938. /**
  29939. * Returns `true` if the given object is a typed array.
  29940. *
  29941. * @param {any} object - The object to check.
  29942. * @return {boolean} Whether the given object is a typed array.
  29943. */
  29944. function isTypedArray( object ) {
  29945. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29946. }
  29947. /**
  29948. * Returns an array by which times and values can be sorted.
  29949. *
  29950. * @param {Array<number>} times - The keyframe time values.
  29951. * @return {Array<number>} The array.
  29952. */
  29953. function getKeyframeOrder( times ) {
  29954. function compareTime( i, j ) {
  29955. return times[ i ] - times[ j ];
  29956. }
  29957. const n = times.length;
  29958. const result = new Array( n );
  29959. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29960. result.sort( compareTime );
  29961. return result;
  29962. }
  29963. /**
  29964. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29965. *
  29966. * @param {Array<number>} values - The values to sort.
  29967. * @param {number} stride - The stride.
  29968. * @param {Array<number>} order - The sort order.
  29969. * @return {Array<number>} The sorted values.
  29970. */
  29971. function sortedArray( values, stride, order ) {
  29972. const nValues = values.length;
  29973. const result = new values.constructor( nValues );
  29974. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29975. const srcOffset = order[ i ] * stride;
  29976. for ( let j = 0; j !== stride; ++ j ) {
  29977. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29978. }
  29979. }
  29980. return result;
  29981. }
  29982. /**
  29983. * Used for parsing AOS keyframe formats.
  29984. *
  29985. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29986. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29987. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29988. * @param {string} valuePropertyName - The name of the property to use.
  29989. */
  29990. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29991. let i = 1, key = jsonKeys[ 0 ];
  29992. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29993. key = jsonKeys[ i ++ ];
  29994. }
  29995. if ( key === undefined ) return; // no data
  29996. let value = key[ valuePropertyName ];
  29997. if ( value === undefined ) return; // no data
  29998. if ( Array.isArray( value ) ) {
  29999. do {
  30000. value = key[ valuePropertyName ];
  30001. if ( value !== undefined ) {
  30002. times.push( key.time );
  30003. values.push( ...value ); // push all elements
  30004. }
  30005. key = jsonKeys[ i ++ ];
  30006. } while ( key !== undefined );
  30007. } else if ( value.toArray !== undefined ) {
  30008. // ...assume THREE.Math-ish
  30009. do {
  30010. value = key[ valuePropertyName ];
  30011. if ( value !== undefined ) {
  30012. times.push( key.time );
  30013. value.toArray( values, values.length );
  30014. }
  30015. key = jsonKeys[ i ++ ];
  30016. } while ( key !== undefined );
  30017. } else {
  30018. // otherwise push as-is
  30019. do {
  30020. value = key[ valuePropertyName ];
  30021. if ( value !== undefined ) {
  30022. times.push( key.time );
  30023. values.push( value );
  30024. }
  30025. key = jsonKeys[ i ++ ];
  30026. } while ( key !== undefined );
  30027. }
  30028. }
  30029. /**
  30030. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30031. *
  30032. * @param {AnimationClip} sourceClip - The values to sort.
  30033. * @param {string} name - The name of the clip.
  30034. * @param {number} startFrame - The start frame.
  30035. * @param {number} endFrame - The end frame.
  30036. * @param {number} [fps=30] - The FPS.
  30037. * @return {AnimationClip} The new sub clip.
  30038. */
  30039. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30040. const clip = sourceClip.clone();
  30041. clip.name = name;
  30042. const tracks = [];
  30043. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30044. const track = clip.tracks[ i ];
  30045. const valueSize = track.getValueSize();
  30046. const times = [];
  30047. const values = [];
  30048. for ( let j = 0; j < track.times.length; ++ j ) {
  30049. const frame = track.times[ j ] * fps;
  30050. if ( frame < startFrame || frame >= endFrame ) continue;
  30051. times.push( track.times[ j ] );
  30052. for ( let k = 0; k < valueSize; ++ k ) {
  30053. values.push( track.values[ j * valueSize + k ] );
  30054. }
  30055. }
  30056. if ( times.length === 0 ) continue;
  30057. track.times = convertArray( times, track.times.constructor );
  30058. track.values = convertArray( values, track.values.constructor );
  30059. tracks.push( track );
  30060. }
  30061. clip.tracks = tracks;
  30062. // find minimum .times value across all tracks in the trimmed clip
  30063. let minStartTime = Infinity;
  30064. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30065. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30066. minStartTime = clip.tracks[ i ].times[ 0 ];
  30067. }
  30068. }
  30069. // shift all tracks such that clip begins at t=0
  30070. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30071. clip.tracks[ i ].shift( -1 * minStartTime );
  30072. }
  30073. clip.resetDuration();
  30074. return clip;
  30075. }
  30076. /**
  30077. * Converts the keyframes of the given animation clip to an additive format.
  30078. *
  30079. * @param {AnimationClip} targetClip - The clip to make additive.
  30080. * @param {number} [referenceFrame=0] - The reference frame.
  30081. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30082. * @param {number} [fps=30] - The FPS.
  30083. * @return {AnimationClip} The updated clip which is now additive.
  30084. */
  30085. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30086. if ( fps <= 0 ) fps = 30;
  30087. const numTracks = referenceClip.tracks.length;
  30088. const referenceTime = referenceFrame / fps;
  30089. // Make each track's values relative to the values at the reference frame
  30090. for ( let i = 0; i < numTracks; ++ i ) {
  30091. const referenceTrack = referenceClip.tracks[ i ];
  30092. const referenceTrackType = referenceTrack.ValueTypeName;
  30093. // Skip this track if it's non-numeric
  30094. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30095. // Find the track in the target clip whose name and type matches the reference track
  30096. const targetTrack = targetClip.tracks.find( function ( track ) {
  30097. return track.name === referenceTrack.name
  30098. && track.ValueTypeName === referenceTrackType;
  30099. } );
  30100. if ( targetTrack === undefined ) continue;
  30101. let referenceOffset = 0;
  30102. const referenceValueSize = referenceTrack.getValueSize();
  30103. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30104. referenceOffset = referenceValueSize / 3;
  30105. }
  30106. let targetOffset = 0;
  30107. const targetValueSize = targetTrack.getValueSize();
  30108. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30109. targetOffset = targetValueSize / 3;
  30110. }
  30111. const lastIndex = referenceTrack.times.length - 1;
  30112. let referenceValue;
  30113. // Find the value to subtract out of the track
  30114. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30115. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30116. const startIndex = referenceOffset;
  30117. const endIndex = referenceValueSize - referenceOffset;
  30118. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30119. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30120. // Reference frame is after the last keyframe, so just use the last keyframe
  30121. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30122. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30123. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30124. } else {
  30125. // Interpolate to the reference value
  30126. const interpolant = referenceTrack.createInterpolant();
  30127. const startIndex = referenceOffset;
  30128. const endIndex = referenceValueSize - referenceOffset;
  30129. interpolant.evaluate( referenceTime );
  30130. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30131. }
  30132. // Conjugate the quaternion
  30133. if ( referenceTrackType === 'quaternion' ) {
  30134. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30135. referenceQuat.toArray( referenceValue );
  30136. }
  30137. // Subtract the reference value from all of the track values
  30138. const numTimes = targetTrack.times.length;
  30139. for ( let j = 0; j < numTimes; ++ j ) {
  30140. const valueStart = j * targetValueSize + targetOffset;
  30141. if ( referenceTrackType === 'quaternion' ) {
  30142. // Multiply the conjugate for quaternion track types
  30143. Quaternion.multiplyQuaternionsFlat(
  30144. targetTrack.values,
  30145. valueStart,
  30146. referenceValue,
  30147. 0,
  30148. targetTrack.values,
  30149. valueStart
  30150. );
  30151. } else {
  30152. const valueEnd = targetValueSize - targetOffset * 2;
  30153. // Subtract each value for all other numeric track types
  30154. for ( let k = 0; k < valueEnd; ++ k ) {
  30155. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30156. }
  30157. }
  30158. }
  30159. }
  30160. targetClip.blendMode = AdditiveAnimationBlendMode;
  30161. return targetClip;
  30162. }
  30163. /**
  30164. * A class with various methods to assist with animations.
  30165. *
  30166. * @hideconstructor
  30167. */
  30168. class AnimationUtils {
  30169. /**
  30170. * Converts an array to a specific type
  30171. *
  30172. * @static
  30173. * @param {TypedArray|Array} array - The array to convert.
  30174. * @param {TypedArray.constructor} type - The constructor of a type array.
  30175. * @return {TypedArray} The converted array
  30176. */
  30177. static convertArray( array, type ) {
  30178. return convertArray( array, type );
  30179. }
  30180. /**
  30181. * Returns `true` if the given object is a typed array.
  30182. *
  30183. * @static
  30184. * @param {any} object - The object to check.
  30185. * @return {boolean} Whether the given object is a typed array.
  30186. */
  30187. static isTypedArray( object ) {
  30188. return isTypedArray( object );
  30189. }
  30190. /**
  30191. * Returns an array by which times and values can be sorted.
  30192. *
  30193. * @static
  30194. * @param {Array<number>} times - The keyframe time values.
  30195. * @return {Array<number>} The array.
  30196. */
  30197. static getKeyframeOrder( times ) {
  30198. return getKeyframeOrder( times );
  30199. }
  30200. /**
  30201. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30202. *
  30203. * @static
  30204. * @param {Array<number>} values - The values to sort.
  30205. * @param {number} stride - The stride.
  30206. * @param {Array<number>} order - The sort order.
  30207. * @return {Array<number>} The sorted values.
  30208. */
  30209. static sortedArray( values, stride, order ) {
  30210. return sortedArray( values, stride, order );
  30211. }
  30212. /**
  30213. * Used for parsing AOS keyframe formats.
  30214. *
  30215. * @static
  30216. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30217. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30218. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30219. * @param {string} valuePropertyName - The name of the property to use.
  30220. */
  30221. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30222. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30223. }
  30224. /**
  30225. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30226. *
  30227. * @static
  30228. * @param {AnimationClip} sourceClip - The values to sort.
  30229. * @param {string} name - The name of the clip.
  30230. * @param {number} startFrame - The start frame.
  30231. * @param {number} endFrame - The end frame.
  30232. * @param {number} [fps=30] - The FPS.
  30233. * @return {AnimationClip} The new sub clip.
  30234. */
  30235. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30236. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30237. }
  30238. /**
  30239. * Converts the keyframes of the given animation clip to an additive format.
  30240. *
  30241. * @static
  30242. * @param {AnimationClip} targetClip - The clip to make additive.
  30243. * @param {number} [referenceFrame=0] - The reference frame.
  30244. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30245. * @param {number} [fps=30] - The FPS.
  30246. * @return {AnimationClip} The updated clip which is now additive.
  30247. */
  30248. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30249. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30250. }
  30251. }
  30252. /**
  30253. * Abstract base class of interpolants over parametric samples.
  30254. *
  30255. * The parameter domain is one dimensional, typically the time or a path
  30256. * along a curve defined by the data.
  30257. *
  30258. * The sample values can have any dimensionality and derived classes may
  30259. * apply special interpretations to the data.
  30260. *
  30261. * This class provides the interval seek in a Template Method, deferring
  30262. * the actual interpolation to derived classes.
  30263. *
  30264. * Time complexity is O(1) for linear access crossing at most two points
  30265. * and O(log N) for random access, where N is the number of positions.
  30266. *
  30267. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30268. *
  30269. * @abstract
  30270. */
  30271. class Interpolant {
  30272. /**
  30273. * Constructs a new interpolant.
  30274. *
  30275. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30276. * @param {TypedArray} sampleValues - The sample values.
  30277. * @param {number} sampleSize - The sample size
  30278. * @param {TypedArray} [resultBuffer] - The result buffer.
  30279. */
  30280. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30281. /**
  30282. * The parameter positions.
  30283. *
  30284. * @type {TypedArray}
  30285. */
  30286. this.parameterPositions = parameterPositions;
  30287. /**
  30288. * A cache index.
  30289. *
  30290. * @private
  30291. * @type {number}
  30292. * @default 0
  30293. */
  30294. this._cachedIndex = 0;
  30295. /**
  30296. * The result buffer.
  30297. *
  30298. * @type {TypedArray}
  30299. */
  30300. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30301. /**
  30302. * The sample values.
  30303. *
  30304. * @type {TypedArray}
  30305. */
  30306. this.sampleValues = sampleValues;
  30307. /**
  30308. * The value size.
  30309. *
  30310. * @type {TypedArray}
  30311. */
  30312. this.valueSize = sampleSize;
  30313. /**
  30314. * The interpolation settings.
  30315. *
  30316. * @type {?Object}
  30317. * @default null
  30318. */
  30319. this.settings = null;
  30320. /**
  30321. * The default settings object.
  30322. *
  30323. * @type {Object}
  30324. */
  30325. this.DefaultSettings_ = {};
  30326. }
  30327. /**
  30328. * Evaluate the interpolant at position `t`.
  30329. *
  30330. * @param {number} t - The interpolation factor.
  30331. * @return {TypedArray} The result buffer.
  30332. */
  30333. evaluate( t ) {
  30334. const pp = this.parameterPositions;
  30335. let i1 = this._cachedIndex,
  30336. t1 = pp[ i1 ],
  30337. t0 = pp[ i1 - 1 ];
  30338. validate_interval: {
  30339. seek: {
  30340. let right;
  30341. linear_scan: {
  30342. //- See http://jsperf.com/comparison-to-undefined/3
  30343. //- slower code:
  30344. //-
  30345. //- if ( t >= t1 || t1 === undefined ) {
  30346. forward_scan: if ( ! ( t < t1 ) ) {
  30347. for ( let giveUpAt = i1 + 2; ; ) {
  30348. if ( t1 === undefined ) {
  30349. if ( t < t0 ) break forward_scan;
  30350. // after end
  30351. i1 = pp.length;
  30352. this._cachedIndex = i1;
  30353. return this.copySampleValue_( i1 - 1 );
  30354. }
  30355. if ( i1 === giveUpAt ) break; // this loop
  30356. t0 = t1;
  30357. t1 = pp[ ++ i1 ];
  30358. if ( t < t1 ) {
  30359. // we have arrived at the sought interval
  30360. break seek;
  30361. }
  30362. }
  30363. // prepare binary search on the right side of the index
  30364. right = pp.length;
  30365. break linear_scan;
  30366. }
  30367. //- slower code:
  30368. //- if ( t < t0 || t0 === undefined ) {
  30369. if ( ! ( t >= t0 ) ) {
  30370. // looping?
  30371. const t1global = pp[ 1 ];
  30372. if ( t < t1global ) {
  30373. i1 = 2; // + 1, using the scan for the details
  30374. t0 = t1global;
  30375. }
  30376. // linear reverse scan
  30377. for ( let giveUpAt = i1 - 2; ; ) {
  30378. if ( t0 === undefined ) {
  30379. // before start
  30380. this._cachedIndex = 0;
  30381. return this.copySampleValue_( 0 );
  30382. }
  30383. if ( i1 === giveUpAt ) break; // this loop
  30384. t1 = t0;
  30385. t0 = pp[ -- i1 - 1 ];
  30386. if ( t >= t0 ) {
  30387. // we have arrived at the sought interval
  30388. break seek;
  30389. }
  30390. }
  30391. // prepare binary search on the left side of the index
  30392. right = i1;
  30393. i1 = 0;
  30394. break linear_scan;
  30395. }
  30396. // the interval is valid
  30397. break validate_interval;
  30398. } // linear scan
  30399. // binary search
  30400. while ( i1 < right ) {
  30401. const mid = ( i1 + right ) >>> 1;
  30402. if ( t < pp[ mid ] ) {
  30403. right = mid;
  30404. } else {
  30405. i1 = mid + 1;
  30406. }
  30407. }
  30408. t1 = pp[ i1 ];
  30409. t0 = pp[ i1 - 1 ];
  30410. // check boundary cases, again
  30411. if ( t0 === undefined ) {
  30412. this._cachedIndex = 0;
  30413. return this.copySampleValue_( 0 );
  30414. }
  30415. if ( t1 === undefined ) {
  30416. i1 = pp.length;
  30417. this._cachedIndex = i1;
  30418. return this.copySampleValue_( i1 - 1 );
  30419. }
  30420. } // seek
  30421. this._cachedIndex = i1;
  30422. this.intervalChanged_( i1, t0, t1 );
  30423. } // validate_interval
  30424. return this.interpolate_( i1, t0, t, t1 );
  30425. }
  30426. /**
  30427. * Returns the interpolation settings.
  30428. *
  30429. * @return {Object} The interpolation settings.
  30430. */
  30431. getSettings_() {
  30432. return this.settings || this.DefaultSettings_;
  30433. }
  30434. /**
  30435. * Copies a sample value to the result buffer.
  30436. *
  30437. * @param {number} index - An index into the sample value buffer.
  30438. * @return {TypedArray} The result buffer.
  30439. */
  30440. copySampleValue_( index ) {
  30441. // copies a sample value to the result buffer
  30442. const result = this.resultBuffer,
  30443. values = this.sampleValues,
  30444. stride = this.valueSize,
  30445. offset = index * stride;
  30446. for ( let i = 0; i !== stride; ++ i ) {
  30447. result[ i ] = values[ offset + i ];
  30448. }
  30449. return result;
  30450. }
  30451. /**
  30452. * Copies a sample value to the result buffer.
  30453. *
  30454. * @abstract
  30455. * @param {number} i1 - An index into the sample value buffer.
  30456. * @param {number} t0 - The previous interpolation factor.
  30457. * @param {number} t - The current interpolation factor.
  30458. * @param {number} t1 - The next interpolation factor.
  30459. * @return {TypedArray} The result buffer.
  30460. */
  30461. interpolate_( /* i1, t0, t, t1 */ ) {
  30462. throw new Error( 'call to abstract method' );
  30463. // implementations shall return this.resultBuffer
  30464. }
  30465. /**
  30466. * Optional method that is executed when the interval has changed.
  30467. *
  30468. * @param {number} i1 - An index into the sample value buffer.
  30469. * @param {number} t0 - The previous interpolation factor.
  30470. * @param {number} t - The current interpolation factor.
  30471. */
  30472. intervalChanged_( /* i1, t0, t1 */ ) {
  30473. // empty
  30474. }
  30475. }
  30476. /**
  30477. * Fast and simple cubic spline interpolant.
  30478. *
  30479. * It was derived from a Hermitian construction setting the first derivative
  30480. * at each sample position to the linear slope between neighboring positions
  30481. * over their parameter interval.
  30482. *
  30483. * @augments Interpolant
  30484. */
  30485. class CubicInterpolant extends Interpolant {
  30486. /**
  30487. * Constructs a new cubic interpolant.
  30488. *
  30489. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30490. * @param {TypedArray} sampleValues - The sample values.
  30491. * @param {number} sampleSize - The sample size
  30492. * @param {TypedArray} [resultBuffer] - The result buffer.
  30493. */
  30494. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30495. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30496. this._weightPrev = -0;
  30497. this._offsetPrev = -0;
  30498. this._weightNext = -0;
  30499. this._offsetNext = -0;
  30500. this.DefaultSettings_ = {
  30501. endingStart: ZeroCurvatureEnding,
  30502. endingEnd: ZeroCurvatureEnding
  30503. };
  30504. }
  30505. intervalChanged_( i1, t0, t1 ) {
  30506. const pp = this.parameterPositions;
  30507. let iPrev = i1 - 2,
  30508. iNext = i1 + 1,
  30509. tPrev = pp[ iPrev ],
  30510. tNext = pp[ iNext ];
  30511. if ( tPrev === undefined ) {
  30512. switch ( this.getSettings_().endingStart ) {
  30513. case ZeroSlopeEnding:
  30514. // f'(t0) = 0
  30515. iPrev = i1;
  30516. tPrev = 2 * t0 - t1;
  30517. break;
  30518. case WrapAroundEnding:
  30519. // use the other end of the curve
  30520. iPrev = pp.length - 2;
  30521. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30522. break;
  30523. default: // ZeroCurvatureEnding
  30524. // f''(t0) = 0 a.k.a. Natural Spline
  30525. iPrev = i1;
  30526. tPrev = t1;
  30527. }
  30528. }
  30529. if ( tNext === undefined ) {
  30530. switch ( this.getSettings_().endingEnd ) {
  30531. case ZeroSlopeEnding:
  30532. // f'(tN) = 0
  30533. iNext = i1;
  30534. tNext = 2 * t1 - t0;
  30535. break;
  30536. case WrapAroundEnding:
  30537. // use the other end of the curve
  30538. iNext = 1;
  30539. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30540. break;
  30541. default: // ZeroCurvatureEnding
  30542. // f''(tN) = 0, a.k.a. Natural Spline
  30543. iNext = i1 - 1;
  30544. tNext = t0;
  30545. }
  30546. }
  30547. const halfDt = ( t1 - t0 ) * 0.5,
  30548. stride = this.valueSize;
  30549. this._weightPrev = halfDt / ( t0 - tPrev );
  30550. this._weightNext = halfDt / ( tNext - t1 );
  30551. this._offsetPrev = iPrev * stride;
  30552. this._offsetNext = iNext * stride;
  30553. }
  30554. interpolate_( i1, t0, t, t1 ) {
  30555. const result = this.resultBuffer,
  30556. values = this.sampleValues,
  30557. stride = this.valueSize,
  30558. o1 = i1 * stride, o0 = o1 - stride,
  30559. oP = this._offsetPrev, oN = this._offsetNext,
  30560. wP = this._weightPrev, wN = this._weightNext,
  30561. p = ( t - t0 ) / ( t1 - t0 ),
  30562. pp = p * p,
  30563. ppp = pp * p;
  30564. // evaluate polynomials
  30565. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30566. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30567. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30568. const sN = wN * ppp - wN * pp;
  30569. // combine data linearly
  30570. for ( let i = 0; i !== stride; ++ i ) {
  30571. result[ i ] =
  30572. sP * values[ oP + i ] +
  30573. s0 * values[ o0 + i ] +
  30574. s1 * values[ o1 + i ] +
  30575. sN * values[ oN + i ];
  30576. }
  30577. return result;
  30578. }
  30579. }
  30580. /**
  30581. * A basic linear interpolant.
  30582. *
  30583. * @augments Interpolant
  30584. */
  30585. class LinearInterpolant extends Interpolant {
  30586. /**
  30587. * Constructs a new linear interpolant.
  30588. *
  30589. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30590. * @param {TypedArray} sampleValues - The sample values.
  30591. * @param {number} sampleSize - The sample size
  30592. * @param {TypedArray} [resultBuffer] - The result buffer.
  30593. */
  30594. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30595. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30596. }
  30597. interpolate_( i1, t0, t, t1 ) {
  30598. const result = this.resultBuffer,
  30599. values = this.sampleValues,
  30600. stride = this.valueSize,
  30601. offset1 = i1 * stride,
  30602. offset0 = offset1 - stride,
  30603. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30604. weight0 = 1 - weight1;
  30605. for ( let i = 0; i !== stride; ++ i ) {
  30606. result[ i ] =
  30607. values[ offset0 + i ] * weight0 +
  30608. values[ offset1 + i ] * weight1;
  30609. }
  30610. return result;
  30611. }
  30612. }
  30613. /**
  30614. * Interpolant that evaluates to the sample value at the position preceding
  30615. * the parameter.
  30616. *
  30617. * @augments Interpolant
  30618. */
  30619. class DiscreteInterpolant extends Interpolant {
  30620. /**
  30621. * Constructs a new discrete interpolant.
  30622. *
  30623. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30624. * @param {TypedArray} sampleValues - The sample values.
  30625. * @param {number} sampleSize - The sample size
  30626. * @param {TypedArray} [resultBuffer] - The result buffer.
  30627. */
  30628. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30629. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30630. }
  30631. interpolate_( i1 /*, t0, t, t1 */ ) {
  30632. return this.copySampleValue_( i1 - 1 );
  30633. }
  30634. }
  30635. /**
  30636. * Represents s a timed sequence of keyframes, which are composed of lists of
  30637. * times and related values, and which are used to animate a specific property
  30638. * of an object.
  30639. */
  30640. class KeyframeTrack {
  30641. /**
  30642. * Constructs a new keyframe track.
  30643. *
  30644. * @param {string} name - The keyframe track's name.
  30645. * @param {Array<number>} times - A list of keyframe times.
  30646. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30647. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30648. */
  30649. constructor( name, times, values, interpolation ) {
  30650. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30651. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30652. /**
  30653. * The track's name can refer to morph targets or bones or
  30654. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30655. * for the forms of strings that can be parsed for property binding.
  30656. *
  30657. * @type {string}
  30658. */
  30659. this.name = name;
  30660. /**
  30661. * The keyframe times.
  30662. *
  30663. * @type {Float32Array}
  30664. */
  30665. this.times = convertArray( times, this.TimeBufferType );
  30666. /**
  30667. * The keyframe values.
  30668. *
  30669. * @type {Float32Array}
  30670. */
  30671. this.values = convertArray( values, this.ValueBufferType );
  30672. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30673. }
  30674. /**
  30675. * Converts the keyframe track to JSON.
  30676. *
  30677. * @static
  30678. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30679. * @return {Object} The serialized keyframe track as JSON.
  30680. */
  30681. static toJSON( track ) {
  30682. const trackType = track.constructor;
  30683. let json;
  30684. // derived classes can define a static toJSON method
  30685. if ( trackType.toJSON !== this.toJSON ) {
  30686. json = trackType.toJSON( track );
  30687. } else {
  30688. // by default, we assume the data can be serialized as-is
  30689. json = {
  30690. 'name': track.name,
  30691. 'times': convertArray( track.times, Array ),
  30692. 'values': convertArray( track.values, Array )
  30693. };
  30694. const interpolation = track.getInterpolation();
  30695. if ( interpolation !== track.DefaultInterpolation ) {
  30696. json.interpolation = interpolation;
  30697. }
  30698. }
  30699. json.type = track.ValueTypeName; // mandatory
  30700. return json;
  30701. }
  30702. /**
  30703. * Factory method for creating a new discrete interpolant.
  30704. *
  30705. * @static
  30706. * @param {TypedArray} [result] - The result buffer.
  30707. * @return {DiscreteInterpolant} The new interpolant.
  30708. */
  30709. InterpolantFactoryMethodDiscrete( result ) {
  30710. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30711. }
  30712. /**
  30713. * Factory method for creating a new linear interpolant.
  30714. *
  30715. * @static
  30716. * @param {TypedArray} [result] - The result buffer.
  30717. * @return {LinearInterpolant} The new interpolant.
  30718. */
  30719. InterpolantFactoryMethodLinear( result ) {
  30720. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30721. }
  30722. /**
  30723. * Factory method for creating a new smooth interpolant.
  30724. *
  30725. * @static
  30726. * @param {TypedArray} [result] - The result buffer.
  30727. * @return {CubicInterpolant} The new interpolant.
  30728. */
  30729. InterpolantFactoryMethodSmooth( result ) {
  30730. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30731. }
  30732. /**
  30733. * Defines the interpolation factor method for this keyframe track.
  30734. *
  30735. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30736. * @return {KeyframeTrack} A reference to this keyframe track.
  30737. */
  30738. setInterpolation( interpolation ) {
  30739. let factoryMethod;
  30740. switch ( interpolation ) {
  30741. case InterpolateDiscrete:
  30742. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30743. break;
  30744. case InterpolateLinear:
  30745. factoryMethod = this.InterpolantFactoryMethodLinear;
  30746. break;
  30747. case InterpolateSmooth:
  30748. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30749. break;
  30750. }
  30751. if ( factoryMethod === undefined ) {
  30752. const message = 'unsupported interpolation for ' +
  30753. this.ValueTypeName + ' keyframe track named ' + this.name;
  30754. if ( this.createInterpolant === undefined ) {
  30755. // fall back to default, unless the default itself is messed up
  30756. if ( interpolation !== this.DefaultInterpolation ) {
  30757. this.setInterpolation( this.DefaultInterpolation );
  30758. } else {
  30759. throw new Error( message ); // fatal, in this case
  30760. }
  30761. }
  30762. console.warn( 'THREE.KeyframeTrack:', message );
  30763. return this;
  30764. }
  30765. this.createInterpolant = factoryMethod;
  30766. return this;
  30767. }
  30768. /**
  30769. * Returns the current interpolation type.
  30770. *
  30771. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30772. */
  30773. getInterpolation() {
  30774. switch ( this.createInterpolant ) {
  30775. case this.InterpolantFactoryMethodDiscrete:
  30776. return InterpolateDiscrete;
  30777. case this.InterpolantFactoryMethodLinear:
  30778. return InterpolateLinear;
  30779. case this.InterpolantFactoryMethodSmooth:
  30780. return InterpolateSmooth;
  30781. }
  30782. }
  30783. /**
  30784. * Returns the value size.
  30785. *
  30786. * @return {number} The value size.
  30787. */
  30788. getValueSize() {
  30789. return this.values.length / this.times.length;
  30790. }
  30791. /**
  30792. * Moves all keyframes either forward or backward in time.
  30793. *
  30794. * @param {number} timeOffset - The offset to move the time values.
  30795. * @return {KeyframeTrack} A reference to this keyframe track.
  30796. */
  30797. shift( timeOffset ) {
  30798. if ( timeOffset !== 0.0 ) {
  30799. const times = this.times;
  30800. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30801. times[ i ] += timeOffset;
  30802. }
  30803. }
  30804. return this;
  30805. }
  30806. /**
  30807. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30808. *
  30809. * @param {number} timeScale - The time scale.
  30810. * @return {KeyframeTrack} A reference to this keyframe track.
  30811. */
  30812. scale( timeScale ) {
  30813. if ( timeScale !== 1.0 ) {
  30814. const times = this.times;
  30815. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30816. times[ i ] *= timeScale;
  30817. }
  30818. }
  30819. return this;
  30820. }
  30821. /**
  30822. * Removes keyframes before and after animation without changing any values within the defined time range.
  30823. *
  30824. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30825. * keys this will change their values
  30826. *
  30827. * @param {number} startTime - The start time.
  30828. * @param {number} endTime - The end time.
  30829. * @return {KeyframeTrack} A reference to this keyframe track.
  30830. */
  30831. trim( startTime, endTime ) {
  30832. const times = this.times,
  30833. nKeys = times.length;
  30834. let from = 0,
  30835. to = nKeys - 1;
  30836. while ( from !== nKeys && times[ from ] < startTime ) {
  30837. ++ from;
  30838. }
  30839. while ( to !== -1 && times[ to ] > endTime ) {
  30840. -- to;
  30841. }
  30842. ++ to; // inclusive -> exclusive bound
  30843. if ( from !== 0 || to !== nKeys ) {
  30844. // empty tracks are forbidden, so keep at least one keyframe
  30845. if ( from >= to ) {
  30846. to = Math.max( to, 1 );
  30847. from = to - 1;
  30848. }
  30849. const stride = this.getValueSize();
  30850. this.times = times.slice( from, to );
  30851. this.values = this.values.slice( from * stride, to * stride );
  30852. }
  30853. return this;
  30854. }
  30855. /**
  30856. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30857. * are valid.
  30858. *
  30859. * @return {boolean} Whether the keyframes are valid or not.
  30860. */
  30861. validate() {
  30862. let valid = true;
  30863. const valueSize = this.getValueSize();
  30864. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30865. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30866. valid = false;
  30867. }
  30868. const times = this.times,
  30869. values = this.values,
  30870. nKeys = times.length;
  30871. if ( nKeys === 0 ) {
  30872. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30873. valid = false;
  30874. }
  30875. let prevTime = null;
  30876. for ( let i = 0; i !== nKeys; i ++ ) {
  30877. const currTime = times[ i ];
  30878. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30879. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30880. valid = false;
  30881. break;
  30882. }
  30883. if ( prevTime !== null && prevTime > currTime ) {
  30884. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30885. valid = false;
  30886. break;
  30887. }
  30888. prevTime = currTime;
  30889. }
  30890. if ( values !== undefined ) {
  30891. if ( isTypedArray( values ) ) {
  30892. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30893. const value = values[ i ];
  30894. if ( isNaN( value ) ) {
  30895. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30896. valid = false;
  30897. break;
  30898. }
  30899. }
  30900. }
  30901. }
  30902. return valid;
  30903. }
  30904. /**
  30905. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30906. * common in morph target sequences).
  30907. *
  30908. * @return {AnimationClip} A reference to this animation clip.
  30909. */
  30910. optimize() {
  30911. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30912. // times or values may be shared with other tracks, so overwriting is unsafe
  30913. const times = this.times.slice(),
  30914. values = this.values.slice(),
  30915. stride = this.getValueSize(),
  30916. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30917. lastIndex = times.length - 1;
  30918. let writeIndex = 1;
  30919. for ( let i = 1; i < lastIndex; ++ i ) {
  30920. let keep = false;
  30921. const time = times[ i ];
  30922. const timeNext = times[ i + 1 ];
  30923. // remove adjacent keyframes scheduled at the same time
  30924. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30925. if ( ! smoothInterpolation ) {
  30926. // remove unnecessary keyframes same as their neighbors
  30927. const offset = i * stride,
  30928. offsetP = offset - stride,
  30929. offsetN = offset + stride;
  30930. for ( let j = 0; j !== stride; ++ j ) {
  30931. const value = values[ offset + j ];
  30932. if ( value !== values[ offsetP + j ] ||
  30933. value !== values[ offsetN + j ] ) {
  30934. keep = true;
  30935. break;
  30936. }
  30937. }
  30938. } else {
  30939. keep = true;
  30940. }
  30941. }
  30942. // in-place compaction
  30943. if ( keep ) {
  30944. if ( i !== writeIndex ) {
  30945. times[ writeIndex ] = times[ i ];
  30946. const readOffset = i * stride,
  30947. writeOffset = writeIndex * stride;
  30948. for ( let j = 0; j !== stride; ++ j ) {
  30949. values[ writeOffset + j ] = values[ readOffset + j ];
  30950. }
  30951. }
  30952. ++ writeIndex;
  30953. }
  30954. }
  30955. // flush last keyframe (compaction looks ahead)
  30956. if ( lastIndex > 0 ) {
  30957. times[ writeIndex ] = times[ lastIndex ];
  30958. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30959. values[ writeOffset + j ] = values[ readOffset + j ];
  30960. }
  30961. ++ writeIndex;
  30962. }
  30963. if ( writeIndex !== times.length ) {
  30964. this.times = times.slice( 0, writeIndex );
  30965. this.values = values.slice( 0, writeIndex * stride );
  30966. } else {
  30967. this.times = times;
  30968. this.values = values;
  30969. }
  30970. return this;
  30971. }
  30972. /**
  30973. * Returns a new keyframe track with copied values from this instance.
  30974. *
  30975. * @return {KeyframeTrack} A clone of this instance.
  30976. */
  30977. clone() {
  30978. const times = this.times.slice();
  30979. const values = this.values.slice();
  30980. const TypedKeyframeTrack = this.constructor;
  30981. const track = new TypedKeyframeTrack( this.name, times, values );
  30982. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30983. track.createInterpolant = this.createInterpolant;
  30984. return track;
  30985. }
  30986. }
  30987. /**
  30988. * The value type name.
  30989. *
  30990. * @type {String}
  30991. * @default ''
  30992. */
  30993. KeyframeTrack.prototype.ValueTypeName = '';
  30994. /**
  30995. * The time buffer type of this keyframe track.
  30996. *
  30997. * @type {TypedArray|Array}
  30998. * @default Float32Array.constructor
  30999. */
  31000. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31001. /**
  31002. * The value buffer type of this keyframe track.
  31003. *
  31004. * @type {TypedArray|Array}
  31005. * @default Float32Array.constructor
  31006. */
  31007. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31008. /**
  31009. * The default interpolation type of this keyframe track.
  31010. *
  31011. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31012. * @default InterpolateLinear
  31013. */
  31014. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31015. /**
  31016. * A track for boolean keyframe values.
  31017. *
  31018. * @augments KeyframeTrack
  31019. */
  31020. class BooleanKeyframeTrack extends KeyframeTrack {
  31021. /**
  31022. * Constructs a new boolean keyframe track.
  31023. *
  31024. * This keyframe track type has no `interpolation` parameter because the
  31025. * interpolation is always discrete.
  31026. *
  31027. * @param {string} name - The keyframe track's name.
  31028. * @param {Array<number>} times - A list of keyframe times.
  31029. * @param {Array<boolean>} values - A list of keyframe values.
  31030. */
  31031. constructor( name, times, values ) {
  31032. super( name, times, values );
  31033. }
  31034. }
  31035. /**
  31036. * The value type name.
  31037. *
  31038. * @type {String}
  31039. * @default 'bool'
  31040. */
  31041. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31042. /**
  31043. * The value buffer type of this keyframe track.
  31044. *
  31045. * @type {TypedArray|Array}
  31046. * @default Array.constructor
  31047. */
  31048. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31049. /**
  31050. * The default interpolation type of this keyframe track.
  31051. *
  31052. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31053. * @default InterpolateDiscrete
  31054. */
  31055. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31056. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31057. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31058. /**
  31059. * A track for color keyframe values.
  31060. *
  31061. * @augments KeyframeTrack
  31062. */
  31063. class ColorKeyframeTrack extends KeyframeTrack {
  31064. /**
  31065. * Constructs a new color keyframe track.
  31066. *
  31067. * @param {string} name - The keyframe track's name.
  31068. * @param {Array<number>} times - A list of keyframe times.
  31069. * @param {Array<number>} values - A list of keyframe values.
  31070. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31071. */
  31072. constructor( name, times, values, interpolation ) {
  31073. super( name, times, values, interpolation );
  31074. }
  31075. }
  31076. /**
  31077. * The value type name.
  31078. *
  31079. * @type {String}
  31080. * @default 'color'
  31081. */
  31082. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31083. /**
  31084. * A track for numeric keyframe values.
  31085. *
  31086. * @augments KeyframeTrack
  31087. */
  31088. class NumberKeyframeTrack extends KeyframeTrack {
  31089. /**
  31090. * Constructs a new number keyframe track.
  31091. *
  31092. * @param {string} name - The keyframe track's name.
  31093. * @param {Array<number>} times - A list of keyframe times.
  31094. * @param {Array<number>} values - A list of keyframe values.
  31095. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31096. */
  31097. constructor( name, times, values, interpolation ) {
  31098. super( name, times, values, interpolation );
  31099. }
  31100. }
  31101. /**
  31102. * The value type name.
  31103. *
  31104. * @type {String}
  31105. * @default 'number'
  31106. */
  31107. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31108. /**
  31109. * Spherical linear unit quaternion interpolant.
  31110. *
  31111. * @augments Interpolant
  31112. */
  31113. class QuaternionLinearInterpolant extends Interpolant {
  31114. /**
  31115. * Constructs a new SLERP interpolant.
  31116. *
  31117. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31118. * @param {TypedArray} sampleValues - The sample values.
  31119. * @param {number} sampleSize - The sample size
  31120. * @param {TypedArray} [resultBuffer] - The result buffer.
  31121. */
  31122. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31123. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31124. }
  31125. interpolate_( i1, t0, t, t1 ) {
  31126. const result = this.resultBuffer,
  31127. values = this.sampleValues,
  31128. stride = this.valueSize,
  31129. alpha = ( t - t0 ) / ( t1 - t0 );
  31130. let offset = i1 * stride;
  31131. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31132. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31133. }
  31134. return result;
  31135. }
  31136. }
  31137. /**
  31138. * A track for Quaternion keyframe values.
  31139. *
  31140. * @augments KeyframeTrack
  31141. */
  31142. class QuaternionKeyframeTrack extends KeyframeTrack {
  31143. /**
  31144. * Constructs a new Quaternion keyframe track.
  31145. *
  31146. * @param {string} name - The keyframe track's name.
  31147. * @param {Array<number>} times - A list of keyframe times.
  31148. * @param {Array<number>} values - A list of keyframe values.
  31149. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31150. */
  31151. constructor( name, times, values, interpolation ) {
  31152. super( name, times, values, interpolation );
  31153. }
  31154. /**
  31155. * Overwritten so the method returns Quaternion based interpolant.
  31156. *
  31157. * @static
  31158. * @param {TypedArray} [result] - The result buffer.
  31159. * @return {QuaternionLinearInterpolant} The new interpolant.
  31160. */
  31161. InterpolantFactoryMethodLinear( result ) {
  31162. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31163. }
  31164. }
  31165. /**
  31166. * The value type name.
  31167. *
  31168. * @type {String}
  31169. * @default 'quaternion'
  31170. */
  31171. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31172. // ValueBufferType is inherited
  31173. // DefaultInterpolation is inherited;
  31174. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31175. /**
  31176. * A track for string keyframe values.
  31177. *
  31178. * @augments KeyframeTrack
  31179. */
  31180. class StringKeyframeTrack extends KeyframeTrack {
  31181. /**
  31182. * Constructs a new string keyframe track.
  31183. *
  31184. * This keyframe track type has no `interpolation` parameter because the
  31185. * interpolation is always discrete.
  31186. *
  31187. * @param {string} name - The keyframe track's name.
  31188. * @param {Array<number>} times - A list of keyframe times.
  31189. * @param {Array<string>} values - A list of keyframe values.
  31190. */
  31191. constructor( name, times, values ) {
  31192. super( name, times, values );
  31193. }
  31194. }
  31195. /**
  31196. * The value type name.
  31197. *
  31198. * @type {String}
  31199. * @default 'string'
  31200. */
  31201. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31202. /**
  31203. * The value buffer type of this keyframe track.
  31204. *
  31205. * @type {TypedArray|Array}
  31206. * @default Array.constructor
  31207. */
  31208. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31209. /**
  31210. * The default interpolation type of this keyframe track.
  31211. *
  31212. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31213. * @default InterpolateDiscrete
  31214. */
  31215. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31216. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31217. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31218. /**
  31219. * A track for vector keyframe values.
  31220. *
  31221. * @augments KeyframeTrack
  31222. */
  31223. class VectorKeyframeTrack extends KeyframeTrack {
  31224. /**
  31225. * Constructs a new vector keyframe track.
  31226. *
  31227. * @param {string} name - The keyframe track's name.
  31228. * @param {Array<number>} times - A list of keyframe times.
  31229. * @param {Array<number>} values - A list of keyframe values.
  31230. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31231. */
  31232. constructor( name, times, values, interpolation ) {
  31233. super( name, times, values, interpolation );
  31234. }
  31235. }
  31236. /**
  31237. * The value type name.
  31238. *
  31239. * @type {String}
  31240. * @default 'vector'
  31241. */
  31242. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31243. /**
  31244. * A reusable set of keyframe tracks which represent an animation.
  31245. */
  31246. class AnimationClip {
  31247. /**
  31248. * Constructs a new animation clip.
  31249. *
  31250. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31251. * use the static interface of this class for creating clips. In most cases though, animation clips
  31252. * will automatically be created by loaders when importing animated 3D assets.
  31253. *
  31254. * @param {string} [name=''] - The clip's name.
  31255. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31256. * the duration will be calculated from the passed keyframes.
  31257. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31258. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31259. * is blended/combined when two or more animations are simultaneously played.
  31260. */
  31261. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31262. /**
  31263. * The clip's name.
  31264. *
  31265. * @type {string}
  31266. */
  31267. this.name = name;
  31268. /**
  31269. * An array of keyframe tracks.
  31270. *
  31271. * @type {Array<KeyframeTrack>}
  31272. */
  31273. this.tracks = tracks;
  31274. /**
  31275. * The clip's duration in seconds.
  31276. *
  31277. * @type {number}
  31278. */
  31279. this.duration = duration;
  31280. /**
  31281. * Defines how the animation is blended/combined when two or more animations
  31282. * are simultaneously played.
  31283. *
  31284. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31285. */
  31286. this.blendMode = blendMode;
  31287. /**
  31288. * The UUID of the animation clip.
  31289. *
  31290. * @type {string}
  31291. * @readonly
  31292. */
  31293. this.uuid = generateUUID();
  31294. // this means it should figure out its duration by scanning the tracks
  31295. if ( this.duration < 0 ) {
  31296. this.resetDuration();
  31297. }
  31298. }
  31299. /**
  31300. * Factory method for creating an animation clip from the given JSON.
  31301. *
  31302. * @static
  31303. * @param {Object} json - The serialized animation clip.
  31304. * @return {AnimationClip} The new animation clip.
  31305. */
  31306. static parse( json ) {
  31307. const tracks = [],
  31308. jsonTracks = json.tracks,
  31309. frameTime = 1.0 / ( json.fps || 1.0 );
  31310. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31311. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31312. }
  31313. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31314. clip.uuid = json.uuid;
  31315. return clip;
  31316. }
  31317. /**
  31318. * Serializes the given animation clip into JSON.
  31319. *
  31320. * @static
  31321. * @param {AnimationClip} clip - The animation clip to serialize.
  31322. * @return {Object} The JSON object.
  31323. */
  31324. static toJSON( clip ) {
  31325. const tracks = [],
  31326. clipTracks = clip.tracks;
  31327. const json = {
  31328. 'name': clip.name,
  31329. 'duration': clip.duration,
  31330. 'tracks': tracks,
  31331. 'uuid': clip.uuid,
  31332. 'blendMode': clip.blendMode
  31333. };
  31334. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31335. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31336. }
  31337. return json;
  31338. }
  31339. /**
  31340. * Returns a new animation clip from the passed morph targets array of a
  31341. * geometry, taking a name and the number of frames per second.
  31342. *
  31343. * Note: The fps parameter is required, but the animation speed can be
  31344. * overridden via {@link AnimationAction#setDuration}.
  31345. *
  31346. * @static
  31347. * @param {string} name - The name of the animation clip.
  31348. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31349. * @param {number} fps - The Frames-Per-Second value.
  31350. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31351. * @return {AnimationClip} The new animation clip.
  31352. */
  31353. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31354. const numMorphTargets = morphTargetSequence.length;
  31355. const tracks = [];
  31356. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31357. let times = [];
  31358. let values = [];
  31359. times.push(
  31360. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31361. i,
  31362. ( i + 1 ) % numMorphTargets );
  31363. values.push( 0, 1, 0 );
  31364. const order = getKeyframeOrder( times );
  31365. times = sortedArray( times, 1, order );
  31366. values = sortedArray( values, 1, order );
  31367. // if there is a key at the first frame, duplicate it as the
  31368. // last frame as well for perfect loop.
  31369. if ( ! noLoop && times[ 0 ] === 0 ) {
  31370. times.push( numMorphTargets );
  31371. values.push( values[ 0 ] );
  31372. }
  31373. tracks.push(
  31374. new NumberKeyframeTrack(
  31375. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31376. times, values
  31377. ).scale( 1.0 / fps ) );
  31378. }
  31379. return new this( name, -1, tracks );
  31380. }
  31381. /**
  31382. * Searches for an animation clip by name, taking as its first parameter
  31383. * either an array of clips, or a mesh or geometry that contains an
  31384. * array named "animations" property.
  31385. *
  31386. * @static
  31387. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31388. * @param {string} name - The name to search for.
  31389. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31390. */
  31391. static findByName( objectOrClipArray, name ) {
  31392. let clipArray = objectOrClipArray;
  31393. if ( ! Array.isArray( objectOrClipArray ) ) {
  31394. const o = objectOrClipArray;
  31395. clipArray = o.geometry && o.geometry.animations || o.animations;
  31396. }
  31397. for ( let i = 0; i < clipArray.length; i ++ ) {
  31398. if ( clipArray[ i ].name === name ) {
  31399. return clipArray[ i ];
  31400. }
  31401. }
  31402. return null;
  31403. }
  31404. /**
  31405. * Returns an array of new AnimationClips created from the morph target
  31406. * sequences of a geometry, trying to sort morph target names into
  31407. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31408. *
  31409. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31410. *
  31411. * @static
  31412. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31413. * @param {number} fps - The Frames-Per-Second value.
  31414. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31415. * @return {Array<AnimationClip>} An array of new animation clips.
  31416. */
  31417. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31418. const animationToMorphTargets = {};
  31419. // tested with https://regex101.com/ on trick sequences
  31420. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31421. const pattern = /^([\w-]*?)([\d]+)$/;
  31422. // sort morph target names into animation groups based
  31423. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31424. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31425. const morphTarget = morphTargets[ i ];
  31426. const parts = morphTarget.name.match( pattern );
  31427. if ( parts && parts.length > 1 ) {
  31428. const name = parts[ 1 ];
  31429. let animationMorphTargets = animationToMorphTargets[ name ];
  31430. if ( ! animationMorphTargets ) {
  31431. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31432. }
  31433. animationMorphTargets.push( morphTarget );
  31434. }
  31435. }
  31436. const clips = [];
  31437. for ( const name in animationToMorphTargets ) {
  31438. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31439. }
  31440. return clips;
  31441. }
  31442. /**
  31443. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31444. *
  31445. * @static
  31446. * @deprecated since r175.
  31447. * @param {Object} animation - A serialized animation clip as JSON.
  31448. * @param {Array<Bones>} bones - An array of bones.
  31449. * @return {?AnimationClip} The new animation clip.
  31450. */
  31451. static parseAnimation( animation, bones ) {
  31452. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31453. if ( ! animation ) {
  31454. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31455. return null;
  31456. }
  31457. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31458. // only return track if there are actually keys.
  31459. if ( animationKeys.length !== 0 ) {
  31460. const times = [];
  31461. const values = [];
  31462. flattenJSON( animationKeys, times, values, propertyName );
  31463. // empty keys are filtered out, so check again
  31464. if ( times.length !== 0 ) {
  31465. destTracks.push( new trackType( trackName, times, values ) );
  31466. }
  31467. }
  31468. };
  31469. const tracks = [];
  31470. const clipName = animation.name || 'default';
  31471. const fps = animation.fps || 30;
  31472. const blendMode = animation.blendMode;
  31473. // automatic length determination in AnimationClip.
  31474. let duration = animation.length || -1;
  31475. const hierarchyTracks = animation.hierarchy || [];
  31476. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31477. const animationKeys = hierarchyTracks[ h ].keys;
  31478. // skip empty tracks
  31479. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31480. // process morph targets
  31481. if ( animationKeys[ 0 ].morphTargets ) {
  31482. // figure out all morph targets used in this track
  31483. const morphTargetNames = {};
  31484. let k;
  31485. for ( k = 0; k < animationKeys.length; k ++ ) {
  31486. if ( animationKeys[ k ].morphTargets ) {
  31487. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31488. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31489. }
  31490. }
  31491. }
  31492. // create a track for each morph target with all zero
  31493. // morphTargetInfluences except for the keys in which
  31494. // the morphTarget is named.
  31495. for ( const morphTargetName in morphTargetNames ) {
  31496. const times = [];
  31497. const values = [];
  31498. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31499. const animationKey = animationKeys[ k ];
  31500. times.push( animationKey.time );
  31501. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31502. }
  31503. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31504. }
  31505. duration = morphTargetNames.length * fps;
  31506. } else {
  31507. // ...assume skeletal animation
  31508. const boneName = '.bones[' + bones[ h ].name + ']';
  31509. addNonemptyTrack(
  31510. VectorKeyframeTrack, boneName + '.position',
  31511. animationKeys, 'pos', tracks );
  31512. addNonemptyTrack(
  31513. QuaternionKeyframeTrack, boneName + '.quaternion',
  31514. animationKeys, 'rot', tracks );
  31515. addNonemptyTrack(
  31516. VectorKeyframeTrack, boneName + '.scale',
  31517. animationKeys, 'scl', tracks );
  31518. }
  31519. }
  31520. if ( tracks.length === 0 ) {
  31521. return null;
  31522. }
  31523. const clip = new this( clipName, duration, tracks, blendMode );
  31524. return clip;
  31525. }
  31526. /**
  31527. * Sets the duration of this clip to the duration of its longest keyframe track.
  31528. *
  31529. * @return {AnimationClip} A reference to this animation clip.
  31530. */
  31531. resetDuration() {
  31532. const tracks = this.tracks;
  31533. let duration = 0;
  31534. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31535. const track = this.tracks[ i ];
  31536. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31537. }
  31538. this.duration = duration;
  31539. return this;
  31540. }
  31541. /**
  31542. * Trims all tracks to the clip's duration.
  31543. *
  31544. * @return {AnimationClip} A reference to this animation clip.
  31545. */
  31546. trim() {
  31547. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31548. this.tracks[ i ].trim( 0, this.duration );
  31549. }
  31550. return this;
  31551. }
  31552. /**
  31553. * Performs minimal validation on each track in the clip. Returns `true` if all
  31554. * tracks are valid.
  31555. *
  31556. * @return {boolean} Whether the clip's keyframes are valid or not.
  31557. */
  31558. validate() {
  31559. let valid = true;
  31560. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31561. valid = valid && this.tracks[ i ].validate();
  31562. }
  31563. return valid;
  31564. }
  31565. /**
  31566. * Optimizes each track by removing equivalent sequential keys (which are
  31567. * common in morph target sequences).
  31568. *
  31569. * @return {AnimationClip} A reference to this animation clip.
  31570. */
  31571. optimize() {
  31572. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31573. this.tracks[ i ].optimize();
  31574. }
  31575. return this;
  31576. }
  31577. /**
  31578. * Returns a new animation clip with copied values from this instance.
  31579. *
  31580. * @return {AnimationClip} A clone of this instance.
  31581. */
  31582. clone() {
  31583. const tracks = [];
  31584. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31585. tracks.push( this.tracks[ i ].clone() );
  31586. }
  31587. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31588. }
  31589. /**
  31590. * Serializes this animation clip into JSON.
  31591. *
  31592. * @return {Object} The JSON object.
  31593. */
  31594. toJSON() {
  31595. return this.constructor.toJSON( this );
  31596. }
  31597. }
  31598. function getTrackTypeForValueTypeName( typeName ) {
  31599. switch ( typeName.toLowerCase() ) {
  31600. case 'scalar':
  31601. case 'double':
  31602. case 'float':
  31603. case 'number':
  31604. case 'integer':
  31605. return NumberKeyframeTrack;
  31606. case 'vector':
  31607. case 'vector2':
  31608. case 'vector3':
  31609. case 'vector4':
  31610. return VectorKeyframeTrack;
  31611. case 'color':
  31612. return ColorKeyframeTrack;
  31613. case 'quaternion':
  31614. return QuaternionKeyframeTrack;
  31615. case 'bool':
  31616. case 'boolean':
  31617. return BooleanKeyframeTrack;
  31618. case 'string':
  31619. return StringKeyframeTrack;
  31620. }
  31621. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31622. }
  31623. function parseKeyframeTrack( json ) {
  31624. if ( json.type === undefined ) {
  31625. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31626. }
  31627. const trackType = getTrackTypeForValueTypeName( json.type );
  31628. if ( json.times === undefined ) {
  31629. const times = [], values = [];
  31630. flattenJSON( json.keys, times, values, 'value' );
  31631. json.times = times;
  31632. json.values = values;
  31633. }
  31634. // derived classes can define a static parse method
  31635. if ( trackType.parse !== undefined ) {
  31636. return trackType.parse( json );
  31637. } else {
  31638. // by default, we assume a constructor compatible with the base
  31639. return new trackType( json.name, json.times, json.values, json.interpolation );
  31640. }
  31641. }
  31642. /**
  31643. * @class
  31644. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31645. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31646. * @hideconstructor
  31647. */
  31648. const Cache = {
  31649. /**
  31650. * Whether caching is enabled or not.
  31651. *
  31652. * @static
  31653. * @type {boolean}
  31654. * @default false
  31655. */
  31656. enabled: false,
  31657. /**
  31658. * A dictionary that holds cached files.
  31659. *
  31660. * @static
  31661. * @type {Object<string,Object>}
  31662. */
  31663. files: {},
  31664. /**
  31665. * Adds a cache entry with a key to reference the file. If this key already
  31666. * holds a file, it is overwritten.
  31667. *
  31668. * @static
  31669. * @param {string} key - The key to reference the cached file.
  31670. * @param {Object} file - The file to be cached.
  31671. */
  31672. add: function ( key, file ) {
  31673. if ( this.enabled === false ) return;
  31674. // console.log( 'THREE.Cache', 'Adding key:', key );
  31675. this.files[ key ] = file;
  31676. },
  31677. /**
  31678. * Gets the cached value for the given key.
  31679. *
  31680. * @static
  31681. * @param {string} key - The key to reference the cached file.
  31682. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31683. */
  31684. get: function ( key ) {
  31685. if ( this.enabled === false ) return;
  31686. // console.log( 'THREE.Cache', 'Checking key:', key );
  31687. return this.files[ key ];
  31688. },
  31689. /**
  31690. * Removes the cached file associated with the given key.
  31691. *
  31692. * @static
  31693. * @param {string} key - The key to reference the cached file.
  31694. */
  31695. remove: function ( key ) {
  31696. delete this.files[ key ];
  31697. },
  31698. /**
  31699. * Remove all values from the cache.
  31700. *
  31701. * @static
  31702. */
  31703. clear: function () {
  31704. this.files = {};
  31705. }
  31706. };
  31707. /**
  31708. * Handles and keeps track of loaded and pending data. A default global
  31709. * instance of this class is created and used by loaders if not supplied
  31710. * manually.
  31711. *
  31712. * In general that should be sufficient, however there are times when it can
  31713. * be useful to have separate loaders - for example if you want to show
  31714. * separate loading bars for objects and textures.
  31715. *
  31716. * ```js
  31717. * const manager = new THREE.LoadingManager();
  31718. * manager.onLoad = () => console.log( 'Loading complete!' );
  31719. *
  31720. * const loader1 = new OBJLoader( manager );
  31721. * const loader2 = new ColladaLoader( manager );
  31722. * ```
  31723. */
  31724. class LoadingManager {
  31725. /**
  31726. * Constructs a new loading manager.
  31727. *
  31728. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31729. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31730. * @param {Function} [onError] - Executes when an error occurs.
  31731. */
  31732. constructor( onLoad, onProgress, onError ) {
  31733. const scope = this;
  31734. let isLoading = false;
  31735. let itemsLoaded = 0;
  31736. let itemsTotal = 0;
  31737. let urlModifier = undefined;
  31738. const handlers = [];
  31739. // Refer to #5689 for the reason why we don't set .onStart
  31740. // in the constructor
  31741. /**
  31742. * Executes when an item starts loading.
  31743. *
  31744. * @type {Function|undefined}
  31745. * @default undefined
  31746. */
  31747. this.onStart = undefined;
  31748. /**
  31749. * Executes when all items have been loaded.
  31750. *
  31751. * @type {Function|undefined}
  31752. * @default undefined
  31753. */
  31754. this.onLoad = onLoad;
  31755. /**
  31756. * Executes when single items have been loaded.
  31757. *
  31758. * @type {Function|undefined}
  31759. * @default undefined
  31760. */
  31761. this.onProgress = onProgress;
  31762. /**
  31763. * Executes when an error occurs.
  31764. *
  31765. * @type {Function|undefined}
  31766. * @default undefined
  31767. */
  31768. this.onError = onError;
  31769. /**
  31770. * Used for aborting ongoing requests in loaders using this manager.
  31771. *
  31772. * @type {AbortController}
  31773. */
  31774. this.abortController = new AbortController();
  31775. /**
  31776. * This should be called by any loader using the manager when the loader
  31777. * starts loading an item.
  31778. *
  31779. * @param {string} url - The URL to load.
  31780. */
  31781. this.itemStart = function ( url ) {
  31782. itemsTotal ++;
  31783. if ( isLoading === false ) {
  31784. if ( scope.onStart !== undefined ) {
  31785. scope.onStart( url, itemsLoaded, itemsTotal );
  31786. }
  31787. }
  31788. isLoading = true;
  31789. };
  31790. /**
  31791. * This should be called by any loader using the manager when the loader
  31792. * ended loading an item.
  31793. *
  31794. * @param {string} url - The URL of the loaded item.
  31795. */
  31796. this.itemEnd = function ( url ) {
  31797. itemsLoaded ++;
  31798. if ( scope.onProgress !== undefined ) {
  31799. scope.onProgress( url, itemsLoaded, itemsTotal );
  31800. }
  31801. if ( itemsLoaded === itemsTotal ) {
  31802. isLoading = false;
  31803. if ( scope.onLoad !== undefined ) {
  31804. scope.onLoad();
  31805. }
  31806. }
  31807. };
  31808. /**
  31809. * This should be called by any loader using the manager when the loader
  31810. * encounters an error when loading an item.
  31811. *
  31812. * @param {string} url - The URL of the item that produces an error.
  31813. */
  31814. this.itemError = function ( url ) {
  31815. if ( scope.onError !== undefined ) {
  31816. scope.onError( url );
  31817. }
  31818. };
  31819. /**
  31820. * Given a URL, uses the URL modifier callback (if any) and returns a
  31821. * resolved URL. If no URL modifier is set, returns the original URL.
  31822. *
  31823. * @param {string} url - The URL to load.
  31824. * @return {string} The resolved URL.
  31825. */
  31826. this.resolveURL = function ( url ) {
  31827. if ( urlModifier ) {
  31828. return urlModifier( url );
  31829. }
  31830. return url;
  31831. };
  31832. /**
  31833. * If provided, the callback will be passed each resource URL before a
  31834. * request is sent. The callback may return the original URL, or a new URL to
  31835. * override loading behavior. This behavior can be used to load assets from
  31836. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31837. *
  31838. * ```js
  31839. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31840. *
  31841. * const manager = new THREE.LoadingManager();
  31842. *
  31843. * // Initialize loading manager with URL callback.
  31844. * const objectURLs = [];
  31845. * manager.setURLModifier( ( url ) => {
  31846. *
  31847. * url = URL.createObjectURL( blobs[ url ] );
  31848. * objectURLs.push( url );
  31849. * return url;
  31850. *
  31851. * } );
  31852. *
  31853. * // Load as usual, then revoke the blob URLs.
  31854. * const loader = new GLTFLoader( manager );
  31855. * loader.load( 'fish.gltf', (gltf) => {
  31856. *
  31857. * scene.add( gltf.scene );
  31858. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31859. *
  31860. * } );
  31861. * ```
  31862. *
  31863. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31864. * @return {LoadingManager} A reference to this loading manager.
  31865. */
  31866. this.setURLModifier = function ( transform ) {
  31867. urlModifier = transform;
  31868. return this;
  31869. };
  31870. /**
  31871. * Registers a loader with the given regular expression. Can be used to
  31872. * define what loader should be used in order to load specific files. A
  31873. * typical use case is to overwrite the default loader for textures.
  31874. *
  31875. * ```js
  31876. * // add handler for TGA textures
  31877. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31878. * ```
  31879. *
  31880. * @param {string} regex - A regular expression.
  31881. * @param {Loader} loader - A loader that should handle matched cases.
  31882. * @return {LoadingManager} A reference to this loading manager.
  31883. */
  31884. this.addHandler = function ( regex, loader ) {
  31885. handlers.push( regex, loader );
  31886. return this;
  31887. };
  31888. /**
  31889. * Removes the loader for the given regular expression.
  31890. *
  31891. * @param {string} regex - A regular expression.
  31892. * @return {LoadingManager} A reference to this loading manager.
  31893. */
  31894. this.removeHandler = function ( regex ) {
  31895. const index = handlers.indexOf( regex );
  31896. if ( index !== -1 ) {
  31897. handlers.splice( index, 2 );
  31898. }
  31899. return this;
  31900. };
  31901. /**
  31902. * Can be used to retrieve the registered loader for the given file path.
  31903. *
  31904. * @param {string} file - The file path.
  31905. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31906. */
  31907. this.getHandler = function ( file ) {
  31908. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31909. const regex = handlers[ i ];
  31910. const loader = handlers[ i + 1 ];
  31911. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31912. if ( regex.test( file ) ) {
  31913. return loader;
  31914. }
  31915. }
  31916. return null;
  31917. };
  31918. /**
  31919. * Can be used to abort ongoing loading requests in loaders using this manager.
  31920. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31921. * is supported in the browser.
  31922. *
  31923. * @return {LoadingManager} A reference to this loading manager.
  31924. */
  31925. this.abort = function () {
  31926. this.abortController.abort();
  31927. this.abortController = new AbortController();
  31928. return this;
  31929. };
  31930. }
  31931. }
  31932. /**
  31933. * The global default loading manager.
  31934. *
  31935. * @constant
  31936. * @type {LoadingManager}
  31937. */
  31938. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31939. /**
  31940. * Abstract base class for loaders.
  31941. *
  31942. * @abstract
  31943. */
  31944. class Loader {
  31945. /**
  31946. * Constructs a new loader.
  31947. *
  31948. * @param {LoadingManager} [manager] - The loading manager.
  31949. */
  31950. constructor( manager ) {
  31951. /**
  31952. * The loading manager.
  31953. *
  31954. * @type {LoadingManager}
  31955. * @default DefaultLoadingManager
  31956. */
  31957. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31958. /**
  31959. * The crossOrigin string to implement CORS for loading the url from a
  31960. * different domain that allows CORS.
  31961. *
  31962. * @type {string}
  31963. * @default 'anonymous'
  31964. */
  31965. this.crossOrigin = 'anonymous';
  31966. /**
  31967. * Whether the XMLHttpRequest uses credentials.
  31968. *
  31969. * @type {boolean}
  31970. * @default false
  31971. */
  31972. this.withCredentials = false;
  31973. /**
  31974. * The base path from which the asset will be loaded.
  31975. *
  31976. * @type {string}
  31977. */
  31978. this.path = '';
  31979. /**
  31980. * The base path from which additional resources like textures will be loaded.
  31981. *
  31982. * @type {string}
  31983. */
  31984. this.resourcePath = '';
  31985. /**
  31986. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31987. * used in HTTP request.
  31988. *
  31989. * @type {Object<string, any>}
  31990. */
  31991. this.requestHeader = {};
  31992. }
  31993. /**
  31994. * This method needs to be implemented by all concrete loaders. It holds the
  31995. * logic for loading assets from the backend.
  31996. *
  31997. * @abstract
  31998. * @param {string} url - The path/URL of the file to be loaded.
  31999. * @param {Function} onLoad - Executed when the loading process has been finished.
  32000. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32001. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32002. */
  32003. load( /* url, onLoad, onProgress, onError */ ) {}
  32004. /**
  32005. * A async version of {@link Loader#load}.
  32006. *
  32007. * @param {string} url - The path/URL of the file to be loaded.
  32008. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32009. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32010. */
  32011. loadAsync( url, onProgress ) {
  32012. const scope = this;
  32013. return new Promise( function ( resolve, reject ) {
  32014. scope.load( url, resolve, onProgress, reject );
  32015. } );
  32016. }
  32017. /**
  32018. * This method needs to be implemented by all concrete loaders. It holds the
  32019. * logic for parsing the asset into three.js entities.
  32020. *
  32021. * @abstract
  32022. * @param {any} data - The data to parse.
  32023. */
  32024. parse( /* data */ ) {}
  32025. /**
  32026. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32027. * from a different domain that allows CORS.
  32028. *
  32029. * @param {string} crossOrigin - The `crossOrigin` value.
  32030. * @return {Loader} A reference to this instance.
  32031. */
  32032. setCrossOrigin( crossOrigin ) {
  32033. this.crossOrigin = crossOrigin;
  32034. return this;
  32035. }
  32036. /**
  32037. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32038. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32039. *
  32040. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32041. *
  32042. * @param {boolean} value - The `withCredentials` value.
  32043. * @return {Loader} A reference to this instance.
  32044. */
  32045. setWithCredentials( value ) {
  32046. this.withCredentials = value;
  32047. return this;
  32048. }
  32049. /**
  32050. * Sets the base path for the asset.
  32051. *
  32052. * @param {string} path - The base path.
  32053. * @return {Loader} A reference to this instance.
  32054. */
  32055. setPath( path ) {
  32056. this.path = path;
  32057. return this;
  32058. }
  32059. /**
  32060. * Sets the base path for dependent resources like textures.
  32061. *
  32062. * @param {string} resourcePath - The resource path.
  32063. * @return {Loader} A reference to this instance.
  32064. */
  32065. setResourcePath( resourcePath ) {
  32066. this.resourcePath = resourcePath;
  32067. return this;
  32068. }
  32069. /**
  32070. * Sets the given request header.
  32071. *
  32072. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32073. * for configuring the HTTP request.
  32074. * @return {Loader} A reference to this instance.
  32075. */
  32076. setRequestHeader( requestHeader ) {
  32077. this.requestHeader = requestHeader;
  32078. return this;
  32079. }
  32080. /**
  32081. * This method can be implemented in loaders for aborting ongoing requests.
  32082. *
  32083. * @abstract
  32084. * @return {Loader} A reference to this instance.
  32085. */
  32086. abort() {
  32087. return this;
  32088. }
  32089. }
  32090. /**
  32091. * Callback for onProgress in loaders.
  32092. *
  32093. * @callback onProgressCallback
  32094. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32095. */
  32096. /**
  32097. * Callback for onError in loaders.
  32098. *
  32099. * @callback onErrorCallback
  32100. * @param {Error} error - The error which occurred during the loading process.
  32101. */
  32102. /**
  32103. * The default material name that is used by loaders
  32104. * when creating materials for loaded 3D objects.
  32105. *
  32106. * Note: Not all loaders might honor this setting.
  32107. *
  32108. * @static
  32109. * @type {string}
  32110. * @default '__DEFAULT'
  32111. */
  32112. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32113. const loading = {};
  32114. class HttpError extends Error {
  32115. constructor( message, response ) {
  32116. super( message );
  32117. this.response = response;
  32118. }
  32119. }
  32120. /**
  32121. * A low level class for loading resources with the Fetch API, used internally by
  32122. * most loaders. It can also be used directly to load any file type that does
  32123. * not have a loader.
  32124. *
  32125. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32126. * once to your application.
  32127. *
  32128. * ```js
  32129. * const loader = new THREE.FileLoader();
  32130. * const data = await loader.loadAsync( 'example.txt' );
  32131. * ```
  32132. *
  32133. * @augments Loader
  32134. */
  32135. class FileLoader extends Loader {
  32136. /**
  32137. * Constructs a new file loader.
  32138. *
  32139. * @param {LoadingManager} [manager] - The loading manager.
  32140. */
  32141. constructor( manager ) {
  32142. super( manager );
  32143. /**
  32144. * The expected mime type. Valid values can be found
  32145. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32146. *
  32147. * @type {string}
  32148. */
  32149. this.mimeType = '';
  32150. /**
  32151. * The expected response type.
  32152. *
  32153. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32154. * @default ''
  32155. */
  32156. this.responseType = '';
  32157. /**
  32158. * Used for aborting requests.
  32159. *
  32160. * @private
  32161. * @type {AbortController}
  32162. */
  32163. this._abortController = new AbortController();
  32164. }
  32165. /**
  32166. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32167. *
  32168. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32169. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32170. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32171. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32172. * @return {any|undefined} The cached resource if available.
  32173. */
  32174. load( url, onLoad, onProgress, onError ) {
  32175. if ( url === undefined ) url = '';
  32176. if ( this.path !== undefined ) url = this.path + url;
  32177. url = this.manager.resolveURL( url );
  32178. const cached = Cache.get( `file:${url}` );
  32179. if ( cached !== undefined ) {
  32180. this.manager.itemStart( url );
  32181. setTimeout( () => {
  32182. if ( onLoad ) onLoad( cached );
  32183. this.manager.itemEnd( url );
  32184. }, 0 );
  32185. return cached;
  32186. }
  32187. // Check if request is duplicate
  32188. if ( loading[ url ] !== undefined ) {
  32189. loading[ url ].push( {
  32190. onLoad: onLoad,
  32191. onProgress: onProgress,
  32192. onError: onError
  32193. } );
  32194. return;
  32195. }
  32196. // Initialise array for duplicate requests
  32197. loading[ url ] = [];
  32198. loading[ url ].push( {
  32199. onLoad: onLoad,
  32200. onProgress: onProgress,
  32201. onError: onError,
  32202. } );
  32203. // create request
  32204. const req = new Request( url, {
  32205. headers: new Headers( this.requestHeader ),
  32206. credentials: this.withCredentials ? 'include' : 'same-origin',
  32207. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32208. } );
  32209. // record states ( avoid data race )
  32210. const mimeType = this.mimeType;
  32211. const responseType = this.responseType;
  32212. // start the fetch
  32213. fetch( req )
  32214. .then( response => {
  32215. if ( response.status === 200 || response.status === 0 ) {
  32216. // Some browsers return HTTP Status 0 when using non-http protocol
  32217. // e.g. 'file://' or 'data://'. Handle as success.
  32218. if ( response.status === 0 ) {
  32219. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32220. }
  32221. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32222. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32223. return response;
  32224. }
  32225. const callbacks = loading[ url ];
  32226. const reader = response.body.getReader();
  32227. // Nginx needs X-File-Size check
  32228. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32229. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32230. const total = contentLength ? parseInt( contentLength ) : 0;
  32231. const lengthComputable = total !== 0;
  32232. let loaded = 0;
  32233. // periodically read data into the new stream tracking while download progress
  32234. const stream = new ReadableStream( {
  32235. start( controller ) {
  32236. readData();
  32237. function readData() {
  32238. reader.read().then( ( { done, value } ) => {
  32239. if ( done ) {
  32240. controller.close();
  32241. } else {
  32242. loaded += value.byteLength;
  32243. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32244. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32245. const callback = callbacks[ i ];
  32246. if ( callback.onProgress ) callback.onProgress( event );
  32247. }
  32248. controller.enqueue( value );
  32249. readData();
  32250. }
  32251. }, ( e ) => {
  32252. controller.error( e );
  32253. } );
  32254. }
  32255. }
  32256. } );
  32257. return new Response( stream );
  32258. } else {
  32259. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32260. }
  32261. } )
  32262. .then( response => {
  32263. switch ( responseType ) {
  32264. case 'arraybuffer':
  32265. return response.arrayBuffer();
  32266. case 'blob':
  32267. return response.blob();
  32268. case 'document':
  32269. return response.text()
  32270. .then( text => {
  32271. const parser = new DOMParser();
  32272. return parser.parseFromString( text, mimeType );
  32273. } );
  32274. case 'json':
  32275. return response.json();
  32276. default:
  32277. if ( mimeType === '' ) {
  32278. return response.text();
  32279. } else {
  32280. // sniff encoding
  32281. const re = /charset="?([^;"\s]*)"?/i;
  32282. const exec = re.exec( mimeType );
  32283. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32284. const decoder = new TextDecoder( label );
  32285. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32286. }
  32287. }
  32288. } )
  32289. .then( data => {
  32290. // Add to cache only on HTTP success, so that we do not cache
  32291. // error response bodies as proper responses to requests.
  32292. Cache.add( `file:${url}`, data );
  32293. const callbacks = loading[ url ];
  32294. delete loading[ url ];
  32295. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32296. const callback = callbacks[ i ];
  32297. if ( callback.onLoad ) callback.onLoad( data );
  32298. }
  32299. } )
  32300. .catch( err => {
  32301. // Abort errors and other errors are handled the same
  32302. const callbacks = loading[ url ];
  32303. if ( callbacks === undefined ) {
  32304. // When onLoad was called and url was deleted in `loading`
  32305. this.manager.itemError( url );
  32306. throw err;
  32307. }
  32308. delete loading[ url ];
  32309. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32310. const callback = callbacks[ i ];
  32311. if ( callback.onError ) callback.onError( err );
  32312. }
  32313. this.manager.itemError( url );
  32314. } )
  32315. .finally( () => {
  32316. this.manager.itemEnd( url );
  32317. } );
  32318. this.manager.itemStart( url );
  32319. }
  32320. /**
  32321. * Sets the expected response type.
  32322. *
  32323. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32324. * @return {FileLoader} A reference to this file loader.
  32325. */
  32326. setResponseType( value ) {
  32327. this.responseType = value;
  32328. return this;
  32329. }
  32330. /**
  32331. * Sets the expected mime type of the loaded file.
  32332. *
  32333. * @param {string} value - The mime type.
  32334. * @return {FileLoader} A reference to this file loader.
  32335. */
  32336. setMimeType( value ) {
  32337. this.mimeType = value;
  32338. return this;
  32339. }
  32340. /**
  32341. * Aborts ongoing fetch requests.
  32342. *
  32343. * @return {FileLoader} A reference to this instance.
  32344. */
  32345. abort() {
  32346. this._abortController.abort();
  32347. this._abortController = new AbortController();
  32348. return this;
  32349. }
  32350. }
  32351. /**
  32352. * Class for loading animation clips in the JSON format. The files are internally
  32353. * loaded via {@link FileLoader}.
  32354. *
  32355. * ```js
  32356. * const loader = new THREE.AnimationLoader();
  32357. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32358. * ```
  32359. *
  32360. * @augments Loader
  32361. */
  32362. class AnimationLoader extends Loader {
  32363. /**
  32364. * Constructs a new animation loader.
  32365. *
  32366. * @param {LoadingManager} [manager] - The loading manager.
  32367. */
  32368. constructor( manager ) {
  32369. super( manager );
  32370. }
  32371. /**
  32372. * Starts loading from the given URL and pass the loaded animations as an array
  32373. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32374. *
  32375. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32376. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32377. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32378. * @param {onErrorCallback} onError - Executed when errors occur.
  32379. */
  32380. load( url, onLoad, onProgress, onError ) {
  32381. const scope = this;
  32382. const loader = new FileLoader( this.manager );
  32383. loader.setPath( this.path );
  32384. loader.setRequestHeader( this.requestHeader );
  32385. loader.setWithCredentials( this.withCredentials );
  32386. loader.load( url, function ( text ) {
  32387. try {
  32388. onLoad( scope.parse( JSON.parse( text ) ) );
  32389. } catch ( e ) {
  32390. if ( onError ) {
  32391. onError( e );
  32392. } else {
  32393. console.error( e );
  32394. }
  32395. scope.manager.itemError( url );
  32396. }
  32397. }, onProgress, onError );
  32398. }
  32399. /**
  32400. * Parses the given JSON object and returns an array of animation clips.
  32401. *
  32402. * @param {Object} json - The serialized animation clips.
  32403. * @return {Array<AnimationClip>} The parsed animation clips.
  32404. */
  32405. parse( json ) {
  32406. const animations = [];
  32407. for ( let i = 0; i < json.length; i ++ ) {
  32408. const clip = AnimationClip.parse( json[ i ] );
  32409. animations.push( clip );
  32410. }
  32411. return animations;
  32412. }
  32413. }
  32414. /**
  32415. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32416. * Textures are internally loaded via {@link FileLoader}.
  32417. *
  32418. * Derived classes have to implement the `parse()` method which holds the parsing
  32419. * for the respective format.
  32420. *
  32421. * @abstract
  32422. * @augments Loader
  32423. */
  32424. class CompressedTextureLoader extends Loader {
  32425. /**
  32426. * Constructs a new compressed texture loader.
  32427. *
  32428. * @param {LoadingManager} [manager] - The loading manager.
  32429. */
  32430. constructor( manager ) {
  32431. super( manager );
  32432. }
  32433. /**
  32434. * Starts loading from the given URL and passes the loaded compressed texture
  32435. * to the `onLoad()` callback. The method also returns a new texture object which can
  32436. * directly be used for material creation. If you do it this way, the texture
  32437. * may pop up in your scene once the respective loading process is finished.
  32438. *
  32439. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32440. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32441. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32442. * @param {onErrorCallback} onError - Executed when errors occur.
  32443. * @return {CompressedTexture} The compressed texture.
  32444. */
  32445. load( url, onLoad, onProgress, onError ) {
  32446. const scope = this;
  32447. const images = [];
  32448. const texture = new CompressedTexture();
  32449. const loader = new FileLoader( this.manager );
  32450. loader.setPath( this.path );
  32451. loader.setResponseType( 'arraybuffer' );
  32452. loader.setRequestHeader( this.requestHeader );
  32453. loader.setWithCredentials( scope.withCredentials );
  32454. let loaded = 0;
  32455. function loadTexture( i ) {
  32456. loader.load( url[ i ], function ( buffer ) {
  32457. const texDatas = scope.parse( buffer, true );
  32458. images[ i ] = {
  32459. width: texDatas.width,
  32460. height: texDatas.height,
  32461. format: texDatas.format,
  32462. mipmaps: texDatas.mipmaps
  32463. };
  32464. loaded += 1;
  32465. if ( loaded === 6 ) {
  32466. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32467. texture.image = images;
  32468. texture.format = texDatas.format;
  32469. texture.needsUpdate = true;
  32470. if ( onLoad ) onLoad( texture );
  32471. }
  32472. }, onProgress, onError );
  32473. }
  32474. if ( Array.isArray( url ) ) {
  32475. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32476. loadTexture( i );
  32477. }
  32478. } else {
  32479. // compressed cubemap texture stored in a single DDS file
  32480. loader.load( url, function ( buffer ) {
  32481. const texDatas = scope.parse( buffer, true );
  32482. if ( texDatas.isCubemap ) {
  32483. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32484. for ( let f = 0; f < faces; f ++ ) {
  32485. images[ f ] = { mipmaps: [] };
  32486. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32487. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32488. images[ f ].format = texDatas.format;
  32489. images[ f ].width = texDatas.width;
  32490. images[ f ].height = texDatas.height;
  32491. }
  32492. }
  32493. texture.image = images;
  32494. } else {
  32495. texture.image.width = texDatas.width;
  32496. texture.image.height = texDatas.height;
  32497. texture.mipmaps = texDatas.mipmaps;
  32498. }
  32499. if ( texDatas.mipmapCount === 1 ) {
  32500. texture.minFilter = LinearFilter;
  32501. }
  32502. texture.format = texDatas.format;
  32503. texture.needsUpdate = true;
  32504. if ( onLoad ) onLoad( texture );
  32505. }, onProgress, onError );
  32506. }
  32507. return texture;
  32508. }
  32509. }
  32510. const _loading = new WeakMap();
  32511. /**
  32512. * A loader for loading images. The class loads images with the HTML `Image` API.
  32513. *
  32514. * ```js
  32515. * const loader = new THREE.ImageLoader();
  32516. * const image = await loader.loadAsync( 'image.png' );
  32517. * ```
  32518. * Please note that `ImageLoader` has dropped support for progress
  32519. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32520. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32521. *
  32522. * @augments Loader
  32523. */
  32524. class ImageLoader extends Loader {
  32525. /**
  32526. * Constructs a new image loader.
  32527. *
  32528. * @param {LoadingManager} [manager] - The loading manager.
  32529. */
  32530. constructor( manager ) {
  32531. super( manager );
  32532. }
  32533. /**
  32534. * Starts loading from the given URL and passes the loaded image
  32535. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32536. * directly be used for texture creation. If you do it this way, the texture
  32537. * may pop up in your scene once the respective loading process is finished.
  32538. *
  32539. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32540. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32541. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32542. * @param {onErrorCallback} onError - Executed when errors occur.
  32543. * @return {Image} The image.
  32544. */
  32545. load( url, onLoad, onProgress, onError ) {
  32546. if ( this.path !== undefined ) url = this.path + url;
  32547. url = this.manager.resolveURL( url );
  32548. const scope = this;
  32549. const cached = Cache.get( `image:${url}` );
  32550. if ( cached !== undefined ) {
  32551. if ( cached.complete === true ) {
  32552. scope.manager.itemStart( url );
  32553. setTimeout( function () {
  32554. if ( onLoad ) onLoad( cached );
  32555. scope.manager.itemEnd( url );
  32556. }, 0 );
  32557. } else {
  32558. let arr = _loading.get( cached );
  32559. if ( arr === undefined ) {
  32560. arr = [];
  32561. _loading.set( cached, arr );
  32562. }
  32563. arr.push( { onLoad, onError } );
  32564. }
  32565. return cached;
  32566. }
  32567. const image = createElementNS( 'img' );
  32568. function onImageLoad() {
  32569. removeEventListeners();
  32570. if ( onLoad ) onLoad( this );
  32571. //
  32572. const callbacks = _loading.get( this ) || [];
  32573. for ( let i = 0; i < callbacks.length; i ++ ) {
  32574. const callback = callbacks[ i ];
  32575. if ( callback.onLoad ) callback.onLoad( this );
  32576. }
  32577. _loading.delete( this );
  32578. scope.manager.itemEnd( url );
  32579. }
  32580. function onImageError( event ) {
  32581. removeEventListeners();
  32582. if ( onError ) onError( event );
  32583. Cache.remove( `image:${url}` );
  32584. //
  32585. const callbacks = _loading.get( this ) || [];
  32586. for ( let i = 0; i < callbacks.length; i ++ ) {
  32587. const callback = callbacks[ i ];
  32588. if ( callback.onError ) callback.onError( event );
  32589. }
  32590. _loading.delete( this );
  32591. scope.manager.itemError( url );
  32592. scope.manager.itemEnd( url );
  32593. }
  32594. function removeEventListeners() {
  32595. image.removeEventListener( 'load', onImageLoad, false );
  32596. image.removeEventListener( 'error', onImageError, false );
  32597. }
  32598. image.addEventListener( 'load', onImageLoad, false );
  32599. image.addEventListener( 'error', onImageError, false );
  32600. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32601. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32602. }
  32603. Cache.add( `image:${url}`, image );
  32604. scope.manager.itemStart( url );
  32605. image.src = url;
  32606. return image;
  32607. }
  32608. }
  32609. /**
  32610. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32611. *
  32612. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32613. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32614. * like vertical and horizontal cross, column and row layouts are not supported.
  32615. *
  32616. * Note that, by convention, cube maps are specified in a coordinate system
  32617. * in which positive-x is to the right when looking up the positive-z axis --
  32618. * in other words, using a left-handed coordinate system. Since three.js uses
  32619. * a right-handed coordinate system, environment maps used in three.js will
  32620. * have pos-x and neg-x swapped.
  32621. *
  32622. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32623. * is set to `SRGBColorSpace` by default.
  32624. *
  32625. * ```js
  32626. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32627. * const cubeTexture = await loader.loadAsync( [
  32628. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32629. * ] );
  32630. * scene.background = cubeTexture;
  32631. * ```
  32632. *
  32633. * @augments Loader
  32634. */
  32635. class CubeTextureLoader extends Loader {
  32636. /**
  32637. * Constructs a new cube texture loader.
  32638. *
  32639. * @param {LoadingManager} [manager] - The loading manager.
  32640. */
  32641. constructor( manager ) {
  32642. super( manager );
  32643. }
  32644. /**
  32645. * Starts loading from the given URL and pass the fully loaded cube texture
  32646. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32647. * directly be used for material creation. If you do it this way, the cube texture
  32648. * may pop up in your scene once the respective loading process is finished.
  32649. *
  32650. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32651. * cube texture. The urls should be specified in the following order: pos-x,
  32652. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32653. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32654. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32655. * @param {onErrorCallback} onError - Executed when errors occur.
  32656. * @return {CubeTexture} The cube texture.
  32657. */
  32658. load( urls, onLoad, onProgress, onError ) {
  32659. const texture = new CubeTexture();
  32660. texture.colorSpace = SRGBColorSpace;
  32661. const loader = new ImageLoader( this.manager );
  32662. loader.setCrossOrigin( this.crossOrigin );
  32663. loader.setPath( this.path );
  32664. let loaded = 0;
  32665. function loadTexture( i ) {
  32666. loader.load( urls[ i ], function ( image ) {
  32667. texture.images[ i ] = image;
  32668. loaded ++;
  32669. if ( loaded === 6 ) {
  32670. texture.needsUpdate = true;
  32671. if ( onLoad ) onLoad( texture );
  32672. }
  32673. }, undefined, onError );
  32674. }
  32675. for ( let i = 0; i < urls.length; ++ i ) {
  32676. loadTexture( i );
  32677. }
  32678. return texture;
  32679. }
  32680. }
  32681. /**
  32682. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32683. * Textures are internally loaded via {@link FileLoader}.
  32684. *
  32685. * Derived classes have to implement the `parse()` method which holds the parsing
  32686. * for the respective format.
  32687. *
  32688. * @abstract
  32689. * @augments Loader
  32690. */
  32691. class DataTextureLoader extends Loader {
  32692. /**
  32693. * Constructs a new data texture loader.
  32694. *
  32695. * @param {LoadingManager} [manager] - The loading manager.
  32696. */
  32697. constructor( manager ) {
  32698. super( manager );
  32699. }
  32700. /**
  32701. * Starts loading from the given URL and passes the loaded data texture
  32702. * to the `onLoad()` callback. The method also returns a new texture object which can
  32703. * directly be used for material creation. If you do it this way, the texture
  32704. * may pop up in your scene once the respective loading process is finished.
  32705. *
  32706. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32707. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32708. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32709. * @param {onErrorCallback} onError - Executed when errors occur.
  32710. * @return {DataTexture} The data texture.
  32711. */
  32712. load( url, onLoad, onProgress, onError ) {
  32713. const scope = this;
  32714. const texture = new DataTexture();
  32715. const loader = new FileLoader( this.manager );
  32716. loader.setResponseType( 'arraybuffer' );
  32717. loader.setRequestHeader( this.requestHeader );
  32718. loader.setPath( this.path );
  32719. loader.setWithCredentials( scope.withCredentials );
  32720. loader.load( url, function ( buffer ) {
  32721. let texData;
  32722. try {
  32723. texData = scope.parse( buffer );
  32724. } catch ( error ) {
  32725. if ( onError !== undefined ) {
  32726. onError( error );
  32727. } else {
  32728. console.error( error );
  32729. return;
  32730. }
  32731. }
  32732. if ( texData.image !== undefined ) {
  32733. texture.image = texData.image;
  32734. } else if ( texData.data !== undefined ) {
  32735. texture.image.width = texData.width;
  32736. texture.image.height = texData.height;
  32737. texture.image.data = texData.data;
  32738. }
  32739. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32740. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32741. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32742. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32743. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32744. if ( texData.colorSpace !== undefined ) {
  32745. texture.colorSpace = texData.colorSpace;
  32746. }
  32747. if ( texData.flipY !== undefined ) {
  32748. texture.flipY = texData.flipY;
  32749. }
  32750. if ( texData.format !== undefined ) {
  32751. texture.format = texData.format;
  32752. }
  32753. if ( texData.type !== undefined ) {
  32754. texture.type = texData.type;
  32755. }
  32756. if ( texData.mipmaps !== undefined ) {
  32757. texture.mipmaps = texData.mipmaps;
  32758. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32759. }
  32760. if ( texData.mipmapCount === 1 ) {
  32761. texture.minFilter = LinearFilter;
  32762. }
  32763. if ( texData.generateMipmaps !== undefined ) {
  32764. texture.generateMipmaps = texData.generateMipmaps;
  32765. }
  32766. texture.needsUpdate = true;
  32767. if ( onLoad ) onLoad( texture, texData );
  32768. }, onProgress, onError );
  32769. return texture;
  32770. }
  32771. }
  32772. /**
  32773. * Class for loading textures. Images are internally
  32774. * loaded via {@link ImageLoader}.
  32775. *
  32776. * ```js
  32777. * const loader = new THREE.TextureLoader();
  32778. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32779. *
  32780. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32781. * ```
  32782. * Please note that `TextureLoader` has dropped support for progress
  32783. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32784. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32785. *
  32786. * @augments Loader
  32787. */
  32788. class TextureLoader extends Loader {
  32789. /**
  32790. * Constructs a new texture loader.
  32791. *
  32792. * @param {LoadingManager} [manager] - The loading manager.
  32793. */
  32794. constructor( manager ) {
  32795. super( manager );
  32796. }
  32797. /**
  32798. * Starts loading from the given URL and pass the fully loaded texture
  32799. * to the `onLoad()` callback. The method also returns a new texture object which can
  32800. * directly be used for material creation. If you do it this way, the texture
  32801. * may pop up in your scene once the respective loading process is finished.
  32802. *
  32803. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32804. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32805. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32806. * @param {onErrorCallback} onError - Executed when errors occur.
  32807. * @return {Texture} The texture.
  32808. */
  32809. load( url, onLoad, onProgress, onError ) {
  32810. const texture = new Texture();
  32811. const loader = new ImageLoader( this.manager );
  32812. loader.setCrossOrigin( this.crossOrigin );
  32813. loader.setPath( this.path );
  32814. loader.load( url, function ( image ) {
  32815. texture.image = image;
  32816. texture.needsUpdate = true;
  32817. if ( onLoad !== undefined ) {
  32818. onLoad( texture );
  32819. }
  32820. }, onProgress, onError );
  32821. return texture;
  32822. }
  32823. }
  32824. /**
  32825. * Abstract base class for lights - all other light types inherit the
  32826. * properties and methods described here.
  32827. *
  32828. * @abstract
  32829. * @augments Object3D
  32830. */
  32831. class Light extends Object3D {
  32832. /**
  32833. * Constructs a new light.
  32834. *
  32835. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32836. * @param {number} [intensity=1] - The light's strength/intensity.
  32837. */
  32838. constructor( color, intensity = 1 ) {
  32839. super();
  32840. /**
  32841. * This flag can be used for type testing.
  32842. *
  32843. * @type {boolean}
  32844. * @readonly
  32845. * @default true
  32846. */
  32847. this.isLight = true;
  32848. this.type = 'Light';
  32849. /**
  32850. * The light's color.
  32851. *
  32852. * @type {Color}
  32853. */
  32854. this.color = new Color( color );
  32855. /**
  32856. * The light's intensity.
  32857. *
  32858. * @type {number}
  32859. * @default 1
  32860. */
  32861. this.intensity = intensity;
  32862. }
  32863. /**
  32864. * Frees the GPU-related resources allocated by this instance. Call this
  32865. * method whenever this instance is no longer used in your app.
  32866. */
  32867. dispose() {
  32868. // Empty here in base class; some subclasses override.
  32869. }
  32870. copy( source, recursive ) {
  32871. super.copy( source, recursive );
  32872. this.color.copy( source.color );
  32873. this.intensity = source.intensity;
  32874. return this;
  32875. }
  32876. toJSON( meta ) {
  32877. const data = super.toJSON( meta );
  32878. data.object.color = this.color.getHex();
  32879. data.object.intensity = this.intensity;
  32880. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32881. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32882. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32883. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32884. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32885. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32886. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32887. return data;
  32888. }
  32889. }
  32890. /**
  32891. * A light source positioned directly above the scene, with color fading from
  32892. * the sky color to the ground color.
  32893. *
  32894. * This light cannot be used to cast shadows.
  32895. *
  32896. * ```js
  32897. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32898. * scene.add( light );
  32899. * ```
  32900. *
  32901. * @augments Light
  32902. */
  32903. class HemisphereLight extends Light {
  32904. /**
  32905. * Constructs a new hemisphere light.
  32906. *
  32907. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32908. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32909. * @param {number} [intensity=1] - The light's strength/intensity.
  32910. */
  32911. constructor( skyColor, groundColor, intensity ) {
  32912. super( skyColor, intensity );
  32913. /**
  32914. * This flag can be used for type testing.
  32915. *
  32916. * @type {boolean}
  32917. * @readonly
  32918. * @default true
  32919. */
  32920. this.isHemisphereLight = true;
  32921. this.type = 'HemisphereLight';
  32922. this.position.copy( Object3D.DEFAULT_UP );
  32923. this.updateMatrix();
  32924. /**
  32925. * The light's ground color.
  32926. *
  32927. * @type {Color}
  32928. */
  32929. this.groundColor = new Color( groundColor );
  32930. }
  32931. copy( source, recursive ) {
  32932. super.copy( source, recursive );
  32933. this.groundColor.copy( source.groundColor );
  32934. return this;
  32935. }
  32936. }
  32937. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32938. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32939. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32940. /**
  32941. * Abstract base class for light shadow classes. These classes
  32942. * represent the shadow configuration for different light types.
  32943. *
  32944. * @abstract
  32945. */
  32946. class LightShadow {
  32947. /**
  32948. * Constructs a new light shadow.
  32949. *
  32950. * @param {Camera} camera - The light's view of the world.
  32951. */
  32952. constructor( camera ) {
  32953. /**
  32954. * The light's view of the world.
  32955. *
  32956. * @type {Camera}
  32957. */
  32958. this.camera = camera;
  32959. /**
  32960. * The intensity of the shadow. The default is `1`.
  32961. * Valid values are in the range `[0, 1]`.
  32962. *
  32963. * @type {number}
  32964. * @default 1
  32965. */
  32966. this.intensity = 1;
  32967. /**
  32968. * Shadow map bias, how much to add or subtract from the normalized depth
  32969. * when deciding whether a surface is in shadow.
  32970. *
  32971. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32972. * may help reduce artifacts in shadows.
  32973. *
  32974. * @type {number}
  32975. * @default 0
  32976. */
  32977. this.bias = 0;
  32978. /**
  32979. * Defines how much the position used to query the shadow map is offset along
  32980. * the object normal. The default is `0`. Increasing this value can be used to
  32981. * reduce shadow acne especially in large scenes where light shines onto
  32982. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32983. *
  32984. * @type {number}
  32985. * @default 0
  32986. */
  32987. this.normalBias = 0;
  32988. /**
  32989. * Setting this to values greater than 1 will blur the edges of the shadow.
  32990. * High values will cause unwanted banding effects in the shadows - a greater
  32991. * map size will allow for a higher value to be used here before these effects
  32992. * become visible.
  32993. *
  32994. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32995. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32996. *
  32997. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32998. *
  32999. * @type {number}
  33000. * @default 1
  33001. */
  33002. this.radius = 1;
  33003. /**
  33004. * The amount of samples to use when blurring a VSM shadow map.
  33005. *
  33006. * @type {number}
  33007. * @default 8
  33008. */
  33009. this.blurSamples = 8;
  33010. /**
  33011. * Defines the width and height of the shadow map. Higher values give better quality
  33012. * shadows at the cost of computation time. Values must be powers of two.
  33013. *
  33014. * @type {Vector2}
  33015. * @default (512,512)
  33016. */
  33017. this.mapSize = new Vector2( 512, 512 );
  33018. /**
  33019. * The type of shadow texture. The default is `UnsignedByteType`.
  33020. *
  33021. * @type {number}
  33022. * @default UnsignedByteType
  33023. */
  33024. this.mapType = UnsignedByteType;
  33025. /**
  33026. * The depth map generated using the internal camera; a location beyond a
  33027. * pixel's depth is in shadow. Computed internally during rendering.
  33028. *
  33029. * @type {?RenderTarget}
  33030. * @default null
  33031. */
  33032. this.map = null;
  33033. /**
  33034. * The distribution map generated using the internal camera; an occlusion is
  33035. * calculated based on the distribution of depths. Computed internally during
  33036. * rendering.
  33037. *
  33038. * @type {?RenderTarget}
  33039. * @default null
  33040. */
  33041. this.mapPass = null;
  33042. /**
  33043. * Model to shadow camera space, to compute location and depth in shadow map.
  33044. * This is computed internally during rendering.
  33045. *
  33046. * @type {Matrix4}
  33047. */
  33048. this.matrix = new Matrix4();
  33049. /**
  33050. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33051. * lighting / shadows, you may set this to `false`.
  33052. *
  33053. * @type {boolean}
  33054. * @default true
  33055. */
  33056. this.autoUpdate = true;
  33057. /**
  33058. * When set to `true`, shadow maps will be updated in the next `render` call.
  33059. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33060. * set this property to `true` and then make a render call to update the light's shadow.
  33061. *
  33062. * @type {boolean}
  33063. * @default false
  33064. */
  33065. this.needsUpdate = false;
  33066. this._frustum = new Frustum();
  33067. this._frameExtents = new Vector2( 1, 1 );
  33068. this._viewportCount = 1;
  33069. this._viewports = [
  33070. new Vector4( 0, 0, 1, 1 )
  33071. ];
  33072. }
  33073. /**
  33074. * Used internally by the renderer to get the number of viewports that need
  33075. * to be rendered for this shadow.
  33076. *
  33077. * @return {number} The viewport count.
  33078. */
  33079. getViewportCount() {
  33080. return this._viewportCount;
  33081. }
  33082. /**
  33083. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33084. *
  33085. * @return {Frustum} The shadow camera frustum.
  33086. */
  33087. getFrustum() {
  33088. return this._frustum;
  33089. }
  33090. /**
  33091. * Update the matrices for the camera and shadow, used internally by the renderer.
  33092. *
  33093. * @param {Light} light - The light for which the shadow is being rendered.
  33094. */
  33095. updateMatrices( light ) {
  33096. const shadowCamera = this.camera;
  33097. const shadowMatrix = this.matrix;
  33098. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33099. shadowCamera.position.copy( _lightPositionWorld$1 );
  33100. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33101. shadowCamera.lookAt( _lookTarget$1 );
  33102. shadowCamera.updateMatrixWorld();
  33103. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33104. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33105. if ( shadowCamera.reversedDepth ) {
  33106. shadowMatrix.set(
  33107. 0.5, 0.0, 0.0, 0.5,
  33108. 0.0, 0.5, 0.0, 0.5,
  33109. 0.0, 0.0, 1.0, 0.0,
  33110. 0.0, 0.0, 0.0, 1.0
  33111. );
  33112. } else {
  33113. shadowMatrix.set(
  33114. 0.5, 0.0, 0.0, 0.5,
  33115. 0.0, 0.5, 0.0, 0.5,
  33116. 0.0, 0.0, 0.5, 0.5,
  33117. 0.0, 0.0, 0.0, 1.0
  33118. );
  33119. }
  33120. shadowMatrix.multiply( _projScreenMatrix$1 );
  33121. }
  33122. /**
  33123. * Returns a viewport definition for the given viewport index.
  33124. *
  33125. * @param {number} viewportIndex - The viewport index.
  33126. * @return {Vector4} The viewport.
  33127. */
  33128. getViewport( viewportIndex ) {
  33129. return this._viewports[ viewportIndex ];
  33130. }
  33131. /**
  33132. * Returns the frame extends.
  33133. *
  33134. * @return {Vector2} The frame extends.
  33135. */
  33136. getFrameExtents() {
  33137. return this._frameExtents;
  33138. }
  33139. /**
  33140. * Frees the GPU-related resources allocated by this instance. Call this
  33141. * method whenever this instance is no longer used in your app.
  33142. */
  33143. dispose() {
  33144. if ( this.map ) {
  33145. this.map.dispose();
  33146. }
  33147. if ( this.mapPass ) {
  33148. this.mapPass.dispose();
  33149. }
  33150. }
  33151. /**
  33152. * Copies the values of the given light shadow instance to this instance.
  33153. *
  33154. * @param {LightShadow} source - The light shadow to copy.
  33155. * @return {LightShadow} A reference to this light shadow instance.
  33156. */
  33157. copy( source ) {
  33158. this.camera = source.camera.clone();
  33159. this.intensity = source.intensity;
  33160. this.bias = source.bias;
  33161. this.radius = source.radius;
  33162. this.autoUpdate = source.autoUpdate;
  33163. this.needsUpdate = source.needsUpdate;
  33164. this.normalBias = source.normalBias;
  33165. this.blurSamples = source.blurSamples;
  33166. this.mapSize.copy( source.mapSize );
  33167. return this;
  33168. }
  33169. /**
  33170. * Returns a new light shadow instance with copied values from this instance.
  33171. *
  33172. * @return {LightShadow} A clone of this instance.
  33173. */
  33174. clone() {
  33175. return new this.constructor().copy( this );
  33176. }
  33177. /**
  33178. * Serializes the light shadow into JSON.
  33179. *
  33180. * @return {Object} A JSON object representing the serialized light shadow.
  33181. * @see {@link ObjectLoader#parse}
  33182. */
  33183. toJSON() {
  33184. const object = {};
  33185. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33186. if ( this.bias !== 0 ) object.bias = this.bias;
  33187. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33188. if ( this.radius !== 1 ) object.radius = this.radius;
  33189. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33190. object.camera = this.camera.toJSON( false ).object;
  33191. delete object.camera.matrix;
  33192. return object;
  33193. }
  33194. }
  33195. /**
  33196. * Represents the shadow configuration of directional lights.
  33197. *
  33198. * @augments LightShadow
  33199. */
  33200. class SpotLightShadow extends LightShadow {
  33201. /**
  33202. * Constructs a new spot light shadow.
  33203. */
  33204. constructor() {
  33205. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33206. /**
  33207. * This flag can be used for type testing.
  33208. *
  33209. * @type {boolean}
  33210. * @readonly
  33211. * @default true
  33212. */
  33213. this.isSpotLightShadow = true;
  33214. /**
  33215. * Used to focus the shadow camera. The camera's field of view is set as a
  33216. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33217. *
  33218. * @type {number}
  33219. * @default 1
  33220. */
  33221. this.focus = 1;
  33222. /**
  33223. * Texture aspect ratio.
  33224. *
  33225. * @type {number}
  33226. * @default 1
  33227. */
  33228. this.aspect = 1;
  33229. }
  33230. updateMatrices( light ) {
  33231. const camera = this.camera;
  33232. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33233. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33234. const far = light.distance || camera.far;
  33235. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33236. camera.fov = fov;
  33237. camera.aspect = aspect;
  33238. camera.far = far;
  33239. camera.updateProjectionMatrix();
  33240. }
  33241. super.updateMatrices( light );
  33242. }
  33243. copy( source ) {
  33244. super.copy( source );
  33245. this.focus = source.focus;
  33246. return this;
  33247. }
  33248. }
  33249. /**
  33250. * This light gets emitted from a single point in one direction, along a cone
  33251. * that increases in size the further from the light it gets.
  33252. *
  33253. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33254. *
  33255. * ```js
  33256. * // white spotlight shining from the side, modulated by a texture
  33257. * const spotLight = new THREE.SpotLight( 0xffffff );
  33258. * spotLight.position.set( 100, 1000, 100 );
  33259. * spotLight.map = new THREE.TextureLoader().load( url );
  33260. *
  33261. * spotLight.castShadow = true;
  33262. * spotLight.shadow.mapSize.width = 1024;
  33263. * spotLight.shadow.mapSize.height = 1024;
  33264. * spotLight.shadow.camera.near = 500;
  33265. * spotLight.shadow.camera.far = 4000;
  33266. * spotLight.shadow.camera.fov = 30;s
  33267. * ```
  33268. *
  33269. * @augments Light
  33270. */
  33271. class SpotLight extends Light {
  33272. /**
  33273. * Constructs a new spot light.
  33274. *
  33275. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33276. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33277. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33278. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33279. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33280. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33281. */
  33282. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33283. super( color, intensity );
  33284. /**
  33285. * This flag can be used for type testing.
  33286. *
  33287. * @type {boolean}
  33288. * @readonly
  33289. * @default true
  33290. */
  33291. this.isSpotLight = true;
  33292. this.type = 'SpotLight';
  33293. this.position.copy( Object3D.DEFAULT_UP );
  33294. this.updateMatrix();
  33295. /**
  33296. * The spot light points from its position to the
  33297. * target's position.
  33298. *
  33299. * For the target's position to be changed to anything other
  33300. * than the default, it must be added to the scene.
  33301. *
  33302. * It is also possible to set the target to be another 3D object
  33303. * in the scene. The light will now track the target object.
  33304. *
  33305. * @type {Object3D}
  33306. */
  33307. this.target = new Object3D();
  33308. /**
  33309. * Maximum range of the light. `0` means no limit.
  33310. *
  33311. * @type {number}
  33312. * @default 0
  33313. */
  33314. this.distance = distance;
  33315. /**
  33316. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33317. *
  33318. * @type {number}
  33319. * @default Math.PI/3
  33320. */
  33321. this.angle = angle;
  33322. /**
  33323. * Percent of the spotlight cone that is attenuated due to penumbra.
  33324. * Value range is `[0,1]`.
  33325. *
  33326. * @type {number}
  33327. * @default 0
  33328. */
  33329. this.penumbra = penumbra;
  33330. /**
  33331. * The amount the light dims along the distance of the light. In context of
  33332. * physically-correct rendering the default value should not be changed.
  33333. *
  33334. * @type {number}
  33335. * @default 2
  33336. */
  33337. this.decay = decay;
  33338. /**
  33339. * A texture used to modulate the color of the light. The spot light
  33340. * color is mixed with the RGB value of this texture, with a ratio
  33341. * corresponding to its alpha value. The cookie-like masking effect is
  33342. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33343. *
  33344. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33345. *
  33346. * @type {?Texture}
  33347. * @default null
  33348. */
  33349. this.map = null;
  33350. /**
  33351. * This property holds the light's shadow configuration.
  33352. *
  33353. * @type {SpotLightShadow}
  33354. */
  33355. this.shadow = new SpotLightShadow();
  33356. }
  33357. /**
  33358. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33359. * Changing the power will also change the light's intensity.
  33360. *
  33361. * @type {number}
  33362. */
  33363. get power() {
  33364. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33365. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33366. return this.intensity * Math.PI;
  33367. }
  33368. set power( power ) {
  33369. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33370. this.intensity = power / Math.PI;
  33371. }
  33372. dispose() {
  33373. this.shadow.dispose();
  33374. }
  33375. copy( source, recursive ) {
  33376. super.copy( source, recursive );
  33377. this.distance = source.distance;
  33378. this.angle = source.angle;
  33379. this.penumbra = source.penumbra;
  33380. this.decay = source.decay;
  33381. this.target = source.target.clone();
  33382. this.shadow = source.shadow.clone();
  33383. return this;
  33384. }
  33385. }
  33386. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33387. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33388. const _lookTarget = /*@__PURE__*/ new Vector3();
  33389. /**
  33390. * Represents the shadow configuration of point lights.
  33391. *
  33392. * @augments LightShadow
  33393. */
  33394. class PointLightShadow extends LightShadow {
  33395. /**
  33396. * Constructs a new point light shadow.
  33397. */
  33398. constructor() {
  33399. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33400. /**
  33401. * This flag can be used for type testing.
  33402. *
  33403. * @type {boolean}
  33404. * @readonly
  33405. * @default true
  33406. */
  33407. this.isPointLightShadow = true;
  33408. this._frameExtents = new Vector2( 4, 2 );
  33409. this._viewportCount = 6;
  33410. this._viewports = [
  33411. // These viewports map a cube-map onto a 2D texture with the
  33412. // following orientation:
  33413. //
  33414. // xzXZ
  33415. // y Y
  33416. //
  33417. // X - Positive x direction
  33418. // x - Negative x direction
  33419. // Y - Positive y direction
  33420. // y - Negative y direction
  33421. // Z - Positive z direction
  33422. // z - Negative z direction
  33423. // positive X
  33424. new Vector4( 2, 1, 1, 1 ),
  33425. // negative X
  33426. new Vector4( 0, 1, 1, 1 ),
  33427. // positive Z
  33428. new Vector4( 3, 1, 1, 1 ),
  33429. // negative Z
  33430. new Vector4( 1, 1, 1, 1 ),
  33431. // positive Y
  33432. new Vector4( 3, 0, 1, 1 ),
  33433. // negative Y
  33434. new Vector4( 1, 0, 1, 1 )
  33435. ];
  33436. this._cubeDirections = [
  33437. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33438. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33439. ];
  33440. this._cubeUps = [
  33441. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33442. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33443. ];
  33444. }
  33445. /**
  33446. * Update the matrices for the camera and shadow, used internally by the renderer.
  33447. *
  33448. * @param {Light} light - The light for which the shadow is being rendered.
  33449. * @param {number} [viewportIndex=0] - The viewport index.
  33450. */
  33451. updateMatrices( light, viewportIndex = 0 ) {
  33452. const camera = this.camera;
  33453. const shadowMatrix = this.matrix;
  33454. const far = light.distance || camera.far;
  33455. if ( far !== camera.far ) {
  33456. camera.far = far;
  33457. camera.updateProjectionMatrix();
  33458. }
  33459. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33460. camera.position.copy( _lightPositionWorld );
  33461. _lookTarget.copy( camera.position );
  33462. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33463. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33464. camera.lookAt( _lookTarget );
  33465. camera.updateMatrixWorld();
  33466. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33467. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33468. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33469. }
  33470. }
  33471. /**
  33472. * A light that gets emitted from a single point in all directions. A common
  33473. * use case for this is to replicate the light emitted from a bare
  33474. * lightbulb.
  33475. *
  33476. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33477. *
  33478. * ```js
  33479. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33480. * light.position.set( 50, 50, 50 );
  33481. * scene.add( light );
  33482. * ```
  33483. *
  33484. * @augments Light
  33485. */
  33486. class PointLight extends Light {
  33487. /**
  33488. * Constructs a new point light.
  33489. *
  33490. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33491. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33492. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33493. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33494. */
  33495. constructor( color, intensity, distance = 0, decay = 2 ) {
  33496. super( color, intensity );
  33497. /**
  33498. * This flag can be used for type testing.
  33499. *
  33500. * @type {boolean}
  33501. * @readonly
  33502. * @default true
  33503. */
  33504. this.isPointLight = true;
  33505. this.type = 'PointLight';
  33506. /**
  33507. * When distance is zero, light will attenuate according to inverse-square
  33508. * law to infinite distance. When distance is non-zero, light will attenuate
  33509. * according to inverse-square law until near the distance cutoff, where it
  33510. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33511. * physically correct.
  33512. *
  33513. * @type {number}
  33514. * @default 0
  33515. */
  33516. this.distance = distance;
  33517. /**
  33518. * The amount the light dims along the distance of the light. In context of
  33519. * physically-correct rendering the default value should not be changed.
  33520. *
  33521. * @type {number}
  33522. * @default 2
  33523. */
  33524. this.decay = decay;
  33525. /**
  33526. * This property holds the light's shadow configuration.
  33527. *
  33528. * @type {PointLightShadow}
  33529. */
  33530. this.shadow = new PointLightShadow();
  33531. }
  33532. /**
  33533. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33534. * Changing the power will also change the light's intensity.
  33535. *
  33536. * @type {number}
  33537. */
  33538. get power() {
  33539. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33540. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33541. return this.intensity * 4 * Math.PI;
  33542. }
  33543. set power( power ) {
  33544. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33545. this.intensity = power / ( 4 * Math.PI );
  33546. }
  33547. dispose() {
  33548. this.shadow.dispose();
  33549. }
  33550. copy( source, recursive ) {
  33551. super.copy( source, recursive );
  33552. this.distance = source.distance;
  33553. this.decay = source.decay;
  33554. this.shadow = source.shadow.clone();
  33555. return this;
  33556. }
  33557. }
  33558. /**
  33559. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33560. *
  33561. * In this projection mode, an object's size in the rendered image stays
  33562. * constant regardless of its distance from the camera. This can be useful
  33563. * for rendering 2D scenes and UI elements, amongst other things.
  33564. *
  33565. * ```js
  33566. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33567. * scene.add( camera );
  33568. * ```
  33569. *
  33570. * @augments Camera
  33571. */
  33572. class OrthographicCamera extends Camera {
  33573. /**
  33574. * Constructs a new orthographic camera.
  33575. *
  33576. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33577. * @param {number} [right=1] - The right plane of the camera's frustum.
  33578. * @param {number} [top=1] - The top plane of the camera's frustum.
  33579. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33580. * @param {number} [near=0.1] - The camera's near plane.
  33581. * @param {number} [far=2000] - The camera's far plane.
  33582. */
  33583. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33584. super();
  33585. /**
  33586. * This flag can be used for type testing.
  33587. *
  33588. * @type {boolean}
  33589. * @readonly
  33590. * @default true
  33591. */
  33592. this.isOrthographicCamera = true;
  33593. this.type = 'OrthographicCamera';
  33594. /**
  33595. * The zoom factor of the camera.
  33596. *
  33597. * @type {number}
  33598. * @default 1
  33599. */
  33600. this.zoom = 1;
  33601. /**
  33602. * Represents the frustum window specification. This property should not be edited
  33603. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33604. *
  33605. * @type {?Object}
  33606. * @default null
  33607. */
  33608. this.view = null;
  33609. /**
  33610. * The left plane of the camera's frustum.
  33611. *
  33612. * @type {number}
  33613. * @default -1
  33614. */
  33615. this.left = left;
  33616. /**
  33617. * The right plane of the camera's frustum.
  33618. *
  33619. * @type {number}
  33620. * @default 1
  33621. */
  33622. this.right = right;
  33623. /**
  33624. * The top plane of the camera's frustum.
  33625. *
  33626. * @type {number}
  33627. * @default 1
  33628. */
  33629. this.top = top;
  33630. /**
  33631. * The bottom plane of the camera's frustum.
  33632. *
  33633. * @type {number}
  33634. * @default -1
  33635. */
  33636. this.bottom = bottom;
  33637. /**
  33638. * The camera's near plane. The valid range is greater than `0`
  33639. * and less than the current value of {@link OrthographicCamera#far}.
  33640. *
  33641. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33642. * valid value for an orthographic camera's near plane.
  33643. *
  33644. * @type {number}
  33645. * @default 0.1
  33646. */
  33647. this.near = near;
  33648. /**
  33649. * The camera's far plane. Must be greater than the
  33650. * current value of {@link OrthographicCamera#near}.
  33651. *
  33652. * @type {number}
  33653. * @default 2000
  33654. */
  33655. this.far = far;
  33656. this.updateProjectionMatrix();
  33657. }
  33658. copy( source, recursive ) {
  33659. super.copy( source, recursive );
  33660. this.left = source.left;
  33661. this.right = source.right;
  33662. this.top = source.top;
  33663. this.bottom = source.bottom;
  33664. this.near = source.near;
  33665. this.far = source.far;
  33666. this.zoom = source.zoom;
  33667. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33668. return this;
  33669. }
  33670. /**
  33671. * Sets an offset in a larger frustum. This is useful for multi-window or
  33672. * multi-monitor/multi-machine setups.
  33673. *
  33674. * @param {number} fullWidth - The full width of multiview setup.
  33675. * @param {number} fullHeight - The full height of multiview setup.
  33676. * @param {number} x - The horizontal offset of the subcamera.
  33677. * @param {number} y - The vertical offset of the subcamera.
  33678. * @param {number} width - The width of subcamera.
  33679. * @param {number} height - The height of subcamera.
  33680. * @see {@link PerspectiveCamera#setViewOffset}
  33681. */
  33682. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33683. if ( this.view === null ) {
  33684. this.view = {
  33685. enabled: true,
  33686. fullWidth: 1,
  33687. fullHeight: 1,
  33688. offsetX: 0,
  33689. offsetY: 0,
  33690. width: 1,
  33691. height: 1
  33692. };
  33693. }
  33694. this.view.enabled = true;
  33695. this.view.fullWidth = fullWidth;
  33696. this.view.fullHeight = fullHeight;
  33697. this.view.offsetX = x;
  33698. this.view.offsetY = y;
  33699. this.view.width = width;
  33700. this.view.height = height;
  33701. this.updateProjectionMatrix();
  33702. }
  33703. /**
  33704. * Removes the view offset from the projection matrix.
  33705. */
  33706. clearViewOffset() {
  33707. if ( this.view !== null ) {
  33708. this.view.enabled = false;
  33709. }
  33710. this.updateProjectionMatrix();
  33711. }
  33712. /**
  33713. * Updates the camera's projection matrix. Must be called after any change of
  33714. * camera properties.
  33715. */
  33716. updateProjectionMatrix() {
  33717. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33718. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33719. const cx = ( this.right + this.left ) / 2;
  33720. const cy = ( this.top + this.bottom ) / 2;
  33721. let left = cx - dx;
  33722. let right = cx + dx;
  33723. let top = cy + dy;
  33724. let bottom = cy - dy;
  33725. if ( this.view !== null && this.view.enabled ) {
  33726. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33727. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33728. left += scaleW * this.view.offsetX;
  33729. right = left + scaleW * this.view.width;
  33730. top -= scaleH * this.view.offsetY;
  33731. bottom = top - scaleH * this.view.height;
  33732. }
  33733. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33734. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33735. }
  33736. toJSON( meta ) {
  33737. const data = super.toJSON( meta );
  33738. data.object.zoom = this.zoom;
  33739. data.object.left = this.left;
  33740. data.object.right = this.right;
  33741. data.object.top = this.top;
  33742. data.object.bottom = this.bottom;
  33743. data.object.near = this.near;
  33744. data.object.far = this.far;
  33745. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33746. return data;
  33747. }
  33748. }
  33749. /**
  33750. * Represents the shadow configuration of directional lights.
  33751. *
  33752. * @augments LightShadow
  33753. */
  33754. class DirectionalLightShadow extends LightShadow {
  33755. /**
  33756. * Constructs a new directional light shadow.
  33757. */
  33758. constructor() {
  33759. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33760. /**
  33761. * This flag can be used for type testing.
  33762. *
  33763. * @type {boolean}
  33764. * @readonly
  33765. * @default true
  33766. */
  33767. this.isDirectionalLightShadow = true;
  33768. }
  33769. }
  33770. /**
  33771. * A light that gets emitted in a specific direction. This light will behave
  33772. * as though it is infinitely far away and the rays produced from it are all
  33773. * parallel. The common use case for this is to simulate daylight; the sun is
  33774. * far enough away that its position can be considered to be infinite, and
  33775. * all light rays coming from it are parallel.
  33776. *
  33777. * A common point of confusion for directional lights is that setting the
  33778. * rotation has no effect. This is because three.js's DirectionalLight is the
  33779. * equivalent to what is often called a 'Target Direct Light' in other
  33780. * applications.
  33781. *
  33782. * This means that its direction is calculated as pointing from the light's
  33783. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33784. * (as opposed to a 'Free Direct Light' that just has a rotation
  33785. * component).
  33786. *
  33787. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33788. *
  33789. * ```js
  33790. * // White directional light at half intensity shining from the top.
  33791. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33792. * scene.add( directionalLight );
  33793. * ```
  33794. *
  33795. * @augments Light
  33796. */
  33797. class DirectionalLight extends Light {
  33798. /**
  33799. * Constructs a new directional light.
  33800. *
  33801. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33802. * @param {number} [intensity=1] - The light's strength/intensity.
  33803. */
  33804. constructor( color, intensity ) {
  33805. super( color, intensity );
  33806. /**
  33807. * This flag can be used for type testing.
  33808. *
  33809. * @type {boolean}
  33810. * @readonly
  33811. * @default true
  33812. */
  33813. this.isDirectionalLight = true;
  33814. this.type = 'DirectionalLight';
  33815. this.position.copy( Object3D.DEFAULT_UP );
  33816. this.updateMatrix();
  33817. /**
  33818. * The directional light points from its position to the
  33819. * target's position.
  33820. *
  33821. * For the target's position to be changed to anything other
  33822. * than the default, it must be added to the scene.
  33823. *
  33824. * It is also possible to set the target to be another 3D object
  33825. * in the scene. The light will now track the target object.
  33826. *
  33827. * @type {Object3D}
  33828. */
  33829. this.target = new Object3D();
  33830. /**
  33831. * This property holds the light's shadow configuration.
  33832. *
  33833. * @type {DirectionalLightShadow}
  33834. */
  33835. this.shadow = new DirectionalLightShadow();
  33836. }
  33837. dispose() {
  33838. this.shadow.dispose();
  33839. }
  33840. copy( source ) {
  33841. super.copy( source );
  33842. this.target = source.target.clone();
  33843. this.shadow = source.shadow.clone();
  33844. return this;
  33845. }
  33846. }
  33847. /**
  33848. * This light globally illuminates all objects in the scene equally.
  33849. *
  33850. * It cannot be used to cast shadows as it does not have a direction.
  33851. *
  33852. * ```js
  33853. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33854. * scene.add( light );
  33855. * ```
  33856. *
  33857. * @augments Light
  33858. */
  33859. class AmbientLight extends Light {
  33860. /**
  33861. * Constructs a new ambient light.
  33862. *
  33863. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33864. * @param {number} [intensity=1] - The light's strength/intensity.
  33865. */
  33866. constructor( color, intensity ) {
  33867. super( color, intensity );
  33868. /**
  33869. * This flag can be used for type testing.
  33870. *
  33871. * @type {boolean}
  33872. * @readonly
  33873. * @default true
  33874. */
  33875. this.isAmbientLight = true;
  33876. this.type = 'AmbientLight';
  33877. }
  33878. }
  33879. /**
  33880. * This class emits light uniformly across the face a rectangular plane.
  33881. * This light type can be used to simulate light sources such as bright
  33882. * windows or strip lighting.
  33883. *
  33884. * Important Notes:
  33885. *
  33886. * - There is no shadow support.
  33887. * - Only PBR materials are supported.
  33888. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33889. * into your app and init the uniforms/textures.
  33890. *
  33891. * ```js
  33892. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33893. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33894. *
  33895. * const intensity = 1; const width = 10; const height = 10;
  33896. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33897. * rectLight.position.set( 5, 5, 0 );
  33898. * rectLight.lookAt( 0, 0, 0 );
  33899. * scene.add( rectLight )
  33900. * ```
  33901. *
  33902. * @augments Light
  33903. */
  33904. class RectAreaLight extends Light {
  33905. /**
  33906. * Constructs a new area light.
  33907. *
  33908. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33909. * @param {number} [intensity=1] - The light's strength/intensity.
  33910. * @param {number} [width=10] - The width of the light.
  33911. * @param {number} [height=10] - The height of the light.
  33912. */
  33913. constructor( color, intensity, width = 10, height = 10 ) {
  33914. super( color, intensity );
  33915. /**
  33916. * This flag can be used for type testing.
  33917. *
  33918. * @type {boolean}
  33919. * @readonly
  33920. * @default true
  33921. */
  33922. this.isRectAreaLight = true;
  33923. this.type = 'RectAreaLight';
  33924. /**
  33925. * The width of the light.
  33926. *
  33927. * @type {number}
  33928. * @default 10
  33929. */
  33930. this.width = width;
  33931. /**
  33932. * The height of the light.
  33933. *
  33934. * @type {number}
  33935. * @default 10
  33936. */
  33937. this.height = height;
  33938. }
  33939. /**
  33940. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33941. * Changing the power will also change the light's intensity.
  33942. *
  33943. * @type {number}
  33944. */
  33945. get power() {
  33946. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33947. return this.intensity * this.width * this.height * Math.PI;
  33948. }
  33949. set power( power ) {
  33950. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33951. this.intensity = power / ( this.width * this.height * Math.PI );
  33952. }
  33953. copy( source ) {
  33954. super.copy( source );
  33955. this.width = source.width;
  33956. this.height = source.height;
  33957. return this;
  33958. }
  33959. toJSON( meta ) {
  33960. const data = super.toJSON( meta );
  33961. data.object.width = this.width;
  33962. data.object.height = this.height;
  33963. return data;
  33964. }
  33965. }
  33966. /**
  33967. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33968. * to encode lighting information.
  33969. *
  33970. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33971. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33972. */
  33973. class SphericalHarmonics3 {
  33974. /**
  33975. * Constructs a new spherical harmonics.
  33976. */
  33977. constructor() {
  33978. /**
  33979. * This flag can be used for type testing.
  33980. *
  33981. * @type {boolean}
  33982. * @readonly
  33983. * @default true
  33984. */
  33985. this.isSphericalHarmonics3 = true;
  33986. /**
  33987. * An array holding the (9) SH coefficients.
  33988. *
  33989. * @type {Array<Vector3>}
  33990. */
  33991. this.coefficients = [];
  33992. for ( let i = 0; i < 9; i ++ ) {
  33993. this.coefficients.push( new Vector3() );
  33994. }
  33995. }
  33996. /**
  33997. * Sets the given SH coefficients to this instance by copying
  33998. * the values.
  33999. *
  34000. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34001. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34002. */
  34003. set( coefficients ) {
  34004. for ( let i = 0; i < 9; i ++ ) {
  34005. this.coefficients[ i ].copy( coefficients[ i ] );
  34006. }
  34007. return this;
  34008. }
  34009. /**
  34010. * Sets all SH coefficients to `0`.
  34011. *
  34012. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34013. */
  34014. zero() {
  34015. for ( let i = 0; i < 9; i ++ ) {
  34016. this.coefficients[ i ].set( 0, 0, 0 );
  34017. }
  34018. return this;
  34019. }
  34020. /**
  34021. * Returns the radiance in the direction of the given normal.
  34022. *
  34023. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34024. * @param {Vector3} target - The target vector that is used to store the method's result.
  34025. * @return {Vector3} The radiance.
  34026. */
  34027. getAt( normal, target ) {
  34028. // normal is assumed to be unit length
  34029. const x = normal.x, y = normal.y, z = normal.z;
  34030. const coeff = this.coefficients;
  34031. // band 0
  34032. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34033. // band 1
  34034. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34035. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34036. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34037. // band 2
  34038. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34039. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34040. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34041. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34042. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34043. return target;
  34044. }
  34045. /**
  34046. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34047. * direction of the given normal.
  34048. *
  34049. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34050. * @param {Vector3} target - The target vector that is used to store the method's result.
  34051. * @return {Vector3} The irradiance.
  34052. */
  34053. getIrradianceAt( normal, target ) {
  34054. // normal is assumed to be unit length
  34055. const x = normal.x, y = normal.y, z = normal.z;
  34056. const coeff = this.coefficients;
  34057. // band 0
  34058. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34059. // band 1
  34060. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34061. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34062. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34063. // band 2
  34064. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34065. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34066. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34067. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34068. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34069. return target;
  34070. }
  34071. /**
  34072. * Adds the given SH to this instance.
  34073. *
  34074. * @param {SphericalHarmonics3} sh - The SH to add.
  34075. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34076. */
  34077. add( sh ) {
  34078. for ( let i = 0; i < 9; i ++ ) {
  34079. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34080. }
  34081. return this;
  34082. }
  34083. /**
  34084. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34085. * {@link SphericalHarmonics3#scale} at once.
  34086. *
  34087. * @param {SphericalHarmonics3} sh - The SH to add.
  34088. * @param {number} s - The scale factor.
  34089. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34090. */
  34091. addScaledSH( sh, s ) {
  34092. for ( let i = 0; i < 9; i ++ ) {
  34093. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34094. }
  34095. return this;
  34096. }
  34097. /**
  34098. * Scales this SH by the given scale factor.
  34099. *
  34100. * @param {number} s - The scale factor.
  34101. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34102. */
  34103. scale( s ) {
  34104. for ( let i = 0; i < 9; i ++ ) {
  34105. this.coefficients[ i ].multiplyScalar( s );
  34106. }
  34107. return this;
  34108. }
  34109. /**
  34110. * Linear interpolates between the given SH and this instance by the given
  34111. * alpha factor.
  34112. *
  34113. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34114. * @param {number} alpha - The alpha factor.
  34115. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34116. */
  34117. lerp( sh, alpha ) {
  34118. for ( let i = 0; i < 9; i ++ ) {
  34119. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34120. }
  34121. return this;
  34122. }
  34123. /**
  34124. * Returns `true` if this spherical harmonics is equal with the given one.
  34125. *
  34126. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34127. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34128. */
  34129. equals( sh ) {
  34130. for ( let i = 0; i < 9; i ++ ) {
  34131. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34132. return false;
  34133. }
  34134. }
  34135. return true;
  34136. }
  34137. /**
  34138. * Copies the values of the given spherical harmonics to this instance.
  34139. *
  34140. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34141. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34142. */
  34143. copy( sh ) {
  34144. return this.set( sh.coefficients );
  34145. }
  34146. /**
  34147. * Returns a new spherical harmonics with copied values from this instance.
  34148. *
  34149. * @return {SphericalHarmonics3} A clone of this instance.
  34150. */
  34151. clone() {
  34152. return new this.constructor().copy( this );
  34153. }
  34154. /**
  34155. * Sets the SH coefficients of this instance from the given array.
  34156. *
  34157. * @param {Array<number>} array - An array holding the SH coefficients.
  34158. * @param {number} [offset=0] - The array offset where to start copying.
  34159. * @return {SphericalHarmonics3} A clone of this instance.
  34160. */
  34161. fromArray( array, offset = 0 ) {
  34162. const coefficients = this.coefficients;
  34163. for ( let i = 0; i < 9; i ++ ) {
  34164. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34165. }
  34166. return this;
  34167. }
  34168. /**
  34169. * Returns an array with the SH coefficients, or copies them into the provided
  34170. * array. The coefficients are represented as numbers.
  34171. *
  34172. * @param {Array<number>} [array=[]] - The target array.
  34173. * @param {number} [offset=0] - The array offset where to start copying.
  34174. * @return {Array<number>} An array with flat SH coefficients.
  34175. */
  34176. toArray( array = [], offset = 0 ) {
  34177. const coefficients = this.coefficients;
  34178. for ( let i = 0; i < 9; i ++ ) {
  34179. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34180. }
  34181. return array;
  34182. }
  34183. /**
  34184. * Computes the SH basis for the given normal vector.
  34185. *
  34186. * @param {Vector3} normal - The normal.
  34187. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34188. */
  34189. static getBasisAt( normal, shBasis ) {
  34190. // normal is assumed to be unit length
  34191. const x = normal.x, y = normal.y, z = normal.z;
  34192. // band 0
  34193. shBasis[ 0 ] = 0.282095;
  34194. // band 1
  34195. shBasis[ 1 ] = 0.488603 * y;
  34196. shBasis[ 2 ] = 0.488603 * z;
  34197. shBasis[ 3 ] = 0.488603 * x;
  34198. // band 2
  34199. shBasis[ 4 ] = 1.092548 * x * y;
  34200. shBasis[ 5 ] = 1.092548 * y * z;
  34201. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34202. shBasis[ 7 ] = 1.092548 * x * z;
  34203. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34204. }
  34205. }
  34206. /**
  34207. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34208. * classical light sources (e.g. directional, point or spot lights), light
  34209. * probes do not emit light. Instead they store information about light
  34210. * passing through 3D space. During rendering, the light that hits a 3D
  34211. * object is approximated by using the data from the light probe.
  34212. *
  34213. * Light probes are usually created from (radiance) environment maps. The
  34214. * class {@link LightProbeGenerator} can be used to create light probes from
  34215. * cube textures or render targets. However, light estimation data could also
  34216. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34217. * augmented reality content that reacts to real world lighting.
  34218. *
  34219. * The current probe implementation in three.js supports so-called diffuse
  34220. * light probes. This type of light probe is functionally equivalent to an
  34221. * irradiance environment map.
  34222. *
  34223. * @augments Light
  34224. */
  34225. class LightProbe extends Light {
  34226. /**
  34227. * Constructs a new light probe.
  34228. *
  34229. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34230. * @param {number} [intensity=1] - The light's strength/intensity.
  34231. */
  34232. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34233. super( undefined, intensity );
  34234. /**
  34235. * This flag can be used for type testing.
  34236. *
  34237. * @type {boolean}
  34238. * @readonly
  34239. * @default true
  34240. */
  34241. this.isLightProbe = true;
  34242. /**
  34243. * A light probe uses spherical harmonics to encode lighting information.
  34244. *
  34245. * @type {SphericalHarmonics3}
  34246. */
  34247. this.sh = sh;
  34248. }
  34249. copy( source ) {
  34250. super.copy( source );
  34251. this.sh.copy( source.sh );
  34252. return this;
  34253. }
  34254. /**
  34255. * Deserializes the light prove from the given JSON.
  34256. *
  34257. * @param {Object} json - The JSON holding the serialized light probe.
  34258. * @return {LightProbe} A reference to this light probe.
  34259. */
  34260. fromJSON( json ) {
  34261. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34262. this.sh.fromArray( json.sh );
  34263. return this;
  34264. }
  34265. toJSON( meta ) {
  34266. const data = super.toJSON( meta );
  34267. data.object.sh = this.sh.toArray();
  34268. return data;
  34269. }
  34270. }
  34271. /**
  34272. * Class for loading geometries. The files are internally
  34273. * loaded via {@link FileLoader}.
  34274. *
  34275. * ```js
  34276. * const loader = new THREE.MaterialLoader();
  34277. * const material = await loader.loadAsync( 'material.json' );
  34278. * ```
  34279. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34280. *
  34281. * @augments Loader
  34282. */
  34283. class MaterialLoader extends Loader {
  34284. /**
  34285. * Constructs a new material loader.
  34286. *
  34287. * @param {LoadingManager} [manager] - The loading manager.
  34288. */
  34289. constructor( manager ) {
  34290. super( manager );
  34291. /**
  34292. * A dictionary holding textures used by the material.
  34293. *
  34294. * @type {Object<string,Texture>}
  34295. */
  34296. this.textures = {};
  34297. }
  34298. /**
  34299. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34300. *
  34301. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34302. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34303. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34304. * @param {onErrorCallback} onError - Executed when errors occur.
  34305. */
  34306. load( url, onLoad, onProgress, onError ) {
  34307. const scope = this;
  34308. const loader = new FileLoader( scope.manager );
  34309. loader.setPath( scope.path );
  34310. loader.setRequestHeader( scope.requestHeader );
  34311. loader.setWithCredentials( scope.withCredentials );
  34312. loader.load( url, function ( text ) {
  34313. try {
  34314. onLoad( scope.parse( JSON.parse( text ) ) );
  34315. } catch ( e ) {
  34316. if ( onError ) {
  34317. onError( e );
  34318. } else {
  34319. console.error( e );
  34320. }
  34321. scope.manager.itemError( url );
  34322. }
  34323. }, onProgress, onError );
  34324. }
  34325. /**
  34326. * Parses the given JSON object and returns a material.
  34327. *
  34328. * @param {Object} json - The serialized material.
  34329. * @return {Material} The parsed material.
  34330. */
  34331. parse( json ) {
  34332. const textures = this.textures;
  34333. function getTexture( name ) {
  34334. if ( textures[ name ] === undefined ) {
  34335. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34336. }
  34337. return textures[ name ];
  34338. }
  34339. const material = this.createMaterialFromType( json.type );
  34340. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34341. if ( json.name !== undefined ) material.name = json.name;
  34342. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34343. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34344. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34345. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34346. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34347. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34348. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34349. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34350. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34351. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34352. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34353. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34354. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34355. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34356. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34357. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34358. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34359. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34360. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34361. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34362. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34363. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34364. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34365. if ( json.fog !== undefined ) material.fog = json.fog;
  34366. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34367. if ( json.blending !== undefined ) material.blending = json.blending;
  34368. if ( json.combine !== undefined ) material.combine = json.combine;
  34369. if ( json.side !== undefined ) material.side = json.side;
  34370. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34371. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34372. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34373. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34374. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34375. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34376. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34377. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34378. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34379. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34380. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34381. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34382. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34383. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34384. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34385. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34386. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34387. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34388. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34389. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34390. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34391. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34392. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34393. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34394. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34395. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34396. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34397. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34398. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34399. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34400. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34401. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34402. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34403. if ( json.scale !== undefined ) material.scale = json.scale;
  34404. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34405. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34406. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34407. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34408. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34409. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34410. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34411. if ( json.visible !== undefined ) material.visible = json.visible;
  34412. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34413. if ( json.userData !== undefined ) material.userData = json.userData;
  34414. if ( json.vertexColors !== undefined ) {
  34415. if ( typeof json.vertexColors === 'number' ) {
  34416. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34417. } else {
  34418. material.vertexColors = json.vertexColors;
  34419. }
  34420. }
  34421. // Shader Material
  34422. if ( json.uniforms !== undefined ) {
  34423. for ( const name in json.uniforms ) {
  34424. const uniform = json.uniforms[ name ];
  34425. material.uniforms[ name ] = {};
  34426. switch ( uniform.type ) {
  34427. case 't':
  34428. material.uniforms[ name ].value = getTexture( uniform.value );
  34429. break;
  34430. case 'c':
  34431. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34432. break;
  34433. case 'v2':
  34434. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34435. break;
  34436. case 'v3':
  34437. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34438. break;
  34439. case 'v4':
  34440. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34441. break;
  34442. case 'm3':
  34443. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34444. break;
  34445. case 'm4':
  34446. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34447. break;
  34448. default:
  34449. material.uniforms[ name ].value = uniform.value;
  34450. }
  34451. }
  34452. }
  34453. if ( json.defines !== undefined ) material.defines = json.defines;
  34454. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34455. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34456. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34457. if ( json.extensions !== undefined ) {
  34458. for ( const key in json.extensions ) {
  34459. material.extensions[ key ] = json.extensions[ key ];
  34460. }
  34461. }
  34462. if ( json.lights !== undefined ) material.lights = json.lights;
  34463. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34464. // for PointsMaterial
  34465. if ( json.size !== undefined ) material.size = json.size;
  34466. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34467. // maps
  34468. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34469. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34470. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34471. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34472. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34473. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34474. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34475. if ( json.normalScale !== undefined ) {
  34476. let normalScale = json.normalScale;
  34477. if ( Array.isArray( normalScale ) === false ) {
  34478. // Blender exporter used to export a scalar. See #7459
  34479. normalScale = [ normalScale, normalScale ];
  34480. }
  34481. material.normalScale = new Vector2().fromArray( normalScale );
  34482. }
  34483. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34484. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34485. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34486. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34487. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34488. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34489. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34490. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34491. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34492. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34493. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34494. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34495. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34496. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34497. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34498. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34499. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34500. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34501. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34502. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34503. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34504. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34505. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34506. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34507. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34508. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34509. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34510. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34511. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34512. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34513. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34514. return material;
  34515. }
  34516. /**
  34517. * Textures are not embedded in the material JSON so they have
  34518. * to be injected before the loading process starts.
  34519. *
  34520. * @param {Object} value - A dictionary holding textures for material properties.
  34521. * @return {MaterialLoader} A reference to this material loader.
  34522. */
  34523. setTextures( value ) {
  34524. this.textures = value;
  34525. return this;
  34526. }
  34527. /**
  34528. * Creates a material for the given type.
  34529. *
  34530. * @param {string} type - The material type.
  34531. * @return {Material} The new material.
  34532. */
  34533. createMaterialFromType( type ) {
  34534. return MaterialLoader.createMaterialFromType( type );
  34535. }
  34536. /**
  34537. * Creates a material for the given type.
  34538. *
  34539. * @static
  34540. * @param {string} type - The material type.
  34541. * @return {Material} The new material.
  34542. */
  34543. static createMaterialFromType( type ) {
  34544. const materialLib = {
  34545. ShadowMaterial,
  34546. SpriteMaterial,
  34547. RawShaderMaterial,
  34548. ShaderMaterial,
  34549. PointsMaterial,
  34550. MeshPhysicalMaterial,
  34551. MeshStandardMaterial,
  34552. MeshPhongMaterial,
  34553. MeshToonMaterial,
  34554. MeshNormalMaterial,
  34555. MeshLambertMaterial,
  34556. MeshDepthMaterial,
  34557. MeshDistanceMaterial,
  34558. MeshBasicMaterial,
  34559. MeshMatcapMaterial,
  34560. LineDashedMaterial,
  34561. LineBasicMaterial,
  34562. Material
  34563. };
  34564. return new materialLib[ type ]();
  34565. }
  34566. }
  34567. /**
  34568. * A class with loader utility functions.
  34569. */
  34570. class LoaderUtils {
  34571. /**
  34572. * Extracts the base URL from the given URL.
  34573. *
  34574. * @param {string} url -The URL to extract the base URL from.
  34575. * @return {string} The extracted base URL.
  34576. */
  34577. static extractUrlBase( url ) {
  34578. const index = url.lastIndexOf( '/' );
  34579. if ( index === -1 ) return './';
  34580. return url.slice( 0, index + 1 );
  34581. }
  34582. /**
  34583. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34584. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34585. * string.
  34586. *
  34587. * @param {string} url -The URL to resolve.
  34588. * @param {string} path - The base path for relative URLs to be resolved against.
  34589. * @return {string} The resolved URL.
  34590. */
  34591. static resolveURL( url, path ) {
  34592. // Invalid URL
  34593. if ( typeof url !== 'string' || url === '' ) return '';
  34594. // Host Relative URL
  34595. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34596. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34597. }
  34598. // Absolute URL http://,https://,//
  34599. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34600. // Data URI
  34601. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34602. // Blob URL
  34603. if ( /^blob:.*$/i.test( url ) ) return url;
  34604. // Relative URL
  34605. return path + url;
  34606. }
  34607. }
  34608. /**
  34609. * An instanced version of a geometry.
  34610. */
  34611. class InstancedBufferGeometry extends BufferGeometry {
  34612. /**
  34613. * Constructs a new instanced buffer geometry.
  34614. */
  34615. constructor() {
  34616. super();
  34617. /**
  34618. * This flag can be used for type testing.
  34619. *
  34620. * @type {boolean}
  34621. * @readonly
  34622. * @default true
  34623. */
  34624. this.isInstancedBufferGeometry = true;
  34625. this.type = 'InstancedBufferGeometry';
  34626. /**
  34627. * The instance count.
  34628. *
  34629. * @type {number}
  34630. * @default Infinity
  34631. */
  34632. this.instanceCount = Infinity;
  34633. }
  34634. copy( source ) {
  34635. super.copy( source );
  34636. this.instanceCount = source.instanceCount;
  34637. return this;
  34638. }
  34639. toJSON() {
  34640. const data = super.toJSON();
  34641. data.instanceCount = this.instanceCount;
  34642. data.isInstancedBufferGeometry = true;
  34643. return data;
  34644. }
  34645. }
  34646. /**
  34647. * Class for loading geometries. The files are internally
  34648. * loaded via {@link FileLoader}.
  34649. *
  34650. * ```js
  34651. * const loader = new THREE.BufferGeometryLoader();
  34652. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34653. *
  34654. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34655. * const object = new THREE.Mesh( geometry, material );
  34656. * scene.add( object );
  34657. * ```
  34658. *
  34659. * @augments Loader
  34660. */
  34661. class BufferGeometryLoader extends Loader {
  34662. /**
  34663. * Constructs a new geometry loader.
  34664. *
  34665. * @param {LoadingManager} [manager] - The loading manager.
  34666. */
  34667. constructor( manager ) {
  34668. super( manager );
  34669. }
  34670. /**
  34671. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34672. *
  34673. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34674. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34675. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34676. * @param {onErrorCallback} onError - Executed when errors occur.
  34677. */
  34678. load( url, onLoad, onProgress, onError ) {
  34679. const scope = this;
  34680. const loader = new FileLoader( scope.manager );
  34681. loader.setPath( scope.path );
  34682. loader.setRequestHeader( scope.requestHeader );
  34683. loader.setWithCredentials( scope.withCredentials );
  34684. loader.load( url, function ( text ) {
  34685. try {
  34686. onLoad( scope.parse( JSON.parse( text ) ) );
  34687. } catch ( e ) {
  34688. if ( onError ) {
  34689. onError( e );
  34690. } else {
  34691. console.error( e );
  34692. }
  34693. scope.manager.itemError( url );
  34694. }
  34695. }, onProgress, onError );
  34696. }
  34697. /**
  34698. * Parses the given JSON object and returns a geometry.
  34699. *
  34700. * @param {Object} json - The serialized geometry.
  34701. * @return {BufferGeometry} The parsed geometry.
  34702. */
  34703. parse( json ) {
  34704. const interleavedBufferMap = {};
  34705. const arrayBufferMap = {};
  34706. function getInterleavedBuffer( json, uuid ) {
  34707. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34708. const interleavedBuffers = json.interleavedBuffers;
  34709. const interleavedBuffer = interleavedBuffers[ uuid ];
  34710. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34711. const array = getTypedArray( interleavedBuffer.type, buffer );
  34712. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34713. ib.uuid = interleavedBuffer.uuid;
  34714. interleavedBufferMap[ uuid ] = ib;
  34715. return ib;
  34716. }
  34717. function getArrayBuffer( json, uuid ) {
  34718. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34719. const arrayBuffers = json.arrayBuffers;
  34720. const arrayBuffer = arrayBuffers[ uuid ];
  34721. const ab = new Uint32Array( arrayBuffer ).buffer;
  34722. arrayBufferMap[ uuid ] = ab;
  34723. return ab;
  34724. }
  34725. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34726. const index = json.data.index;
  34727. if ( index !== undefined ) {
  34728. const typedArray = getTypedArray( index.type, index.array );
  34729. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34730. }
  34731. const attributes = json.data.attributes;
  34732. for ( const key in attributes ) {
  34733. const attribute = attributes[ key ];
  34734. let bufferAttribute;
  34735. if ( attribute.isInterleavedBufferAttribute ) {
  34736. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34737. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34738. } else {
  34739. const typedArray = getTypedArray( attribute.type, attribute.array );
  34740. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34741. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34742. }
  34743. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34744. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34745. geometry.setAttribute( key, bufferAttribute );
  34746. }
  34747. const morphAttributes = json.data.morphAttributes;
  34748. if ( morphAttributes ) {
  34749. for ( const key in morphAttributes ) {
  34750. const attributeArray = morphAttributes[ key ];
  34751. const array = [];
  34752. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34753. const attribute = attributeArray[ i ];
  34754. let bufferAttribute;
  34755. if ( attribute.isInterleavedBufferAttribute ) {
  34756. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34757. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34758. } else {
  34759. const typedArray = getTypedArray( attribute.type, attribute.array );
  34760. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34761. }
  34762. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34763. array.push( bufferAttribute );
  34764. }
  34765. geometry.morphAttributes[ key ] = array;
  34766. }
  34767. }
  34768. const morphTargetsRelative = json.data.morphTargetsRelative;
  34769. if ( morphTargetsRelative ) {
  34770. geometry.morphTargetsRelative = true;
  34771. }
  34772. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34773. if ( groups !== undefined ) {
  34774. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34775. const group = groups[ i ];
  34776. geometry.addGroup( group.start, group.count, group.materialIndex );
  34777. }
  34778. }
  34779. const boundingSphere = json.data.boundingSphere;
  34780. if ( boundingSphere !== undefined ) {
  34781. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34782. }
  34783. if ( json.name ) geometry.name = json.name;
  34784. if ( json.userData ) geometry.userData = json.userData;
  34785. return geometry;
  34786. }
  34787. }
  34788. /**
  34789. * 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}.
  34790. * The files are internally loaded via {@link FileLoader}.
  34791. *
  34792. * ```js
  34793. * const loader = new THREE.ObjectLoader();
  34794. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34795. * scene.add( obj );
  34796. *
  34797. * // Alternatively, to parse a previously loaded JSON structure
  34798. * const object = await loader.parseAsync( a_json_object );
  34799. * scene.add( object );
  34800. * ```
  34801. *
  34802. * @augments Loader
  34803. */
  34804. class ObjectLoader extends Loader {
  34805. /**
  34806. * Constructs a new object loader.
  34807. *
  34808. * @param {LoadingManager} [manager] - The loading manager.
  34809. */
  34810. constructor( manager ) {
  34811. super( manager );
  34812. }
  34813. /**
  34814. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34815. *
  34816. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34817. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34818. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34819. * @param {onErrorCallback} onError - Executed when errors occur.
  34820. */
  34821. load( url, onLoad, onProgress, onError ) {
  34822. const scope = this;
  34823. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34824. this.resourcePath = this.resourcePath || path;
  34825. const loader = new FileLoader( this.manager );
  34826. loader.setPath( this.path );
  34827. loader.setRequestHeader( this.requestHeader );
  34828. loader.setWithCredentials( this.withCredentials );
  34829. loader.load( url, function ( text ) {
  34830. let json = null;
  34831. try {
  34832. json = JSON.parse( text );
  34833. } catch ( error ) {
  34834. if ( onError !== undefined ) onError( error );
  34835. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34836. return;
  34837. }
  34838. const metadata = json.metadata;
  34839. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34840. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34841. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34842. return;
  34843. }
  34844. scope.parse( json, onLoad );
  34845. }, onProgress, onError );
  34846. }
  34847. /**
  34848. * Async version of {@link ObjectLoader#load}.
  34849. *
  34850. * @async
  34851. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34852. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34853. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34854. */
  34855. async loadAsync( url, onProgress ) {
  34856. const scope = this;
  34857. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34858. this.resourcePath = this.resourcePath || path;
  34859. const loader = new FileLoader( this.manager );
  34860. loader.setPath( this.path );
  34861. loader.setRequestHeader( this.requestHeader );
  34862. loader.setWithCredentials( this.withCredentials );
  34863. const text = await loader.loadAsync( url, onProgress );
  34864. const json = JSON.parse( text );
  34865. const metadata = json.metadata;
  34866. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34867. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34868. }
  34869. return await scope.parseAsync( json );
  34870. }
  34871. /**
  34872. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34873. * but can also be used directly to parse a previously loaded JSON structure.
  34874. *
  34875. * @param {Object} json - The serialized 3D object.
  34876. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34877. * @return {Object3D} The parsed 3D object.
  34878. */
  34879. parse( json, onLoad ) {
  34880. const animations = this.parseAnimations( json.animations );
  34881. const shapes = this.parseShapes( json.shapes );
  34882. const geometries = this.parseGeometries( json.geometries, shapes );
  34883. const images = this.parseImages( json.images, function () {
  34884. if ( onLoad !== undefined ) onLoad( object );
  34885. } );
  34886. const textures = this.parseTextures( json.textures, images );
  34887. const materials = this.parseMaterials( json.materials, textures );
  34888. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34889. const skeletons = this.parseSkeletons( json.skeletons, object );
  34890. this.bindSkeletons( object, skeletons );
  34891. this.bindLightTargets( object );
  34892. //
  34893. if ( onLoad !== undefined ) {
  34894. let hasImages = false;
  34895. for ( const uuid in images ) {
  34896. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34897. hasImages = true;
  34898. break;
  34899. }
  34900. }
  34901. if ( hasImages === false ) onLoad( object );
  34902. }
  34903. return object;
  34904. }
  34905. /**
  34906. * Async version of {@link ObjectLoader#parse}.
  34907. *
  34908. * @param {Object} json - The serialized 3D object.
  34909. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34910. */
  34911. async parseAsync( json ) {
  34912. const animations = this.parseAnimations( json.animations );
  34913. const shapes = this.parseShapes( json.shapes );
  34914. const geometries = this.parseGeometries( json.geometries, shapes );
  34915. const images = await this.parseImagesAsync( json.images );
  34916. const textures = this.parseTextures( json.textures, images );
  34917. const materials = this.parseMaterials( json.materials, textures );
  34918. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34919. const skeletons = this.parseSkeletons( json.skeletons, object );
  34920. this.bindSkeletons( object, skeletons );
  34921. this.bindLightTargets( object );
  34922. return object;
  34923. }
  34924. // internals
  34925. parseShapes( json ) {
  34926. const shapes = {};
  34927. if ( json !== undefined ) {
  34928. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34929. const shape = new Shape().fromJSON( json[ i ] );
  34930. shapes[ shape.uuid ] = shape;
  34931. }
  34932. }
  34933. return shapes;
  34934. }
  34935. parseSkeletons( json, object ) {
  34936. const skeletons = {};
  34937. const bones = {};
  34938. // generate bone lookup table
  34939. object.traverse( function ( child ) {
  34940. if ( child.isBone ) bones[ child.uuid ] = child;
  34941. } );
  34942. // create skeletons
  34943. if ( json !== undefined ) {
  34944. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34945. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34946. skeletons[ skeleton.uuid ] = skeleton;
  34947. }
  34948. }
  34949. return skeletons;
  34950. }
  34951. parseGeometries( json, shapes ) {
  34952. const geometries = {};
  34953. if ( json !== undefined ) {
  34954. const bufferGeometryLoader = new BufferGeometryLoader();
  34955. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34956. let geometry;
  34957. const data = json[ i ];
  34958. switch ( data.type ) {
  34959. case 'BufferGeometry':
  34960. case 'InstancedBufferGeometry':
  34961. geometry = bufferGeometryLoader.parse( data );
  34962. break;
  34963. default:
  34964. if ( data.type in Geometries ) {
  34965. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34966. } else {
  34967. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34968. }
  34969. }
  34970. geometry.uuid = data.uuid;
  34971. if ( data.name !== undefined ) geometry.name = data.name;
  34972. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34973. geometries[ data.uuid ] = geometry;
  34974. }
  34975. }
  34976. return geometries;
  34977. }
  34978. parseMaterials( json, textures ) {
  34979. const cache = {}; // MultiMaterial
  34980. const materials = {};
  34981. if ( json !== undefined ) {
  34982. const loader = new MaterialLoader();
  34983. loader.setTextures( textures );
  34984. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34985. const data = json[ i ];
  34986. if ( cache[ data.uuid ] === undefined ) {
  34987. cache[ data.uuid ] = loader.parse( data );
  34988. }
  34989. materials[ data.uuid ] = cache[ data.uuid ];
  34990. }
  34991. }
  34992. return materials;
  34993. }
  34994. parseAnimations( json ) {
  34995. const animations = {};
  34996. if ( json !== undefined ) {
  34997. for ( let i = 0; i < json.length; i ++ ) {
  34998. const data = json[ i ];
  34999. const clip = AnimationClip.parse( data );
  35000. animations[ clip.uuid ] = clip;
  35001. }
  35002. }
  35003. return animations;
  35004. }
  35005. parseImages( json, onLoad ) {
  35006. const scope = this;
  35007. const images = {};
  35008. let loader;
  35009. function loadImage( url ) {
  35010. scope.manager.itemStart( url );
  35011. return loader.load( url, function () {
  35012. scope.manager.itemEnd( url );
  35013. }, undefined, function () {
  35014. scope.manager.itemError( url );
  35015. scope.manager.itemEnd( url );
  35016. } );
  35017. }
  35018. function deserializeImage( image ) {
  35019. if ( typeof image === 'string' ) {
  35020. const url = image;
  35021. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35022. return loadImage( path );
  35023. } else {
  35024. if ( image.data ) {
  35025. return {
  35026. data: getTypedArray( image.type, image.data ),
  35027. width: image.width,
  35028. height: image.height
  35029. };
  35030. } else {
  35031. return null;
  35032. }
  35033. }
  35034. }
  35035. if ( json !== undefined && json.length > 0 ) {
  35036. const manager = new LoadingManager( onLoad );
  35037. loader = new ImageLoader( manager );
  35038. loader.setCrossOrigin( this.crossOrigin );
  35039. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35040. const image = json[ i ];
  35041. const url = image.url;
  35042. if ( Array.isArray( url ) ) {
  35043. // load array of images e.g CubeTexture
  35044. const imageArray = [];
  35045. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35046. const currentUrl = url[ j ];
  35047. const deserializedImage = deserializeImage( currentUrl );
  35048. if ( deserializedImage !== null ) {
  35049. if ( deserializedImage instanceof HTMLImageElement ) {
  35050. imageArray.push( deserializedImage );
  35051. } else {
  35052. // special case: handle array of data textures for cube textures
  35053. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35054. }
  35055. }
  35056. }
  35057. images[ image.uuid ] = new Source( imageArray );
  35058. } else {
  35059. // load single image
  35060. const deserializedImage = deserializeImage( image.url );
  35061. images[ image.uuid ] = new Source( deserializedImage );
  35062. }
  35063. }
  35064. }
  35065. return images;
  35066. }
  35067. async parseImagesAsync( json ) {
  35068. const scope = this;
  35069. const images = {};
  35070. let loader;
  35071. async function deserializeImage( image ) {
  35072. if ( typeof image === 'string' ) {
  35073. const url = image;
  35074. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35075. return await loader.loadAsync( path );
  35076. } else {
  35077. if ( image.data ) {
  35078. return {
  35079. data: getTypedArray( image.type, image.data ),
  35080. width: image.width,
  35081. height: image.height
  35082. };
  35083. } else {
  35084. return null;
  35085. }
  35086. }
  35087. }
  35088. if ( json !== undefined && json.length > 0 ) {
  35089. loader = new ImageLoader( this.manager );
  35090. loader.setCrossOrigin( this.crossOrigin );
  35091. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35092. const image = json[ i ];
  35093. const url = image.url;
  35094. if ( Array.isArray( url ) ) {
  35095. // load array of images e.g CubeTexture
  35096. const imageArray = [];
  35097. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35098. const currentUrl = url[ j ];
  35099. const deserializedImage = await deserializeImage( currentUrl );
  35100. if ( deserializedImage !== null ) {
  35101. if ( deserializedImage instanceof HTMLImageElement ) {
  35102. imageArray.push( deserializedImage );
  35103. } else {
  35104. // special case: handle array of data textures for cube textures
  35105. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35106. }
  35107. }
  35108. }
  35109. images[ image.uuid ] = new Source( imageArray );
  35110. } else {
  35111. // load single image
  35112. const deserializedImage = await deserializeImage( image.url );
  35113. images[ image.uuid ] = new Source( deserializedImage );
  35114. }
  35115. }
  35116. }
  35117. return images;
  35118. }
  35119. parseTextures( json, images ) {
  35120. function parseConstant( value, type ) {
  35121. if ( typeof value === 'number' ) return value;
  35122. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35123. return type[ value ];
  35124. }
  35125. const textures = {};
  35126. if ( json !== undefined ) {
  35127. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35128. const data = json[ i ];
  35129. if ( data.image === undefined ) {
  35130. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35131. }
  35132. if ( images[ data.image ] === undefined ) {
  35133. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35134. }
  35135. const source = images[ data.image ];
  35136. const image = source.data;
  35137. let texture;
  35138. if ( Array.isArray( image ) ) {
  35139. texture = new CubeTexture();
  35140. if ( image.length === 6 ) texture.needsUpdate = true;
  35141. } else {
  35142. if ( image && image.data ) {
  35143. texture = new DataTexture();
  35144. } else {
  35145. texture = new Texture();
  35146. }
  35147. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35148. }
  35149. texture.source = source;
  35150. texture.uuid = data.uuid;
  35151. if ( data.name !== undefined ) texture.name = data.name;
  35152. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35153. if ( data.channel !== undefined ) texture.channel = data.channel;
  35154. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35155. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35156. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35157. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35158. if ( data.wrap !== undefined ) {
  35159. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35160. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35161. }
  35162. if ( data.format !== undefined ) texture.format = data.format;
  35163. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35164. if ( data.type !== undefined ) texture.type = data.type;
  35165. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35166. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35167. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35168. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35169. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35170. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35171. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35172. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35173. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35174. if ( data.userData !== undefined ) texture.userData = data.userData;
  35175. textures[ data.uuid ] = texture;
  35176. }
  35177. }
  35178. return textures;
  35179. }
  35180. parseObject( data, geometries, materials, textures, animations ) {
  35181. let object;
  35182. function getGeometry( name ) {
  35183. if ( geometries[ name ] === undefined ) {
  35184. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35185. }
  35186. return geometries[ name ];
  35187. }
  35188. function getMaterial( name ) {
  35189. if ( name === undefined ) return undefined;
  35190. if ( Array.isArray( name ) ) {
  35191. const array = [];
  35192. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35193. const uuid = name[ i ];
  35194. if ( materials[ uuid ] === undefined ) {
  35195. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35196. }
  35197. array.push( materials[ uuid ] );
  35198. }
  35199. return array;
  35200. }
  35201. if ( materials[ name ] === undefined ) {
  35202. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35203. }
  35204. return materials[ name ];
  35205. }
  35206. function getTexture( uuid ) {
  35207. if ( textures[ uuid ] === undefined ) {
  35208. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35209. }
  35210. return textures[ uuid ];
  35211. }
  35212. let geometry, material;
  35213. switch ( data.type ) {
  35214. case 'Scene':
  35215. object = new Scene();
  35216. if ( data.background !== undefined ) {
  35217. if ( Number.isInteger( data.background ) ) {
  35218. object.background = new Color( data.background );
  35219. } else {
  35220. object.background = getTexture( data.background );
  35221. }
  35222. }
  35223. if ( data.environment !== undefined ) {
  35224. object.environment = getTexture( data.environment );
  35225. }
  35226. if ( data.fog !== undefined ) {
  35227. if ( data.fog.type === 'Fog' ) {
  35228. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35229. } else if ( data.fog.type === 'FogExp2' ) {
  35230. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35231. }
  35232. if ( data.fog.name !== '' ) {
  35233. object.fog.name = data.fog.name;
  35234. }
  35235. }
  35236. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35237. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35238. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35239. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35240. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35241. break;
  35242. case 'PerspectiveCamera':
  35243. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35244. if ( data.focus !== undefined ) object.focus = data.focus;
  35245. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35246. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35247. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35248. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35249. break;
  35250. case 'OrthographicCamera':
  35251. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35252. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35253. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35254. break;
  35255. case 'AmbientLight':
  35256. object = new AmbientLight( data.color, data.intensity );
  35257. break;
  35258. case 'DirectionalLight':
  35259. object = new DirectionalLight( data.color, data.intensity );
  35260. object.target = data.target || '';
  35261. break;
  35262. case 'PointLight':
  35263. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35264. break;
  35265. case 'RectAreaLight':
  35266. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35267. break;
  35268. case 'SpotLight':
  35269. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35270. object.target = data.target || '';
  35271. break;
  35272. case 'HemisphereLight':
  35273. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35274. break;
  35275. case 'LightProbe':
  35276. object = new LightProbe().fromJSON( data );
  35277. break;
  35278. case 'SkinnedMesh':
  35279. geometry = getGeometry( data.geometry );
  35280. material = getMaterial( data.material );
  35281. object = new SkinnedMesh( geometry, material );
  35282. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35283. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35284. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35285. break;
  35286. case 'Mesh':
  35287. geometry = getGeometry( data.geometry );
  35288. material = getMaterial( data.material );
  35289. object = new Mesh( geometry, material );
  35290. break;
  35291. case 'InstancedMesh':
  35292. geometry = getGeometry( data.geometry );
  35293. material = getMaterial( data.material );
  35294. const count = data.count;
  35295. const instanceMatrix = data.instanceMatrix;
  35296. const instanceColor = data.instanceColor;
  35297. object = new InstancedMesh( geometry, material, count );
  35298. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35299. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35300. break;
  35301. case 'BatchedMesh':
  35302. geometry = getGeometry( data.geometry );
  35303. material = getMaterial( data.material );
  35304. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35305. object.geometry = geometry;
  35306. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35307. object.sortObjects = data.sortObjects;
  35308. object._drawRanges = data.drawRanges;
  35309. object._reservedRanges = data.reservedRanges;
  35310. object._geometryInfo = data.geometryInfo.map( info => {
  35311. let box = null;
  35312. let sphere = null;
  35313. if ( info.boundingBox !== undefined ) {
  35314. box = new Box3().fromJSON( info.boundingBox );
  35315. }
  35316. if ( info.boundingSphere !== undefined ) {
  35317. sphere = new Sphere().fromJSON( info.boundingSphere );
  35318. }
  35319. return {
  35320. ...info,
  35321. boundingBox: box,
  35322. boundingSphere: sphere
  35323. };
  35324. } );
  35325. object._instanceInfo = data.instanceInfo;
  35326. object._availableInstanceIds = data._availableInstanceIds;
  35327. object._availableGeometryIds = data._availableGeometryIds;
  35328. object._nextIndexStart = data.nextIndexStart;
  35329. object._nextVertexStart = data.nextVertexStart;
  35330. object._geometryCount = data.geometryCount;
  35331. object._maxInstanceCount = data.maxInstanceCount;
  35332. object._maxVertexCount = data.maxVertexCount;
  35333. object._maxIndexCount = data.maxIndexCount;
  35334. object._geometryInitialized = data.geometryInitialized;
  35335. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35336. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35337. if ( data.colorsTexture !== undefined ) {
  35338. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35339. }
  35340. if ( data.boundingSphere !== undefined ) {
  35341. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35342. }
  35343. if ( data.boundingBox !== undefined ) {
  35344. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35345. }
  35346. break;
  35347. case 'LOD':
  35348. object = new LOD();
  35349. break;
  35350. case 'Line':
  35351. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35352. break;
  35353. case 'LineLoop':
  35354. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35355. break;
  35356. case 'LineSegments':
  35357. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35358. break;
  35359. case 'PointCloud':
  35360. case 'Points':
  35361. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35362. break;
  35363. case 'Sprite':
  35364. object = new Sprite( getMaterial( data.material ) );
  35365. break;
  35366. case 'Group':
  35367. object = new Group();
  35368. break;
  35369. case 'Bone':
  35370. object = new Bone();
  35371. break;
  35372. default:
  35373. object = new Object3D();
  35374. }
  35375. object.uuid = data.uuid;
  35376. if ( data.name !== undefined ) object.name = data.name;
  35377. if ( data.matrix !== undefined ) {
  35378. object.matrix.fromArray( data.matrix );
  35379. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35380. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35381. } else {
  35382. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35383. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35384. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35385. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35386. }
  35387. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35388. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35389. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35390. if ( data.shadow ) {
  35391. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35392. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35393. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35394. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35395. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35396. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35397. }
  35398. if ( data.visible !== undefined ) object.visible = data.visible;
  35399. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35400. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35401. if ( data.userData !== undefined ) object.userData = data.userData;
  35402. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35403. if ( data.children !== undefined ) {
  35404. const children = data.children;
  35405. for ( let i = 0; i < children.length; i ++ ) {
  35406. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35407. }
  35408. }
  35409. if ( data.animations !== undefined ) {
  35410. const objectAnimations = data.animations;
  35411. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35412. const uuid = objectAnimations[ i ];
  35413. object.animations.push( animations[ uuid ] );
  35414. }
  35415. }
  35416. if ( data.type === 'LOD' ) {
  35417. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35418. const levels = data.levels;
  35419. for ( let l = 0; l < levels.length; l ++ ) {
  35420. const level = levels[ l ];
  35421. const child = object.getObjectByProperty( 'uuid', level.object );
  35422. if ( child !== undefined ) {
  35423. object.addLevel( child, level.distance, level.hysteresis );
  35424. }
  35425. }
  35426. }
  35427. return object;
  35428. }
  35429. bindSkeletons( object, skeletons ) {
  35430. if ( Object.keys( skeletons ).length === 0 ) return;
  35431. object.traverse( function ( child ) {
  35432. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35433. const skeleton = skeletons[ child.skeleton ];
  35434. if ( skeleton === undefined ) {
  35435. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35436. } else {
  35437. child.bind( skeleton, child.bindMatrix );
  35438. }
  35439. }
  35440. } );
  35441. }
  35442. bindLightTargets( object ) {
  35443. object.traverse( function ( child ) {
  35444. if ( child.isDirectionalLight || child.isSpotLight ) {
  35445. const uuid = child.target;
  35446. const target = object.getObjectByProperty( 'uuid', uuid );
  35447. if ( target !== undefined ) {
  35448. child.target = target;
  35449. } else {
  35450. child.target = new Object3D();
  35451. }
  35452. }
  35453. } );
  35454. }
  35455. }
  35456. const TEXTURE_MAPPING = {
  35457. UVMapping: UVMapping,
  35458. CubeReflectionMapping: CubeReflectionMapping,
  35459. CubeRefractionMapping: CubeRefractionMapping,
  35460. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35461. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35462. CubeUVReflectionMapping: CubeUVReflectionMapping
  35463. };
  35464. const TEXTURE_WRAPPING = {
  35465. RepeatWrapping: RepeatWrapping,
  35466. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35467. MirroredRepeatWrapping: MirroredRepeatWrapping
  35468. };
  35469. const TEXTURE_FILTER = {
  35470. NearestFilter: NearestFilter,
  35471. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35472. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35473. LinearFilter: LinearFilter,
  35474. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35475. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35476. };
  35477. const _errorMap = new WeakMap();
  35478. /**
  35479. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35480. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35481. * textures for rendering.
  35482. *
  35483. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35484. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35485. *
  35486. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35487. *
  35488. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35489. *
  35490. * ```js
  35491. * const loader = new THREE.ImageBitmapLoader();
  35492. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35493. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35494. *
  35495. * const texture = new THREE.Texture( imageBitmap );
  35496. * texture.needsUpdate = true;
  35497. * ```
  35498. *
  35499. * @augments Loader
  35500. */
  35501. class ImageBitmapLoader extends Loader {
  35502. /**
  35503. * Constructs a new image bitmap loader.
  35504. *
  35505. * @param {LoadingManager} [manager] - The loading manager.
  35506. */
  35507. constructor( manager ) {
  35508. super( manager );
  35509. /**
  35510. * This flag can be used for type testing.
  35511. *
  35512. * @type {boolean}
  35513. * @readonly
  35514. * @default true
  35515. */
  35516. this.isImageBitmapLoader = true;
  35517. if ( typeof createImageBitmap === 'undefined' ) {
  35518. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35519. }
  35520. if ( typeof fetch === 'undefined' ) {
  35521. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35522. }
  35523. /**
  35524. * Represents the loader options.
  35525. *
  35526. * @type {Object}
  35527. * @default {premultiplyAlpha:'none'}
  35528. */
  35529. this.options = { premultiplyAlpha: 'none' };
  35530. /**
  35531. * Used for aborting requests.
  35532. *
  35533. * @private
  35534. * @type {AbortController}
  35535. */
  35536. this._abortController = new AbortController();
  35537. }
  35538. /**
  35539. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35540. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35541. *
  35542. * @param {Object} options - The loader options to set.
  35543. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35544. */
  35545. setOptions( options ) {
  35546. this.options = options;
  35547. return this;
  35548. }
  35549. /**
  35550. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35551. *
  35552. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35553. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35554. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35555. * @param {onErrorCallback} onError - Executed when errors occur.
  35556. * @return {ImageBitmap|undefined} The image bitmap.
  35557. */
  35558. load( url, onLoad, onProgress, onError ) {
  35559. if ( url === undefined ) url = '';
  35560. if ( this.path !== undefined ) url = this.path + url;
  35561. url = this.manager.resolveURL( url );
  35562. const scope = this;
  35563. const cached = Cache.get( `image-bitmap:${url}` );
  35564. if ( cached !== undefined ) {
  35565. scope.manager.itemStart( url );
  35566. // If cached is a promise, wait for it to resolve
  35567. if ( cached.then ) {
  35568. cached.then( imageBitmap => {
  35569. // check if there is an error for the cached promise
  35570. if ( _errorMap.has( cached ) === true ) {
  35571. if ( onError ) onError( _errorMap.get( cached ) );
  35572. scope.manager.itemError( url );
  35573. scope.manager.itemEnd( url );
  35574. } else {
  35575. if ( onLoad ) onLoad( imageBitmap );
  35576. scope.manager.itemEnd( url );
  35577. return imageBitmap;
  35578. }
  35579. } );
  35580. return;
  35581. }
  35582. // If cached is not a promise (i.e., it's already an imageBitmap)
  35583. setTimeout( function () {
  35584. if ( onLoad ) onLoad( cached );
  35585. scope.manager.itemEnd( url );
  35586. }, 0 );
  35587. return cached;
  35588. }
  35589. const fetchOptions = {};
  35590. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35591. fetchOptions.headers = this.requestHeader;
  35592. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35593. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35594. return res.blob();
  35595. } ).then( function ( blob ) {
  35596. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35597. } ).then( function ( imageBitmap ) {
  35598. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35599. if ( onLoad ) onLoad( imageBitmap );
  35600. scope.manager.itemEnd( url );
  35601. return imageBitmap;
  35602. } ).catch( function ( e ) {
  35603. if ( onError ) onError( e );
  35604. _errorMap.set( promise, e );
  35605. Cache.remove( `image-bitmap:${url}` );
  35606. scope.manager.itemError( url );
  35607. scope.manager.itemEnd( url );
  35608. } );
  35609. Cache.add( `image-bitmap:${url}`, promise );
  35610. scope.manager.itemStart( url );
  35611. }
  35612. /**
  35613. * Aborts ongoing fetch requests.
  35614. *
  35615. * @return {ImageBitmapLoader} A reference to this instance.
  35616. */
  35617. abort() {
  35618. this._abortController.abort();
  35619. this._abortController = new AbortController();
  35620. return this;
  35621. }
  35622. }
  35623. let _context;
  35624. /**
  35625. * Manages the global audio context in the engine.
  35626. *
  35627. * @hideconstructor
  35628. */
  35629. class AudioContext {
  35630. /**
  35631. * Returns the global native audio context.
  35632. *
  35633. * @return {AudioContext} The native audio context.
  35634. */
  35635. static getContext() {
  35636. if ( _context === undefined ) {
  35637. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35638. }
  35639. return _context;
  35640. }
  35641. /**
  35642. * Allows to set the global native audio context from outside.
  35643. *
  35644. * @param {AudioContext} value - The native context to set.
  35645. */
  35646. static setContext( value ) {
  35647. _context = value;
  35648. }
  35649. }
  35650. /**
  35651. * Class for loading audio buffers. Audios are internally
  35652. * loaded via {@link FileLoader}.
  35653. *
  35654. * ```js
  35655. * const audioListener = new THREE.AudioListener();
  35656. * const ambientSound = new THREE.Audio( audioListener );
  35657. *
  35658. * const loader = new THREE.AudioLoader();
  35659. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35660. *
  35661. * ambientSound.setBuffer( audioBuffer );
  35662. * ambientSound.play();
  35663. * ```
  35664. *
  35665. * @augments Loader
  35666. */
  35667. class AudioLoader extends Loader {
  35668. /**
  35669. * Constructs a new audio loader.
  35670. *
  35671. * @param {LoadingManager} [manager] - The loading manager.
  35672. */
  35673. constructor( manager ) {
  35674. super( manager );
  35675. }
  35676. /**
  35677. * Starts loading from the given URL and passes the loaded audio buffer
  35678. * to the `onLoad()` callback.
  35679. *
  35680. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35681. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35682. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35683. * @param {onErrorCallback} onError - Executed when errors occur.
  35684. */
  35685. load( url, onLoad, onProgress, onError ) {
  35686. const scope = this;
  35687. const loader = new FileLoader( this.manager );
  35688. loader.setResponseType( 'arraybuffer' );
  35689. loader.setPath( this.path );
  35690. loader.setRequestHeader( this.requestHeader );
  35691. loader.setWithCredentials( this.withCredentials );
  35692. loader.load( url, function ( buffer ) {
  35693. try {
  35694. // Create a copy of the buffer. The `decodeAudioData` method
  35695. // detaches the buffer when complete, preventing reuse.
  35696. const bufferCopy = buffer.slice( 0 );
  35697. const context = AudioContext.getContext();
  35698. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35699. onLoad( audioBuffer );
  35700. } ).catch( handleError );
  35701. } catch ( e ) {
  35702. handleError( e );
  35703. }
  35704. }, onProgress, onError );
  35705. function handleError( e ) {
  35706. if ( onError ) {
  35707. onError( e );
  35708. } else {
  35709. console.error( e );
  35710. }
  35711. scope.manager.itemError( url );
  35712. }
  35713. }
  35714. }
  35715. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35716. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35717. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35718. /**
  35719. * A special type of camera that uses two perspective cameras with
  35720. * stereoscopic projection. Can be used for rendering stereo effects
  35721. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35722. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35723. */
  35724. class StereoCamera {
  35725. /**
  35726. * Constructs a new stereo camera.
  35727. */
  35728. constructor() {
  35729. /**
  35730. * The type property is used for detecting the object type
  35731. * in context of serialization/deserialization.
  35732. *
  35733. * @type {string}
  35734. * @readonly
  35735. */
  35736. this.type = 'StereoCamera';
  35737. /**
  35738. * The aspect.
  35739. *
  35740. * @type {number}
  35741. * @default 1
  35742. */
  35743. this.aspect = 1;
  35744. /**
  35745. * The eye separation which represents the distance
  35746. * between the left and right camera.
  35747. *
  35748. * @type {number}
  35749. * @default 0.064
  35750. */
  35751. this.eyeSep = 0.064;
  35752. /**
  35753. * The camera representing the left eye. This is added to layer `1` so objects to be
  35754. * rendered by the left camera must also be added to this layer.
  35755. *
  35756. * @type {PerspectiveCamera}
  35757. */
  35758. this.cameraL = new PerspectiveCamera();
  35759. this.cameraL.layers.enable( 1 );
  35760. this.cameraL.matrixAutoUpdate = false;
  35761. /**
  35762. * The camera representing the right eye. This is added to layer `2` so objects to be
  35763. * rendered by the right camera must also be added to this layer.
  35764. *
  35765. * @type {PerspectiveCamera}
  35766. */
  35767. this.cameraR = new PerspectiveCamera();
  35768. this.cameraR.layers.enable( 2 );
  35769. this.cameraR.matrixAutoUpdate = false;
  35770. this._cache = {
  35771. focus: null,
  35772. fov: null,
  35773. aspect: null,
  35774. near: null,
  35775. far: null,
  35776. zoom: null,
  35777. eyeSep: null
  35778. };
  35779. }
  35780. /**
  35781. * Updates the stereo camera based on the given perspective camera.
  35782. *
  35783. * @param {PerspectiveCamera} camera - The perspective camera.
  35784. */
  35785. update( camera ) {
  35786. const cache = this._cache;
  35787. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35788. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35789. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35790. if ( needsUpdate ) {
  35791. cache.focus = camera.focus;
  35792. cache.fov = camera.fov;
  35793. cache.aspect = camera.aspect * this.aspect;
  35794. cache.near = camera.near;
  35795. cache.far = camera.far;
  35796. cache.zoom = camera.zoom;
  35797. cache.eyeSep = this.eyeSep;
  35798. // Off-axis stereoscopic effect based on
  35799. // http://paulbourke.net/stereographics/stereorender/
  35800. _projectionMatrix.copy( camera.projectionMatrix );
  35801. const eyeSepHalf = cache.eyeSep / 2;
  35802. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35803. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35804. let xmin, xmax;
  35805. // translate xOffset
  35806. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35807. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35808. // for left eye
  35809. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35810. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35811. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35812. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35813. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35814. // for right eye
  35815. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35816. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35817. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35818. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35819. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35820. }
  35821. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35822. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35823. }
  35824. }
  35825. /**
  35826. * This type of camera can be used in order to efficiently render a scene with a
  35827. * predefined set of cameras. This is an important performance aspect for
  35828. * rendering VR scenes.
  35829. *
  35830. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35831. * to define for each sub camera the `viewport` property which determines the
  35832. * part of the viewport that is rendered with this camera.
  35833. *
  35834. * @augments PerspectiveCamera
  35835. */
  35836. class ArrayCamera extends PerspectiveCamera {
  35837. /**
  35838. * Constructs a new array camera.
  35839. *
  35840. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35841. */
  35842. constructor( array = [] ) {
  35843. super();
  35844. /**
  35845. * This flag can be used for type testing.
  35846. *
  35847. * @type {boolean}
  35848. * @readonly
  35849. * @default true
  35850. */
  35851. this.isArrayCamera = true;
  35852. /**
  35853. * Whether this camera is used with multiview rendering or not.
  35854. *
  35855. * @type {boolean}
  35856. * @readonly
  35857. * @default false
  35858. */
  35859. this.isMultiViewCamera = false;
  35860. /**
  35861. * An array of perspective sub cameras.
  35862. *
  35863. * @type {Array<PerspectiveCamera>}
  35864. */
  35865. this.cameras = array;
  35866. }
  35867. }
  35868. /**
  35869. * Class for keeping track of time.
  35870. */
  35871. class Clock {
  35872. /**
  35873. * Constructs a new clock.
  35874. *
  35875. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35876. * `getDelta()` is called for the first time.
  35877. */
  35878. constructor( autoStart = true ) {
  35879. /**
  35880. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35881. * for the first time.
  35882. *
  35883. * @type {boolean}
  35884. * @default true
  35885. */
  35886. this.autoStart = autoStart;
  35887. /**
  35888. * Holds the time at which the clock's `start()` method was last called.
  35889. *
  35890. * @type {number}
  35891. * @default 0
  35892. */
  35893. this.startTime = 0;
  35894. /**
  35895. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35896. * `getDelta()` methods were last called.
  35897. *
  35898. * @type {number}
  35899. * @default 0
  35900. */
  35901. this.oldTime = 0;
  35902. /**
  35903. * Keeps track of the total time that the clock has been running.
  35904. *
  35905. * @type {number}
  35906. * @default 0
  35907. */
  35908. this.elapsedTime = 0;
  35909. /**
  35910. * Whether the clock is running or not.
  35911. *
  35912. * @type {boolean}
  35913. * @default true
  35914. */
  35915. this.running = false;
  35916. }
  35917. /**
  35918. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35919. * called by the class.
  35920. */
  35921. start() {
  35922. this.startTime = performance.now();
  35923. this.oldTime = this.startTime;
  35924. this.elapsedTime = 0;
  35925. this.running = true;
  35926. }
  35927. /**
  35928. * Stops the clock.
  35929. */
  35930. stop() {
  35931. this.getElapsedTime();
  35932. this.running = false;
  35933. this.autoStart = false;
  35934. }
  35935. /**
  35936. * Returns the elapsed time in seconds.
  35937. *
  35938. * @return {number} The elapsed time.
  35939. */
  35940. getElapsedTime() {
  35941. this.getDelta();
  35942. return this.elapsedTime;
  35943. }
  35944. /**
  35945. * Returns the delta time in seconds.
  35946. *
  35947. * @return {number} The delta time.
  35948. */
  35949. getDelta() {
  35950. let diff = 0;
  35951. if ( this.autoStart && ! this.running ) {
  35952. this.start();
  35953. return 0;
  35954. }
  35955. if ( this.running ) {
  35956. const newTime = performance.now();
  35957. diff = ( newTime - this.oldTime ) / 1000;
  35958. this.oldTime = newTime;
  35959. this.elapsedTime += diff;
  35960. }
  35961. return diff;
  35962. }
  35963. }
  35964. const _position$1 = /*@__PURE__*/ new Vector3();
  35965. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35966. const _scale$1 = /*@__PURE__*/ new Vector3();
  35967. const _forward = /*@__PURE__*/ new Vector3();
  35968. const _up = /*@__PURE__*/ new Vector3();
  35969. /**
  35970. * The class represents a virtual listener of the all positional and non-positional audio effects
  35971. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35972. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35973. *
  35974. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35975. * camera represents the 3D transformation of the listener.
  35976. *
  35977. * @augments Object3D
  35978. */
  35979. class AudioListener extends Object3D {
  35980. /**
  35981. * Constructs a new audio listener.
  35982. */
  35983. constructor() {
  35984. super();
  35985. this.type = 'AudioListener';
  35986. /**
  35987. * The native audio context.
  35988. *
  35989. * @type {AudioContext}
  35990. * @readonly
  35991. */
  35992. this.context = AudioContext.getContext();
  35993. /**
  35994. * The gain node used for volume control.
  35995. *
  35996. * @type {GainNode}
  35997. * @readonly
  35998. */
  35999. this.gain = this.context.createGain();
  36000. this.gain.connect( this.context.destination );
  36001. /**
  36002. * An optional filter.
  36003. *
  36004. * Defined via {@link AudioListener#setFilter}.
  36005. *
  36006. * @type {?AudioNode}
  36007. * @default null
  36008. * @readonly
  36009. */
  36010. this.filter = null;
  36011. /**
  36012. * Time delta values required for `linearRampToValueAtTime()` usage.
  36013. *
  36014. * @type {number}
  36015. * @default 0
  36016. * @readonly
  36017. */
  36018. this.timeDelta = 0;
  36019. // private
  36020. this._clock = new Clock();
  36021. }
  36022. /**
  36023. * Returns the listener's input node.
  36024. *
  36025. * This method is used by other audio nodes to connect to this listener.
  36026. *
  36027. * @return {GainNode} The input node.
  36028. */
  36029. getInput() {
  36030. return this.gain;
  36031. }
  36032. /**
  36033. * Removes the current filter from this listener.
  36034. *
  36035. * @return {AudioListener} A reference to this listener.
  36036. */
  36037. removeFilter() {
  36038. if ( this.filter !== null ) {
  36039. this.gain.disconnect( this.filter );
  36040. this.filter.disconnect( this.context.destination );
  36041. this.gain.connect( this.context.destination );
  36042. this.filter = null;
  36043. }
  36044. return this;
  36045. }
  36046. /**
  36047. * Returns the current set filter.
  36048. *
  36049. * @return {?AudioNode} The filter.
  36050. */
  36051. getFilter() {
  36052. return this.filter;
  36053. }
  36054. /**
  36055. * Sets the given filter to this listener.
  36056. *
  36057. * @param {AudioNode} value - The filter to set.
  36058. * @return {AudioListener} A reference to this listener.
  36059. */
  36060. setFilter( value ) {
  36061. if ( this.filter !== null ) {
  36062. this.gain.disconnect( this.filter );
  36063. this.filter.disconnect( this.context.destination );
  36064. } else {
  36065. this.gain.disconnect( this.context.destination );
  36066. }
  36067. this.filter = value;
  36068. this.gain.connect( this.filter );
  36069. this.filter.connect( this.context.destination );
  36070. return this;
  36071. }
  36072. /**
  36073. * Returns the applications master volume.
  36074. *
  36075. * @return {number} The master volume.
  36076. */
  36077. getMasterVolume() {
  36078. return this.gain.gain.value;
  36079. }
  36080. /**
  36081. * Sets the applications master volume. This volume setting affects
  36082. * all audio nodes in the scene.
  36083. *
  36084. * @param {number} value - The master volume to set.
  36085. * @return {AudioListener} A reference to this listener.
  36086. */
  36087. setMasterVolume( value ) {
  36088. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36089. return this;
  36090. }
  36091. updateMatrixWorld( force ) {
  36092. super.updateMatrixWorld( force );
  36093. const listener = this.context.listener;
  36094. this.timeDelta = this._clock.getDelta();
  36095. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36096. // the initial forward and up directions must be orthogonal
  36097. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36098. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36099. if ( listener.positionX ) {
  36100. // code path for Chrome (see #14393)
  36101. const endTime = this.context.currentTime + this.timeDelta;
  36102. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36103. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36104. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36105. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36106. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36107. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36108. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36109. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36110. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36111. } else {
  36112. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36113. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36114. }
  36115. }
  36116. }
  36117. /**
  36118. * Represents a non-positional ( global ) audio object.
  36119. *
  36120. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36121. *
  36122. * ```js
  36123. * // create an AudioListener and add it to the camera
  36124. * const listener = new THREE.AudioListener();
  36125. * camera.add( listener );
  36126. *
  36127. * // create a global audio source
  36128. * const sound = new THREE.Audio( listener );
  36129. *
  36130. * // load a sound and set it as the Audio object's buffer
  36131. * const audioLoader = new THREE.AudioLoader();
  36132. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36133. * sound.setBuffer( buffer );
  36134. * sound.setLoop( true );
  36135. * sound.setVolume( 0.5 );
  36136. * sound.play();
  36137. * });
  36138. * ```
  36139. *
  36140. * @augments Object3D
  36141. */
  36142. class Audio extends Object3D {
  36143. /**
  36144. * Constructs a new audio.
  36145. *
  36146. * @param {AudioListener} listener - The global audio listener.
  36147. */
  36148. constructor( listener ) {
  36149. super();
  36150. this.type = 'Audio';
  36151. /**
  36152. * The global audio listener.
  36153. *
  36154. * @type {AudioListener}
  36155. * @readonly
  36156. */
  36157. this.listener = listener;
  36158. /**
  36159. * The audio context.
  36160. *
  36161. * @type {AudioContext}
  36162. * @readonly
  36163. */
  36164. this.context = listener.context;
  36165. /**
  36166. * The gain node used for volume control.
  36167. *
  36168. * @type {GainNode}
  36169. * @readonly
  36170. */
  36171. this.gain = this.context.createGain();
  36172. this.gain.connect( listener.getInput() );
  36173. /**
  36174. * Whether to start playback automatically or not.
  36175. *
  36176. * @type {boolean}
  36177. * @default false
  36178. */
  36179. this.autoplay = false;
  36180. /**
  36181. * A reference to an audio buffer.
  36182. *
  36183. * Defined via {@link Audio#setBuffer}.
  36184. *
  36185. * @type {?AudioBuffer}
  36186. * @default null
  36187. * @readonly
  36188. */
  36189. this.buffer = null;
  36190. /**
  36191. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36192. * +/- 1200 is an octave.
  36193. *
  36194. * Defined via {@link Audio#setDetune}.
  36195. *
  36196. * @type {number}
  36197. * @default 0
  36198. * @readonly
  36199. */
  36200. this.detune = 0;
  36201. /**
  36202. * Whether the audio should loop or not.
  36203. *
  36204. * Defined via {@link Audio#setLoop}.
  36205. *
  36206. * @type {boolean}
  36207. * @default false
  36208. * @readonly
  36209. */
  36210. this.loop = false;
  36211. /**
  36212. * Defines where in the audio buffer the replay should
  36213. * start, in seconds.
  36214. *
  36215. * @type {number}
  36216. * @default 0
  36217. */
  36218. this.loopStart = 0;
  36219. /**
  36220. * Defines where in the audio buffer the replay should
  36221. * stop, in seconds.
  36222. *
  36223. * @type {number}
  36224. * @default 0
  36225. */
  36226. this.loopEnd = 0;
  36227. /**
  36228. * An offset to the time within the audio buffer the playback
  36229. * should begin, in seconds.
  36230. *
  36231. * @type {number}
  36232. * @default 0
  36233. */
  36234. this.offset = 0;
  36235. /**
  36236. * Overrides the default duration of the audio.
  36237. *
  36238. * @type {undefined|number}
  36239. * @default undefined
  36240. */
  36241. this.duration = undefined;
  36242. /**
  36243. * The playback speed.
  36244. *
  36245. * Defined via {@link Audio#setPlaybackRate}.
  36246. *
  36247. * @type {number}
  36248. * @readonly
  36249. * @default 1
  36250. */
  36251. this.playbackRate = 1;
  36252. /**
  36253. * Indicates whether the audio is playing or not.
  36254. *
  36255. * This flag will be automatically set when using {@link Audio#play},
  36256. * {@link Audio#pause}, {@link Audio#stop}.
  36257. *
  36258. * @type {boolean}
  36259. * @readonly
  36260. * @default false
  36261. */
  36262. this.isPlaying = false;
  36263. /**
  36264. * Indicates whether the audio playback can be controlled
  36265. * with method like {@link Audio#play} or {@link Audio#pause}.
  36266. *
  36267. * This flag will be automatically set when audio sources are
  36268. * defined.
  36269. *
  36270. * @type {boolean}
  36271. * @readonly
  36272. * @default true
  36273. */
  36274. this.hasPlaybackControl = true;
  36275. /**
  36276. * Holds a reference to the current audio source.
  36277. *
  36278. * The property is automatically by one of the `set*()` methods.
  36279. *
  36280. * @type {?AudioNode}
  36281. * @readonly
  36282. * @default null
  36283. */
  36284. this.source = null;
  36285. /**
  36286. * Defines the source type.
  36287. *
  36288. * The property is automatically by one of the `set*()` methods.
  36289. *
  36290. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36291. * @readonly
  36292. * @default 'empty'
  36293. */
  36294. this.sourceType = 'empty';
  36295. this._startedAt = 0;
  36296. this._progress = 0;
  36297. this._connected = false;
  36298. /**
  36299. * Can be used to apply a variety of low-order filters to create
  36300. * more complex sound effects e.g. via `BiquadFilterNode`.
  36301. *
  36302. * The property is automatically set by {@link Audio#setFilters}.
  36303. *
  36304. * @type {Array<AudioNode>}
  36305. * @readonly
  36306. */
  36307. this.filters = [];
  36308. }
  36309. /**
  36310. * Returns the output audio node.
  36311. *
  36312. * @return {GainNode} The output node.
  36313. */
  36314. getOutput() {
  36315. return this.gain;
  36316. }
  36317. /**
  36318. * Sets the given audio node as the source of this instance.
  36319. *
  36320. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36321. *
  36322. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36323. * @return {Audio} A reference to this instance.
  36324. */
  36325. setNodeSource( audioNode ) {
  36326. this.hasPlaybackControl = false;
  36327. this.sourceType = 'audioNode';
  36328. this.source = audioNode;
  36329. this.connect();
  36330. return this;
  36331. }
  36332. /**
  36333. * Sets the given media element as the source of this instance.
  36334. *
  36335. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36336. *
  36337. * @param {HTMLMediaElement} mediaElement - The media element.
  36338. * @return {Audio} A reference to this instance.
  36339. */
  36340. setMediaElementSource( mediaElement ) {
  36341. this.hasPlaybackControl = false;
  36342. this.sourceType = 'mediaNode';
  36343. this.source = this.context.createMediaElementSource( mediaElement );
  36344. this.connect();
  36345. return this;
  36346. }
  36347. /**
  36348. * Sets the given media stream as the source of this instance.
  36349. *
  36350. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36351. *
  36352. * @param {MediaStream} mediaStream - The media stream.
  36353. * @return {Audio} A reference to this instance.
  36354. */
  36355. setMediaStreamSource( mediaStream ) {
  36356. this.hasPlaybackControl = false;
  36357. this.sourceType = 'mediaStreamNode';
  36358. this.source = this.context.createMediaStreamSource( mediaStream );
  36359. this.connect();
  36360. return this;
  36361. }
  36362. /**
  36363. * Sets the given audio buffer as the source of this instance.
  36364. *
  36365. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36366. *
  36367. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36368. * @return {Audio} A reference to this instance.
  36369. */
  36370. setBuffer( audioBuffer ) {
  36371. this.buffer = audioBuffer;
  36372. this.sourceType = 'buffer';
  36373. if ( this.autoplay ) this.play();
  36374. return this;
  36375. }
  36376. /**
  36377. * Starts the playback of the audio.
  36378. *
  36379. * Can only be used with compatible audio sources that allow playback control.
  36380. *
  36381. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36382. * @return {Audio|undefined} A reference to this instance.
  36383. */
  36384. play( delay = 0 ) {
  36385. if ( this.isPlaying === true ) {
  36386. console.warn( 'THREE.Audio: Audio is already playing.' );
  36387. return;
  36388. }
  36389. if ( this.hasPlaybackControl === false ) {
  36390. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36391. return;
  36392. }
  36393. this._startedAt = this.context.currentTime + delay;
  36394. const source = this.context.createBufferSource();
  36395. source.buffer = this.buffer;
  36396. source.loop = this.loop;
  36397. source.loopStart = this.loopStart;
  36398. source.loopEnd = this.loopEnd;
  36399. source.onended = this.onEnded.bind( this );
  36400. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36401. this.isPlaying = true;
  36402. this.source = source;
  36403. this.setDetune( this.detune );
  36404. this.setPlaybackRate( this.playbackRate );
  36405. return this.connect();
  36406. }
  36407. /**
  36408. * Pauses the playback of the audio.
  36409. *
  36410. * Can only be used with compatible audio sources that allow playback control.
  36411. *
  36412. * @return {Audio|undefined} A reference to this instance.
  36413. */
  36414. pause() {
  36415. if ( this.hasPlaybackControl === false ) {
  36416. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36417. return;
  36418. }
  36419. if ( this.isPlaying === true ) {
  36420. // update current progress
  36421. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36422. if ( this.loop === true ) {
  36423. // ensure _progress does not exceed duration with looped audios
  36424. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36425. }
  36426. this.source.stop();
  36427. this.source.onended = null;
  36428. this.isPlaying = false;
  36429. }
  36430. return this;
  36431. }
  36432. /**
  36433. * Stops the playback of the audio.
  36434. *
  36435. * Can only be used with compatible audio sources that allow playback control.
  36436. *
  36437. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36438. * @return {Audio|undefined} A reference to this instance.
  36439. */
  36440. stop( delay = 0 ) {
  36441. if ( this.hasPlaybackControl === false ) {
  36442. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36443. return;
  36444. }
  36445. this._progress = 0;
  36446. if ( this.source !== null ) {
  36447. this.source.stop( this.context.currentTime + delay );
  36448. this.source.onended = null;
  36449. }
  36450. this.isPlaying = false;
  36451. return this;
  36452. }
  36453. /**
  36454. * Connects to the audio source. This is used internally on
  36455. * initialisation and when setting / removing filters.
  36456. *
  36457. * @return {Audio} A reference to this instance.
  36458. */
  36459. connect() {
  36460. if ( this.filters.length > 0 ) {
  36461. this.source.connect( this.filters[ 0 ] );
  36462. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36463. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36464. }
  36465. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36466. } else {
  36467. this.source.connect( this.getOutput() );
  36468. }
  36469. this._connected = true;
  36470. return this;
  36471. }
  36472. /**
  36473. * Disconnects to the audio source. This is used internally on
  36474. * initialisation and when setting / removing filters.
  36475. *
  36476. * @return {Audio|undefined} A reference to this instance.
  36477. */
  36478. disconnect() {
  36479. if ( this._connected === false ) {
  36480. return;
  36481. }
  36482. if ( this.filters.length > 0 ) {
  36483. this.source.disconnect( this.filters[ 0 ] );
  36484. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36485. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36486. }
  36487. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36488. } else {
  36489. this.source.disconnect( this.getOutput() );
  36490. }
  36491. this._connected = false;
  36492. return this;
  36493. }
  36494. /**
  36495. * Returns the current set filters.
  36496. *
  36497. * @return {Array<AudioNode>} The list of filters.
  36498. */
  36499. getFilters() {
  36500. return this.filters;
  36501. }
  36502. /**
  36503. * Sets an array of filters and connects them with the audio source.
  36504. *
  36505. * @param {Array<AudioNode>} [value] - A list of filters.
  36506. * @return {Audio} A reference to this instance.
  36507. */
  36508. setFilters( value ) {
  36509. if ( ! value ) value = [];
  36510. if ( this._connected === true ) {
  36511. this.disconnect();
  36512. this.filters = value.slice();
  36513. this.connect();
  36514. } else {
  36515. this.filters = value.slice();
  36516. }
  36517. return this;
  36518. }
  36519. /**
  36520. * Defines the detuning of oscillation in cents.
  36521. *
  36522. * @param {number} value - The detuning of oscillation in cents.
  36523. * @return {Audio} A reference to this instance.
  36524. */
  36525. setDetune( value ) {
  36526. this.detune = value;
  36527. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36528. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36529. }
  36530. return this;
  36531. }
  36532. /**
  36533. * Returns the detuning of oscillation in cents.
  36534. *
  36535. * @return {number} The detuning of oscillation in cents.
  36536. */
  36537. getDetune() {
  36538. return this.detune;
  36539. }
  36540. /**
  36541. * Returns the first filter in the list of filters.
  36542. *
  36543. * @return {AudioNode|undefined} The first filter in the list of filters.
  36544. */
  36545. getFilter() {
  36546. return this.getFilters()[ 0 ];
  36547. }
  36548. /**
  36549. * Applies a single filter node to the audio.
  36550. *
  36551. * @param {AudioNode} [filter] - The filter to set.
  36552. * @return {Audio} A reference to this instance.
  36553. */
  36554. setFilter( filter ) {
  36555. return this.setFilters( filter ? [ filter ] : [] );
  36556. }
  36557. /**
  36558. * Sets the playback rate.
  36559. *
  36560. * Can only be used with compatible audio sources that allow playback control.
  36561. *
  36562. * @param {number} [value] - The playback rate to set.
  36563. * @return {Audio|undefined} A reference to this instance.
  36564. */
  36565. setPlaybackRate( value ) {
  36566. if ( this.hasPlaybackControl === false ) {
  36567. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36568. return;
  36569. }
  36570. this.playbackRate = value;
  36571. if ( this.isPlaying === true ) {
  36572. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36573. }
  36574. return this;
  36575. }
  36576. /**
  36577. * Returns the current playback rate.
  36578. * @return {number} The playback rate.
  36579. */
  36580. getPlaybackRate() {
  36581. return this.playbackRate;
  36582. }
  36583. /**
  36584. * Automatically called when playback finished.
  36585. */
  36586. onEnded() {
  36587. this.isPlaying = false;
  36588. this._progress = 0;
  36589. }
  36590. /**
  36591. * Returns the loop flag.
  36592. *
  36593. * Can only be used with compatible audio sources that allow playback control.
  36594. *
  36595. * @return {boolean} Whether the audio should loop or not.
  36596. */
  36597. getLoop() {
  36598. if ( this.hasPlaybackControl === false ) {
  36599. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36600. return false;
  36601. }
  36602. return this.loop;
  36603. }
  36604. /**
  36605. * Sets the loop flag.
  36606. *
  36607. * Can only be used with compatible audio sources that allow playback control.
  36608. *
  36609. * @param {boolean} value - Whether the audio should loop or not.
  36610. * @return {Audio|undefined} A reference to this instance.
  36611. */
  36612. setLoop( value ) {
  36613. if ( this.hasPlaybackControl === false ) {
  36614. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36615. return;
  36616. }
  36617. this.loop = value;
  36618. if ( this.isPlaying === true ) {
  36619. this.source.loop = this.loop;
  36620. }
  36621. return this;
  36622. }
  36623. /**
  36624. * Sets the loop start value which defines where in the audio buffer the replay should
  36625. * start, in seconds.
  36626. *
  36627. * @param {number} value - The loop start value.
  36628. * @return {Audio} A reference to this instance.
  36629. */
  36630. setLoopStart( value ) {
  36631. this.loopStart = value;
  36632. return this;
  36633. }
  36634. /**
  36635. * Sets the loop end value which defines where in the audio buffer the replay should
  36636. * stop, in seconds.
  36637. *
  36638. * @param {number} value - The loop end value.
  36639. * @return {Audio} A reference to this instance.
  36640. */
  36641. setLoopEnd( value ) {
  36642. this.loopEnd = value;
  36643. return this;
  36644. }
  36645. /**
  36646. * Returns the volume.
  36647. *
  36648. * @return {number} The volume.
  36649. */
  36650. getVolume() {
  36651. return this.gain.gain.value;
  36652. }
  36653. /**
  36654. * Sets the volume.
  36655. *
  36656. * @param {number} value - The volume to set.
  36657. * @return {Audio} A reference to this instance.
  36658. */
  36659. setVolume( value ) {
  36660. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36661. return this;
  36662. }
  36663. copy( source, recursive ) {
  36664. super.copy( source, recursive );
  36665. if ( source.sourceType !== 'buffer' ) {
  36666. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36667. return this;
  36668. }
  36669. this.autoplay = source.autoplay;
  36670. this.buffer = source.buffer;
  36671. this.detune = source.detune;
  36672. this.loop = source.loop;
  36673. this.loopStart = source.loopStart;
  36674. this.loopEnd = source.loopEnd;
  36675. this.offset = source.offset;
  36676. this.duration = source.duration;
  36677. this.playbackRate = source.playbackRate;
  36678. this.hasPlaybackControl = source.hasPlaybackControl;
  36679. this.sourceType = source.sourceType;
  36680. this.filters = source.filters.slice();
  36681. return this;
  36682. }
  36683. clone( recursive ) {
  36684. return new this.constructor( this.listener ).copy( this, recursive );
  36685. }
  36686. }
  36687. const _position = /*@__PURE__*/ new Vector3();
  36688. const _quaternion = /*@__PURE__*/ new Quaternion();
  36689. const _scale = /*@__PURE__*/ new Vector3();
  36690. const _orientation = /*@__PURE__*/ new Vector3();
  36691. /**
  36692. * Represents a positional audio object.
  36693. *
  36694. * ```js
  36695. * // create an AudioListener and add it to the camera
  36696. * const listener = new THREE.AudioListener();
  36697. * camera.add( listener );
  36698. *
  36699. * // create the PositionalAudio object (passing in the listener)
  36700. * const sound = new THREE.PositionalAudio( listener );
  36701. *
  36702. * // load a sound and set it as the PositionalAudio object's buffer
  36703. * const audioLoader = new THREE.AudioLoader();
  36704. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36705. * sound.setBuffer( buffer );
  36706. * sound.setRefDistance( 20 );
  36707. * sound.play();
  36708. * });
  36709. *
  36710. * // create an object for the sound to play from
  36711. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36712. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36713. * const mesh = new THREE.Mesh( sphere, material );
  36714. * scene.add( mesh );
  36715. *
  36716. * // finally add the sound to the mesh
  36717. * mesh.add( sound );
  36718. *
  36719. * @augments Audio
  36720. */
  36721. class PositionalAudio extends Audio {
  36722. /**
  36723. * Constructs a positional audio.
  36724. *
  36725. * @param {AudioListener} listener - The global audio listener.
  36726. */
  36727. constructor( listener ) {
  36728. super( listener );
  36729. /**
  36730. * The panner node represents the location, direction, and behavior of an audio
  36731. * source in 3D space.
  36732. *
  36733. * @type {PannerNode}
  36734. * @readonly
  36735. */
  36736. this.panner = this.context.createPanner();
  36737. this.panner.panningModel = 'HRTF';
  36738. this.panner.connect( this.gain );
  36739. }
  36740. connect() {
  36741. super.connect();
  36742. this.panner.connect( this.gain );
  36743. return this;
  36744. }
  36745. disconnect() {
  36746. super.disconnect();
  36747. this.panner.disconnect( this.gain );
  36748. return this;
  36749. }
  36750. getOutput() {
  36751. return this.panner;
  36752. }
  36753. /**
  36754. * Returns the current reference distance.
  36755. *
  36756. * @return {number} The reference distance.
  36757. */
  36758. getRefDistance() {
  36759. return this.panner.refDistance;
  36760. }
  36761. /**
  36762. * Defines the reference distance for reducing volume as the audio source moves
  36763. * further from the listener – i.e. the distance at which the volume reduction
  36764. * starts taking effect.
  36765. *
  36766. * @param {number} value - The reference distance to set.
  36767. * @return {PositionalAudio} A reference to this instance.
  36768. */
  36769. setRefDistance( value ) {
  36770. this.panner.refDistance = value;
  36771. return this;
  36772. }
  36773. /**
  36774. * Returns the current rolloff factor.
  36775. *
  36776. * @return {number} The rolloff factor.
  36777. */
  36778. getRolloffFactor() {
  36779. return this.panner.rolloffFactor;
  36780. }
  36781. /**
  36782. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36783. *
  36784. * @param {number} value - The rolloff factor.
  36785. * @return {PositionalAudio} A reference to this instance.
  36786. */
  36787. setRolloffFactor( value ) {
  36788. this.panner.rolloffFactor = value;
  36789. return this;
  36790. }
  36791. /**
  36792. * Returns the current distance model.
  36793. *
  36794. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36795. */
  36796. getDistanceModel() {
  36797. return this.panner.distanceModel;
  36798. }
  36799. /**
  36800. * Defines which algorithm to use to reduce the volume of the audio source
  36801. * as it moves away from the listener.
  36802. *
  36803. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36804. * for more details.
  36805. *
  36806. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36807. * @return {PositionalAudio} A reference to this instance.
  36808. */
  36809. setDistanceModel( value ) {
  36810. this.panner.distanceModel = value;
  36811. return this;
  36812. }
  36813. /**
  36814. * Returns the current max distance.
  36815. *
  36816. * @return {number} The max distance.
  36817. */
  36818. getMaxDistance() {
  36819. return this.panner.maxDistance;
  36820. }
  36821. /**
  36822. * Defines the maximum distance between the audio source and the listener,
  36823. * after which the volume is not reduced any further.
  36824. *
  36825. * This value is used only by the `linear` distance model.
  36826. *
  36827. * @param {number} value - The max distance.
  36828. * @return {PositionalAudio} A reference to this instance.
  36829. */
  36830. setMaxDistance( value ) {
  36831. this.panner.maxDistance = value;
  36832. return this;
  36833. }
  36834. /**
  36835. * Sets the directional cone in which the audio can be listened.
  36836. *
  36837. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36838. * @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.
  36839. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36840. * @return {PositionalAudio} A reference to this instance.
  36841. */
  36842. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36843. this.panner.coneInnerAngle = coneInnerAngle;
  36844. this.panner.coneOuterAngle = coneOuterAngle;
  36845. this.panner.coneOuterGain = coneOuterGain;
  36846. return this;
  36847. }
  36848. updateMatrixWorld( force ) {
  36849. super.updateMatrixWorld( force );
  36850. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36851. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36852. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36853. const panner = this.panner;
  36854. if ( panner.positionX ) {
  36855. // code path for Chrome and Firefox (see #14393)
  36856. const endTime = this.context.currentTime + this.listener.timeDelta;
  36857. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36858. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36859. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36860. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36861. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36862. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36863. } else {
  36864. panner.setPosition( _position.x, _position.y, _position.z );
  36865. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36866. }
  36867. }
  36868. }
  36869. /**
  36870. * This class can be used to analyse audio data.
  36871. *
  36872. * ```js
  36873. * // create an AudioListener and add it to the camera
  36874. * const listener = new THREE.AudioListener();
  36875. * camera.add( listener );
  36876. *
  36877. * // create an Audio source
  36878. * const sound = new THREE.Audio( listener );
  36879. *
  36880. * // load a sound and set it as the Audio object's buffer
  36881. * const audioLoader = new THREE.AudioLoader();
  36882. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36883. * sound.setBuffer( buffer );
  36884. * sound.setLoop(true);
  36885. * sound.setVolume(0.5);
  36886. * sound.play();
  36887. * });
  36888. *
  36889. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36890. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36891. *
  36892. * // get the average frequency of the sound
  36893. * const data = analyser.getAverageFrequency();
  36894. * ```
  36895. */
  36896. class AudioAnalyser {
  36897. /**
  36898. * Constructs a new audio analyzer.
  36899. *
  36900. * @param {Audio} audio - The audio to analyze.
  36901. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36902. */
  36903. constructor( audio, fftSize = 2048 ) {
  36904. /**
  36905. * The global audio listener.
  36906. *
  36907. * @type {AnalyserNode}
  36908. */
  36909. this.analyser = audio.context.createAnalyser();
  36910. this.analyser.fftSize = fftSize;
  36911. /**
  36912. * Holds the analyzed data.
  36913. *
  36914. * @type {Uint8Array}
  36915. */
  36916. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36917. audio.getOutput().connect( this.analyser );
  36918. }
  36919. /**
  36920. * Returns an array with frequency data of the audio.
  36921. *
  36922. * Each item in the array represents the decibel value for a specific frequency.
  36923. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36924. * For example, for 48000 sample rate, the last item of the array will represent
  36925. * the decibel value for 24000 Hz.
  36926. *
  36927. * @return {Uint8Array} The frequency data.
  36928. */
  36929. getFrequencyData() {
  36930. this.analyser.getByteFrequencyData( this.data );
  36931. return this.data;
  36932. }
  36933. /**
  36934. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36935. *
  36936. * @return {number} The average frequency.
  36937. */
  36938. getAverageFrequency() {
  36939. let value = 0;
  36940. const data = this.getFrequencyData();
  36941. for ( let i = 0; i < data.length; i ++ ) {
  36942. value += data[ i ];
  36943. }
  36944. return value / data.length;
  36945. }
  36946. }
  36947. /**
  36948. * Buffered scene graph property that allows weighted accumulation; used internally.
  36949. */
  36950. class PropertyMixer {
  36951. /**
  36952. * Constructs a new property mixer.
  36953. *
  36954. * @param {PropertyBinding} binding - The property binding.
  36955. * @param {string} typeName - The keyframe track type name.
  36956. * @param {number} valueSize - The keyframe track value size.
  36957. */
  36958. constructor( binding, typeName, valueSize ) {
  36959. /**
  36960. * The property binding.
  36961. *
  36962. * @type {PropertyBinding}
  36963. */
  36964. this.binding = binding;
  36965. /**
  36966. * The keyframe track value size.
  36967. *
  36968. * @type {number}
  36969. */
  36970. this.valueSize = valueSize;
  36971. let mixFunction,
  36972. mixFunctionAdditive,
  36973. setIdentity;
  36974. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36975. //
  36976. // interpolators can use .buffer as their .result
  36977. // the data then goes to 'incoming'
  36978. //
  36979. // 'accu0' and 'accu1' are used frame-interleaved for
  36980. // the cumulative result and are compared to detect
  36981. // changes
  36982. //
  36983. // 'orig' stores the original state of the property
  36984. //
  36985. // 'add' is used for additive cumulative results
  36986. //
  36987. // 'work' is optional and is only present for quaternion types. It is used
  36988. // to store intermediate quaternion multiplication results
  36989. switch ( typeName ) {
  36990. case 'quaternion':
  36991. mixFunction = this._slerp;
  36992. mixFunctionAdditive = this._slerpAdditive;
  36993. setIdentity = this._setAdditiveIdentityQuaternion;
  36994. this.buffer = new Float64Array( valueSize * 6 );
  36995. this._workIndex = 5;
  36996. break;
  36997. case 'string':
  36998. case 'bool':
  36999. mixFunction = this._select;
  37000. // Use the regular mix function and for additive on these types,
  37001. // additive is not relevant for non-numeric types
  37002. mixFunctionAdditive = this._select;
  37003. setIdentity = this._setAdditiveIdentityOther;
  37004. this.buffer = new Array( valueSize * 5 );
  37005. break;
  37006. default:
  37007. mixFunction = this._lerp;
  37008. mixFunctionAdditive = this._lerpAdditive;
  37009. setIdentity = this._setAdditiveIdentityNumeric;
  37010. this.buffer = new Float64Array( valueSize * 5 );
  37011. }
  37012. this._mixBufferRegion = mixFunction;
  37013. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37014. this._setIdentity = setIdentity;
  37015. this._origIndex = 3;
  37016. this._addIndex = 4;
  37017. /**
  37018. * TODO
  37019. *
  37020. * @type {number}
  37021. * @default 0
  37022. */
  37023. this.cumulativeWeight = 0;
  37024. /**
  37025. * TODO
  37026. *
  37027. * @type {number}
  37028. * @default 0
  37029. */
  37030. this.cumulativeWeightAdditive = 0;
  37031. /**
  37032. * TODO
  37033. *
  37034. * @type {number}
  37035. * @default 0
  37036. */
  37037. this.useCount = 0;
  37038. /**
  37039. * TODO
  37040. *
  37041. * @type {number}
  37042. * @default 0
  37043. */
  37044. this.referenceCount = 0;
  37045. }
  37046. /**
  37047. * Accumulates data in the `incoming` region into `accu<i>`.
  37048. *
  37049. * @param {number} accuIndex - The accumulation index.
  37050. * @param {number} weight - The weight.
  37051. */
  37052. accumulate( accuIndex, weight ) {
  37053. // note: happily accumulating nothing when weight = 0, the caller knows
  37054. // the weight and shouldn't have made the call in the first place
  37055. const buffer = this.buffer,
  37056. stride = this.valueSize,
  37057. offset = accuIndex * stride + stride;
  37058. let currentWeight = this.cumulativeWeight;
  37059. if ( currentWeight === 0 ) {
  37060. // accuN := incoming * weight
  37061. for ( let i = 0; i !== stride; ++ i ) {
  37062. buffer[ offset + i ] = buffer[ i ];
  37063. }
  37064. currentWeight = weight;
  37065. } else {
  37066. // accuN := accuN + incoming * weight
  37067. currentWeight += weight;
  37068. const mix = weight / currentWeight;
  37069. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37070. }
  37071. this.cumulativeWeight = currentWeight;
  37072. }
  37073. /**
  37074. * Accumulates data in the `incoming` region into `add`.
  37075. *
  37076. * @param {number} weight - The weight.
  37077. */
  37078. accumulateAdditive( weight ) {
  37079. const buffer = this.buffer,
  37080. stride = this.valueSize,
  37081. offset = stride * this._addIndex;
  37082. if ( this.cumulativeWeightAdditive === 0 ) {
  37083. // add = identity
  37084. this._setIdentity();
  37085. }
  37086. // add := add + incoming * weight
  37087. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37088. this.cumulativeWeightAdditive += weight;
  37089. }
  37090. /**
  37091. * Applies the state of `accu<i>` to the binding when accus differ.
  37092. *
  37093. * @param {number} accuIndex - The accumulation index.
  37094. */
  37095. apply( accuIndex ) {
  37096. const stride = this.valueSize,
  37097. buffer = this.buffer,
  37098. offset = accuIndex * stride + stride,
  37099. weight = this.cumulativeWeight,
  37100. weightAdditive = this.cumulativeWeightAdditive,
  37101. binding = this.binding;
  37102. this.cumulativeWeight = 0;
  37103. this.cumulativeWeightAdditive = 0;
  37104. if ( weight < 1 ) {
  37105. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37106. const originalValueOffset = stride * this._origIndex;
  37107. this._mixBufferRegion(
  37108. buffer, offset, originalValueOffset, 1 - weight, stride );
  37109. }
  37110. if ( weightAdditive > 0 ) {
  37111. // accuN := accuN + additive accuN
  37112. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37113. }
  37114. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37115. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37116. // value has changed -> update scene graph
  37117. binding.setValue( buffer, offset );
  37118. break;
  37119. }
  37120. }
  37121. }
  37122. /**
  37123. * Remembers the state of the bound property and copy it to both accus.
  37124. */
  37125. saveOriginalState() {
  37126. const binding = this.binding;
  37127. const buffer = this.buffer,
  37128. stride = this.valueSize,
  37129. originalValueOffset = stride * this._origIndex;
  37130. binding.getValue( buffer, originalValueOffset );
  37131. // accu[0..1] := orig -- initially detect changes against the original
  37132. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37133. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37134. }
  37135. // Add to identity for additive
  37136. this._setIdentity();
  37137. this.cumulativeWeight = 0;
  37138. this.cumulativeWeightAdditive = 0;
  37139. }
  37140. /**
  37141. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37142. */
  37143. restoreOriginalState() {
  37144. const originalValueOffset = this.valueSize * 3;
  37145. this.binding.setValue( this.buffer, originalValueOffset );
  37146. }
  37147. // internals
  37148. _setAdditiveIdentityNumeric() {
  37149. const startIndex = this._addIndex * this.valueSize;
  37150. const endIndex = startIndex + this.valueSize;
  37151. for ( let i = startIndex; i < endIndex; i ++ ) {
  37152. this.buffer[ i ] = 0;
  37153. }
  37154. }
  37155. _setAdditiveIdentityQuaternion() {
  37156. this._setAdditiveIdentityNumeric();
  37157. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37158. }
  37159. _setAdditiveIdentityOther() {
  37160. const startIndex = this._origIndex * this.valueSize;
  37161. const targetIndex = this._addIndex * this.valueSize;
  37162. for ( let i = 0; i < this.valueSize; i ++ ) {
  37163. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37164. }
  37165. }
  37166. // mix functions
  37167. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37168. if ( t >= 0.5 ) {
  37169. for ( let i = 0; i !== stride; ++ i ) {
  37170. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37171. }
  37172. }
  37173. }
  37174. _slerp( buffer, dstOffset, srcOffset, t ) {
  37175. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37176. }
  37177. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37178. const workOffset = this._workIndex * stride;
  37179. // Store result in intermediate buffer offset
  37180. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37181. // Slerp to the intermediate result
  37182. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37183. }
  37184. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37185. const s = 1 - t;
  37186. for ( let i = 0; i !== stride; ++ i ) {
  37187. const j = dstOffset + i;
  37188. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37189. }
  37190. }
  37191. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37192. for ( let i = 0; i !== stride; ++ i ) {
  37193. const j = dstOffset + i;
  37194. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37195. }
  37196. }
  37197. }
  37198. // Characters [].:/ are reserved for track binding syntax.
  37199. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37200. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37201. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37202. // only latin characters, and the unicode \p{L} is not yet supported. So
  37203. // instead, we exclude reserved characters and match everything else.
  37204. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37205. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37206. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37207. // be matched to parse the rest of the track name.
  37208. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37209. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37210. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37211. // Object on target node, and accessor. May not contain reserved
  37212. // characters. Accessor may contain any character except closing bracket.
  37213. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37214. // Property and accessor. May not contain reserved characters. Accessor may
  37215. // contain any non-bracket characters.
  37216. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37217. const _trackRe = new RegExp( ''
  37218. + '^'
  37219. + _directoryRe
  37220. + _nodeRe
  37221. + _objectRe
  37222. + _propertyRe
  37223. + '$'
  37224. );
  37225. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37226. class Composite {
  37227. constructor( targetGroup, path, optionalParsedPath ) {
  37228. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37229. this._targetGroup = targetGroup;
  37230. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37231. }
  37232. getValue( array, offset ) {
  37233. this.bind(); // bind all binding
  37234. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37235. binding = this._bindings[ firstValidIndex ];
  37236. // and only call .getValue on the first
  37237. if ( binding !== undefined ) binding.getValue( array, offset );
  37238. }
  37239. setValue( array, offset ) {
  37240. const bindings = this._bindings;
  37241. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37242. bindings[ i ].setValue( array, offset );
  37243. }
  37244. }
  37245. bind() {
  37246. const bindings = this._bindings;
  37247. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37248. bindings[ i ].bind();
  37249. }
  37250. }
  37251. unbind() {
  37252. const bindings = this._bindings;
  37253. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37254. bindings[ i ].unbind();
  37255. }
  37256. }
  37257. }
  37258. // Note: This class uses a State pattern on a per-method basis:
  37259. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37260. // prototype version of these methods with one that represents
  37261. // the bound state. When the property is not found, the methods
  37262. // become no-ops.
  37263. /**
  37264. * This holds a reference to a real property in the scene graph; used internally.
  37265. */
  37266. class PropertyBinding {
  37267. /**
  37268. * Constructs a new property binding.
  37269. *
  37270. * @param {Object} rootNode - The root node.
  37271. * @param {string} path - The path.
  37272. * @param {?Object} [parsedPath] - The parsed path.
  37273. */
  37274. constructor( rootNode, path, parsedPath ) {
  37275. /**
  37276. * The object path to the animated property.
  37277. *
  37278. * @type {string}
  37279. */
  37280. this.path = path;
  37281. /**
  37282. * An object holding information about the path.
  37283. *
  37284. * @type {Object}
  37285. */
  37286. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37287. /**
  37288. * The object owns the animated property.
  37289. *
  37290. * @type {?Object}
  37291. */
  37292. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37293. /**
  37294. * The root node.
  37295. *
  37296. * @type {Object3D|Skeleton}
  37297. */
  37298. this.rootNode = rootNode;
  37299. // initial state of these methods that calls 'bind'
  37300. this.getValue = this._getValue_unbound;
  37301. this.setValue = this._setValue_unbound;
  37302. }
  37303. /**
  37304. * Factory method for creating a property binding from the given parameters.
  37305. *
  37306. * @static
  37307. * @param {Object} root - The root node.
  37308. * @param {string} path - The path.
  37309. * @param {?Object} [parsedPath] - The parsed path.
  37310. * @return {PropertyBinding|Composite} The created property binding or composite.
  37311. */
  37312. static create( root, path, parsedPath ) {
  37313. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37314. return new PropertyBinding( root, path, parsedPath );
  37315. } else {
  37316. return new PropertyBinding.Composite( root, path, parsedPath );
  37317. }
  37318. }
  37319. /**
  37320. * Replaces spaces with underscores and removes unsupported characters from
  37321. * node names, to ensure compatibility with parseTrackName().
  37322. *
  37323. * @param {string} name - Node name to be sanitized.
  37324. * @return {string} The sanitized node name.
  37325. */
  37326. static sanitizeNodeName( name ) {
  37327. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37328. }
  37329. /**
  37330. * Parses the given track name (an object path to an animated property) and
  37331. * returns an object with information about the path. Matches strings in the following forms:
  37332. *
  37333. * - nodeName.property
  37334. * - nodeName.property[accessor]
  37335. * - nodeName.material.property[accessor]
  37336. * - uuid.property[accessor]
  37337. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37338. * - parentName/nodeName.property
  37339. * - parentName/parentName/nodeName.property[index]
  37340. * - .bone[Armature.DEF_cog].position
  37341. * - scene:helium_balloon_model:helium_balloon_model.position
  37342. *
  37343. * @static
  37344. * @param {string} trackName - The track name to parse.
  37345. * @return {Object} The parsed track name as an object.
  37346. */
  37347. static parseTrackName( trackName ) {
  37348. const matches = _trackRe.exec( trackName );
  37349. if ( matches === null ) {
  37350. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37351. }
  37352. const results = {
  37353. // directoryName: matches[ 1 ], // (tschw) currently unused
  37354. nodeName: matches[ 2 ],
  37355. objectName: matches[ 3 ],
  37356. objectIndex: matches[ 4 ],
  37357. propertyName: matches[ 5 ], // required
  37358. propertyIndex: matches[ 6 ]
  37359. };
  37360. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37361. if ( lastDot !== undefined && lastDot !== -1 ) {
  37362. const objectName = results.nodeName.substring( lastDot + 1 );
  37363. // Object names must be checked against an allowlist. Otherwise, there
  37364. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37365. // 'bar' could be the objectName, or part of a nodeName (which can
  37366. // include '.' characters).
  37367. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37368. results.nodeName = results.nodeName.substring( 0, lastDot );
  37369. results.objectName = objectName;
  37370. }
  37371. }
  37372. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37373. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37374. }
  37375. return results;
  37376. }
  37377. /**
  37378. * Searches for a node in the hierarchy of the given root object by the given
  37379. * node name.
  37380. *
  37381. * @static
  37382. * @param {Object} root - The root object.
  37383. * @param {string|number} nodeName - The name of the node.
  37384. * @return {?Object} The found node. Returns `null` if no object was found.
  37385. */
  37386. static findNode( root, nodeName ) {
  37387. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37388. return root;
  37389. }
  37390. // search into skeleton bones.
  37391. if ( root.skeleton ) {
  37392. const bone = root.skeleton.getBoneByName( nodeName );
  37393. if ( bone !== undefined ) {
  37394. return bone;
  37395. }
  37396. }
  37397. // search into node subtree.
  37398. if ( root.children ) {
  37399. const searchNodeSubtree = function ( children ) {
  37400. for ( let i = 0; i < children.length; i ++ ) {
  37401. const childNode = children[ i ];
  37402. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37403. return childNode;
  37404. }
  37405. const result = searchNodeSubtree( childNode.children );
  37406. if ( result ) return result;
  37407. }
  37408. return null;
  37409. };
  37410. const subTreeNode = searchNodeSubtree( root.children );
  37411. if ( subTreeNode ) {
  37412. return subTreeNode;
  37413. }
  37414. }
  37415. return null;
  37416. }
  37417. // these are used to "bind" a nonexistent property
  37418. _getValue_unavailable() {}
  37419. _setValue_unavailable() {}
  37420. // Getters
  37421. _getValue_direct( buffer, offset ) {
  37422. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37423. }
  37424. _getValue_array( buffer, offset ) {
  37425. const source = this.resolvedProperty;
  37426. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37427. buffer[ offset ++ ] = source[ i ];
  37428. }
  37429. }
  37430. _getValue_arrayElement( buffer, offset ) {
  37431. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37432. }
  37433. _getValue_toArray( buffer, offset ) {
  37434. this.resolvedProperty.toArray( buffer, offset );
  37435. }
  37436. // Direct
  37437. _setValue_direct( buffer, offset ) {
  37438. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37439. }
  37440. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37441. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37442. this.targetObject.needsUpdate = true;
  37443. }
  37444. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37445. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37446. this.targetObject.matrixWorldNeedsUpdate = true;
  37447. }
  37448. // EntireArray
  37449. _setValue_array( buffer, offset ) {
  37450. const dest = this.resolvedProperty;
  37451. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37452. dest[ i ] = buffer[ offset ++ ];
  37453. }
  37454. }
  37455. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37456. const dest = this.resolvedProperty;
  37457. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37458. dest[ i ] = buffer[ offset ++ ];
  37459. }
  37460. this.targetObject.needsUpdate = true;
  37461. }
  37462. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37463. const dest = this.resolvedProperty;
  37464. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37465. dest[ i ] = buffer[ offset ++ ];
  37466. }
  37467. this.targetObject.matrixWorldNeedsUpdate = true;
  37468. }
  37469. // ArrayElement
  37470. _setValue_arrayElement( buffer, offset ) {
  37471. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37472. }
  37473. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37474. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37475. this.targetObject.needsUpdate = true;
  37476. }
  37477. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37478. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37479. this.targetObject.matrixWorldNeedsUpdate = true;
  37480. }
  37481. // HasToFromArray
  37482. _setValue_fromArray( buffer, offset ) {
  37483. this.resolvedProperty.fromArray( buffer, offset );
  37484. }
  37485. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37486. this.resolvedProperty.fromArray( buffer, offset );
  37487. this.targetObject.needsUpdate = true;
  37488. }
  37489. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37490. this.resolvedProperty.fromArray( buffer, offset );
  37491. this.targetObject.matrixWorldNeedsUpdate = true;
  37492. }
  37493. _getValue_unbound( targetArray, offset ) {
  37494. this.bind();
  37495. this.getValue( targetArray, offset );
  37496. }
  37497. _setValue_unbound( sourceArray, offset ) {
  37498. this.bind();
  37499. this.setValue( sourceArray, offset );
  37500. }
  37501. /**
  37502. * Creates a getter / setter pair for the property tracked by this binding.
  37503. */
  37504. bind() {
  37505. let targetObject = this.node;
  37506. const parsedPath = this.parsedPath;
  37507. const objectName = parsedPath.objectName;
  37508. const propertyName = parsedPath.propertyName;
  37509. let propertyIndex = parsedPath.propertyIndex;
  37510. if ( ! targetObject ) {
  37511. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37512. this.node = targetObject;
  37513. }
  37514. // set fail state so we can just 'return' on error
  37515. this.getValue = this._getValue_unavailable;
  37516. this.setValue = this._setValue_unavailable;
  37517. // ensure there is a value node
  37518. if ( ! targetObject ) {
  37519. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37520. return;
  37521. }
  37522. if ( objectName ) {
  37523. let objectIndex = parsedPath.objectIndex;
  37524. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37525. switch ( objectName ) {
  37526. case 'materials':
  37527. if ( ! targetObject.material ) {
  37528. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37529. return;
  37530. }
  37531. if ( ! targetObject.material.materials ) {
  37532. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37533. return;
  37534. }
  37535. targetObject = targetObject.material.materials;
  37536. break;
  37537. case 'bones':
  37538. if ( ! targetObject.skeleton ) {
  37539. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37540. return;
  37541. }
  37542. // potential future optimization: skip this if propertyIndex is already an integer
  37543. // and convert the integer string to a true integer.
  37544. targetObject = targetObject.skeleton.bones;
  37545. // support resolving morphTarget names into indices.
  37546. for ( let i = 0; i < targetObject.length; i ++ ) {
  37547. if ( targetObject[ i ].name === objectIndex ) {
  37548. objectIndex = i;
  37549. break;
  37550. }
  37551. }
  37552. break;
  37553. case 'map':
  37554. if ( 'map' in targetObject ) {
  37555. targetObject = targetObject.map;
  37556. break;
  37557. }
  37558. if ( ! targetObject.material ) {
  37559. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37560. return;
  37561. }
  37562. if ( ! targetObject.material.map ) {
  37563. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37564. return;
  37565. }
  37566. targetObject = targetObject.material.map;
  37567. break;
  37568. default:
  37569. if ( targetObject[ objectName ] === undefined ) {
  37570. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37571. return;
  37572. }
  37573. targetObject = targetObject[ objectName ];
  37574. }
  37575. if ( objectIndex !== undefined ) {
  37576. if ( targetObject[ objectIndex ] === undefined ) {
  37577. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37578. return;
  37579. }
  37580. targetObject = targetObject[ objectIndex ];
  37581. }
  37582. }
  37583. // resolve property
  37584. const nodeProperty = targetObject[ propertyName ];
  37585. if ( nodeProperty === undefined ) {
  37586. const nodeName = parsedPath.nodeName;
  37587. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37588. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37589. return;
  37590. }
  37591. // determine versioning scheme
  37592. let versioning = this.Versioning.None;
  37593. this.targetObject = targetObject;
  37594. if ( targetObject.isMaterial === true ) {
  37595. versioning = this.Versioning.NeedsUpdate;
  37596. } else if ( targetObject.isObject3D === true ) {
  37597. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37598. }
  37599. // determine how the property gets bound
  37600. let bindingType = this.BindingType.Direct;
  37601. if ( propertyIndex !== undefined ) {
  37602. // access a sub element of the property array (only primitives are supported right now)
  37603. if ( propertyName === 'morphTargetInfluences' ) {
  37604. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37605. // support resolving morphTarget names into indices.
  37606. if ( ! targetObject.geometry ) {
  37607. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37608. return;
  37609. }
  37610. if ( ! targetObject.geometry.morphAttributes ) {
  37611. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37612. return;
  37613. }
  37614. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37615. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37616. }
  37617. }
  37618. bindingType = this.BindingType.ArrayElement;
  37619. this.resolvedProperty = nodeProperty;
  37620. this.propertyIndex = propertyIndex;
  37621. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37622. // must use copy for Object3D.Euler/Quaternion
  37623. bindingType = this.BindingType.HasFromToArray;
  37624. this.resolvedProperty = nodeProperty;
  37625. } else if ( Array.isArray( nodeProperty ) ) {
  37626. bindingType = this.BindingType.EntireArray;
  37627. this.resolvedProperty = nodeProperty;
  37628. } else {
  37629. this.propertyName = propertyName;
  37630. }
  37631. // select getter / setter
  37632. this.getValue = this.GetterByBindingType[ bindingType ];
  37633. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37634. }
  37635. /**
  37636. * Unbinds the property.
  37637. */
  37638. unbind() {
  37639. this.node = null;
  37640. // back to the prototype version of getValue / setValue
  37641. // note: avoiding to mutate the shape of 'this' via 'delete'
  37642. this.getValue = this._getValue_unbound;
  37643. this.setValue = this._setValue_unbound;
  37644. }
  37645. }
  37646. PropertyBinding.Composite = Composite;
  37647. PropertyBinding.prototype.BindingType = {
  37648. Direct: 0,
  37649. EntireArray: 1,
  37650. ArrayElement: 2,
  37651. HasFromToArray: 3
  37652. };
  37653. PropertyBinding.prototype.Versioning = {
  37654. None: 0,
  37655. NeedsUpdate: 1,
  37656. MatrixWorldNeedsUpdate: 2
  37657. };
  37658. PropertyBinding.prototype.GetterByBindingType = [
  37659. PropertyBinding.prototype._getValue_direct,
  37660. PropertyBinding.prototype._getValue_array,
  37661. PropertyBinding.prototype._getValue_arrayElement,
  37662. PropertyBinding.prototype._getValue_toArray,
  37663. ];
  37664. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37665. [
  37666. // Direct
  37667. PropertyBinding.prototype._setValue_direct,
  37668. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37669. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37670. ], [
  37671. // EntireArray
  37672. PropertyBinding.prototype._setValue_array,
  37673. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37674. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37675. ], [
  37676. // ArrayElement
  37677. PropertyBinding.prototype._setValue_arrayElement,
  37678. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37679. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37680. ], [
  37681. // HasToFromArray
  37682. PropertyBinding.prototype._setValue_fromArray,
  37683. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37684. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37685. ]
  37686. ];
  37687. /**
  37688. * A group of objects that receives a shared animation state.
  37689. *
  37690. * Usage:
  37691. *
  37692. * - Add objects you would otherwise pass as 'root' to the
  37693. * constructor or the .clipAction method of AnimationMixer.
  37694. * - Instead pass this object as 'root'.
  37695. * - You can also add and remove objects later when the mixer is running.
  37696. *
  37697. * Note:
  37698. *
  37699. * - Objects of this class appear as one object to the mixer,
  37700. * so cache control of the individual objects must be done on the group.
  37701. *
  37702. * Limitation:
  37703. *
  37704. * - The animated properties must be compatible among the all objects in the group.
  37705. * - A single property can either be controlled through a target group or directly, but not both.
  37706. */
  37707. class AnimationObjectGroup {
  37708. /**
  37709. * Constructs a new animation group.
  37710. *
  37711. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37712. */
  37713. constructor() {
  37714. /**
  37715. * This flag can be used for type testing.
  37716. *
  37717. * @type {boolean}
  37718. * @readonly
  37719. * @default true
  37720. */
  37721. this.isAnimationObjectGroup = true;
  37722. /**
  37723. * The UUID of the 3D object.
  37724. *
  37725. * @type {string}
  37726. * @readonly
  37727. */
  37728. this.uuid = generateUUID();
  37729. // cached objects followed by the active ones
  37730. this._objects = Array.prototype.slice.call( arguments );
  37731. this.nCachedObjects_ = 0; // threshold
  37732. // note: read by PropertyBinding.Composite
  37733. const indices = {};
  37734. this._indicesByUUID = indices; // for bookkeeping
  37735. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37736. indices[ arguments[ i ].uuid ] = i;
  37737. }
  37738. this._paths = []; // inside: string
  37739. this._parsedPaths = []; // inside: { we don't care, here }
  37740. this._bindings = []; // inside: Array< PropertyBinding >
  37741. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37742. const scope = this;
  37743. this.stats = {
  37744. objects: {
  37745. get total() {
  37746. return scope._objects.length;
  37747. },
  37748. get inUse() {
  37749. return this.total - scope.nCachedObjects_;
  37750. }
  37751. },
  37752. get bindingsPerObject() {
  37753. return scope._bindings.length;
  37754. }
  37755. };
  37756. }
  37757. /**
  37758. * Adds an arbitrary number of objects to this animation group.
  37759. *
  37760. * @param {...Object3D} arguments - The 3D objects to add.
  37761. */
  37762. add() {
  37763. const objects = this._objects,
  37764. indicesByUUID = this._indicesByUUID,
  37765. paths = this._paths,
  37766. parsedPaths = this._parsedPaths,
  37767. bindings = this._bindings,
  37768. nBindings = bindings.length;
  37769. let knownObject = undefined,
  37770. nObjects = objects.length,
  37771. nCachedObjects = this.nCachedObjects_;
  37772. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37773. const object = arguments[ i ],
  37774. uuid = object.uuid;
  37775. let index = indicesByUUID[ uuid ];
  37776. if ( index === undefined ) {
  37777. // unknown object -> add it to the ACTIVE region
  37778. index = nObjects ++;
  37779. indicesByUUID[ uuid ] = index;
  37780. objects.push( object );
  37781. // accounting is done, now do the same for all bindings
  37782. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37783. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37784. }
  37785. } else if ( index < nCachedObjects ) {
  37786. knownObject = objects[ index ];
  37787. // move existing object to the ACTIVE region
  37788. const firstActiveIndex = -- nCachedObjects,
  37789. lastCachedObject = objects[ firstActiveIndex ];
  37790. indicesByUUID[ lastCachedObject.uuid ] = index;
  37791. objects[ index ] = lastCachedObject;
  37792. indicesByUUID[ uuid ] = firstActiveIndex;
  37793. objects[ firstActiveIndex ] = object;
  37794. // accounting is done, now do the same for all bindings
  37795. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37796. const bindingsForPath = bindings[ j ],
  37797. lastCached = bindingsForPath[ firstActiveIndex ];
  37798. let binding = bindingsForPath[ index ];
  37799. bindingsForPath[ index ] = lastCached;
  37800. if ( binding === undefined ) {
  37801. // since we do not bother to create new bindings
  37802. // for objects that are cached, the binding may
  37803. // or may not exist
  37804. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37805. }
  37806. bindingsForPath[ firstActiveIndex ] = binding;
  37807. }
  37808. } else if ( objects[ index ] !== knownObject ) {
  37809. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37810. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37811. } // else the object is already where we want it to be
  37812. } // for arguments
  37813. this.nCachedObjects_ = nCachedObjects;
  37814. }
  37815. /**
  37816. * Removes an arbitrary number of objects to this animation group
  37817. *
  37818. * @param {...Object3D} arguments - The 3D objects to remove.
  37819. */
  37820. remove() {
  37821. const objects = this._objects,
  37822. indicesByUUID = this._indicesByUUID,
  37823. bindings = this._bindings,
  37824. nBindings = bindings.length;
  37825. let nCachedObjects = this.nCachedObjects_;
  37826. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37827. const object = arguments[ i ],
  37828. uuid = object.uuid,
  37829. index = indicesByUUID[ uuid ];
  37830. if ( index !== undefined && index >= nCachedObjects ) {
  37831. // move existing object into the CACHED region
  37832. const lastCachedIndex = nCachedObjects ++,
  37833. firstActiveObject = objects[ lastCachedIndex ];
  37834. indicesByUUID[ firstActiveObject.uuid ] = index;
  37835. objects[ index ] = firstActiveObject;
  37836. indicesByUUID[ uuid ] = lastCachedIndex;
  37837. objects[ lastCachedIndex ] = object;
  37838. // accounting is done, now do the same for all bindings
  37839. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37840. const bindingsForPath = bindings[ j ],
  37841. firstActive = bindingsForPath[ lastCachedIndex ],
  37842. binding = bindingsForPath[ index ];
  37843. bindingsForPath[ index ] = firstActive;
  37844. bindingsForPath[ lastCachedIndex ] = binding;
  37845. }
  37846. }
  37847. } // for arguments
  37848. this.nCachedObjects_ = nCachedObjects;
  37849. }
  37850. /**
  37851. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37852. *
  37853. * @param {...Object3D} arguments - The 3D objects to uncache.
  37854. */
  37855. uncache() {
  37856. const objects = this._objects,
  37857. indicesByUUID = this._indicesByUUID,
  37858. bindings = this._bindings,
  37859. nBindings = bindings.length;
  37860. let nCachedObjects = this.nCachedObjects_,
  37861. nObjects = objects.length;
  37862. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37863. const object = arguments[ i ],
  37864. uuid = object.uuid,
  37865. index = indicesByUUID[ uuid ];
  37866. if ( index !== undefined ) {
  37867. delete indicesByUUID[ uuid ];
  37868. if ( index < nCachedObjects ) {
  37869. // object is cached, shrink the CACHED region
  37870. const firstActiveIndex = -- nCachedObjects,
  37871. lastCachedObject = objects[ firstActiveIndex ],
  37872. lastIndex = -- nObjects,
  37873. lastObject = objects[ lastIndex ];
  37874. // last cached object takes this object's place
  37875. indicesByUUID[ lastCachedObject.uuid ] = index;
  37876. objects[ index ] = lastCachedObject;
  37877. // last object goes to the activated slot and pop
  37878. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37879. objects[ firstActiveIndex ] = lastObject;
  37880. objects.pop();
  37881. // accounting is done, now do the same for all bindings
  37882. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37883. const bindingsForPath = bindings[ j ],
  37884. lastCached = bindingsForPath[ firstActiveIndex ],
  37885. last = bindingsForPath[ lastIndex ];
  37886. bindingsForPath[ index ] = lastCached;
  37887. bindingsForPath[ firstActiveIndex ] = last;
  37888. bindingsForPath.pop();
  37889. }
  37890. } else {
  37891. // object is active, just swap with the last and pop
  37892. const lastIndex = -- nObjects,
  37893. lastObject = objects[ lastIndex ];
  37894. if ( lastIndex > 0 ) {
  37895. indicesByUUID[ lastObject.uuid ] = index;
  37896. }
  37897. objects[ index ] = lastObject;
  37898. objects.pop();
  37899. // accounting is done, now do the same for all bindings
  37900. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37901. const bindingsForPath = bindings[ j ];
  37902. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37903. bindingsForPath.pop();
  37904. }
  37905. } // cached or active
  37906. } // if object is known
  37907. } // for arguments
  37908. this.nCachedObjects_ = nCachedObjects;
  37909. }
  37910. // Internal interface used by befriended PropertyBinding.Composite:
  37911. subscribe_( path, parsedPath ) {
  37912. // returns an array of bindings for the given path that is changed
  37913. // according to the contained objects in the group
  37914. const indicesByPath = this._bindingsIndicesByPath;
  37915. let index = indicesByPath[ path ];
  37916. const bindings = this._bindings;
  37917. if ( index !== undefined ) return bindings[ index ];
  37918. const paths = this._paths,
  37919. parsedPaths = this._parsedPaths,
  37920. objects = this._objects,
  37921. nObjects = objects.length,
  37922. nCachedObjects = this.nCachedObjects_,
  37923. bindingsForPath = new Array( nObjects );
  37924. index = bindings.length;
  37925. indicesByPath[ path ] = index;
  37926. paths.push( path );
  37927. parsedPaths.push( parsedPath );
  37928. bindings.push( bindingsForPath );
  37929. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37930. const object = objects[ i ];
  37931. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37932. }
  37933. return bindingsForPath;
  37934. }
  37935. unsubscribe_( path ) {
  37936. // tells the group to forget about a property path and no longer
  37937. // update the array previously obtained with 'subscribe_'
  37938. const indicesByPath = this._bindingsIndicesByPath,
  37939. index = indicesByPath[ path ];
  37940. if ( index !== undefined ) {
  37941. const paths = this._paths,
  37942. parsedPaths = this._parsedPaths,
  37943. bindings = this._bindings,
  37944. lastBindingsIndex = bindings.length - 1,
  37945. lastBindings = bindings[ lastBindingsIndex ],
  37946. lastBindingsPath = path[ lastBindingsIndex ];
  37947. indicesByPath[ lastBindingsPath ] = index;
  37948. bindings[ index ] = lastBindings;
  37949. bindings.pop();
  37950. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37951. parsedPaths.pop();
  37952. paths[ index ] = paths[ lastBindingsIndex ];
  37953. paths.pop();
  37954. }
  37955. }
  37956. }
  37957. /**
  37958. * An instance of `AnimationAction` schedules the playback of an animation which is
  37959. * stored in {@link AnimationClip}.
  37960. */
  37961. class AnimationAction {
  37962. /**
  37963. * Constructs a new animation action.
  37964. *
  37965. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37966. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37967. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37968. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37969. */
  37970. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37971. this._mixer = mixer;
  37972. this._clip = clip;
  37973. this._localRoot = localRoot;
  37974. /**
  37975. * Defines how the animation is blended/combined when two or more animations
  37976. * are simultaneously played.
  37977. *
  37978. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37979. */
  37980. this.blendMode = blendMode;
  37981. const tracks = clip.tracks,
  37982. nTracks = tracks.length,
  37983. interpolants = new Array( nTracks );
  37984. const interpolantSettings = {
  37985. endingStart: ZeroCurvatureEnding,
  37986. endingEnd: ZeroCurvatureEnding
  37987. };
  37988. for ( let i = 0; i !== nTracks; ++ i ) {
  37989. const interpolant = tracks[ i ].createInterpolant( null );
  37990. interpolants[ i ] = interpolant;
  37991. interpolant.settings = interpolantSettings;
  37992. }
  37993. this._interpolantSettings = interpolantSettings;
  37994. this._interpolants = interpolants; // bound by the mixer
  37995. // inside: PropertyMixer (managed by the mixer)
  37996. this._propertyBindings = new Array( nTracks );
  37997. this._cacheIndex = null; // for the memory manager
  37998. this._byClipCacheIndex = null; // for the memory manager
  37999. this._timeScaleInterpolant = null;
  38000. this._weightInterpolant = null;
  38001. /**
  38002. * The loop mode, set via {@link AnimationAction#setLoop}.
  38003. *
  38004. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38005. * @default LoopRepeat
  38006. */
  38007. this.loop = LoopRepeat;
  38008. this._loopCount = -1;
  38009. // global mixer time when the action is to be started
  38010. // it's set back to 'null' upon start of the action
  38011. this._startTime = null;
  38012. /**
  38013. * The local time of this action (in seconds, starting with `0`).
  38014. *
  38015. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38016. * loop state).
  38017. *
  38018. * @type {number}
  38019. * @default Infinity
  38020. */
  38021. this.time = 0;
  38022. /**
  38023. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38024. * animation to pause. Negative values cause the animation to play backwards.
  38025. *
  38026. * @type {number}
  38027. * @default 1
  38028. */
  38029. this.timeScale = 1;
  38030. this._effectiveTimeScale = 1;
  38031. /**
  38032. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38033. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38034. * several actions.
  38035. *
  38036. * @type {number}
  38037. * @default 1
  38038. */
  38039. this.weight = 1;
  38040. this._effectiveWeight = 1;
  38041. /**
  38042. * The number of repetitions of the performed clip over the course of this action.
  38043. * Can be set via {@link AnimationAction#setLoop}.
  38044. *
  38045. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38046. * `THREE:LoopOnce`.
  38047. *
  38048. * @type {number}
  38049. * @default Infinity
  38050. */
  38051. this.repetitions = Infinity;
  38052. /**
  38053. * If set to `true`, the playback of the action is paused.
  38054. *
  38055. * @type {boolean}
  38056. * @default false
  38057. */
  38058. this.paused = false;
  38059. /**
  38060. * If set to `false`, the action is disabled so it has no impact.
  38061. *
  38062. * When the action is re-enabled, the animation continues from its current
  38063. * time (setting `enabled` to `false` doesn't reset the action).
  38064. *
  38065. * @type {boolean}
  38066. * @default true
  38067. */
  38068. this.enabled = true;
  38069. /**
  38070. * If set to true the animation will automatically be paused on its last frame.
  38071. *
  38072. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38073. * to `false` when the last loop of the action has finished, so that this action has
  38074. * no further impact.
  38075. *
  38076. * Note: This member has no impact if the action is interrupted (it
  38077. * has only an effect if its last loop has really finished).
  38078. *
  38079. * @type {boolean}
  38080. * @default false
  38081. */
  38082. this.clampWhenFinished = false;
  38083. /**
  38084. * Enables smooth interpolation without separate clips for start, loop and end.
  38085. *
  38086. * @type {boolean}
  38087. * @default true
  38088. */
  38089. this.zeroSlopeAtStart = true;
  38090. /**
  38091. * Enables smooth interpolation without separate clips for start, loop and end.
  38092. *
  38093. * @type {boolean}
  38094. * @default true
  38095. */
  38096. this.zeroSlopeAtEnd = true;
  38097. }
  38098. /**
  38099. * Starts the playback of the animation.
  38100. *
  38101. * @return {AnimationAction} A reference to this animation action.
  38102. */
  38103. play() {
  38104. this._mixer._activateAction( this );
  38105. return this;
  38106. }
  38107. /**
  38108. * Stops the playback of the animation.
  38109. *
  38110. * @return {AnimationAction} A reference to this animation action.
  38111. */
  38112. stop() {
  38113. this._mixer._deactivateAction( this );
  38114. return this.reset();
  38115. }
  38116. /**
  38117. * Resets the playback of the animation.
  38118. *
  38119. * @return {AnimationAction} A reference to this animation action.
  38120. */
  38121. reset() {
  38122. this.paused = false;
  38123. this.enabled = true;
  38124. this.time = 0; // restart clip
  38125. this._loopCount = -1;// forget previous loops
  38126. this._startTime = null;// forget scheduling
  38127. return this.stopFading().stopWarping();
  38128. }
  38129. /**
  38130. * Returns `true` if the animation is running.
  38131. *
  38132. * @return {boolean} Whether the animation is running or not.
  38133. */
  38134. isRunning() {
  38135. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38136. this._startTime === null && this._mixer._isActiveAction( this );
  38137. }
  38138. /**
  38139. * Returns `true` when {@link AnimationAction#play} has been called.
  38140. *
  38141. * @return {boolean} Whether the animation is scheduled or not.
  38142. */
  38143. isScheduled() {
  38144. return this._mixer._isActiveAction( this );
  38145. }
  38146. /**
  38147. * Defines the time when the animation should start.
  38148. *
  38149. * @param {number} time - The start time in seconds.
  38150. * @return {AnimationAction} A reference to this animation action.
  38151. */
  38152. startAt( time ) {
  38153. this._startTime = time;
  38154. return this;
  38155. }
  38156. /**
  38157. * Configures the loop settings for this action.
  38158. *
  38159. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38160. * @param {number} repetitions - The number of repetitions.
  38161. * @return {AnimationAction} A reference to this animation action.
  38162. */
  38163. setLoop( mode, repetitions ) {
  38164. this.loop = mode;
  38165. this.repetitions = repetitions;
  38166. return this;
  38167. }
  38168. /**
  38169. * Sets the effective weight of this action.
  38170. *
  38171. * An action has no effect and thus an effective weight of zero when the
  38172. * action is disabled.
  38173. *
  38174. * @param {number} weight - The weight to set.
  38175. * @return {AnimationAction} A reference to this animation action.
  38176. */
  38177. setEffectiveWeight( weight ) {
  38178. this.weight = weight;
  38179. // note: same logic as when updated at runtime
  38180. this._effectiveWeight = this.enabled ? weight : 0;
  38181. return this.stopFading();
  38182. }
  38183. /**
  38184. * Returns the effective weight of this action.
  38185. *
  38186. * @return {number} The effective weight.
  38187. */
  38188. getEffectiveWeight() {
  38189. return this._effectiveWeight;
  38190. }
  38191. /**
  38192. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38193. * within the passed time interval.
  38194. *
  38195. * @param {number} duration - The duration of the fade.
  38196. * @return {AnimationAction} A reference to this animation action.
  38197. */
  38198. fadeIn( duration ) {
  38199. return this._scheduleFading( duration, 0, 1 );
  38200. }
  38201. /**
  38202. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38203. * within the passed time interval.
  38204. *
  38205. * @param {number} duration - The duration of the fade.
  38206. * @return {AnimationAction} A reference to this animation action.
  38207. */
  38208. fadeOut( duration ) {
  38209. return this._scheduleFading( duration, 1, 0 );
  38210. }
  38211. /**
  38212. * Causes this action to fade in and the given action to fade out,
  38213. * within the passed time interval.
  38214. *
  38215. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38216. * @param {number} duration - The duration of the fade.
  38217. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38218. * @return {AnimationAction} A reference to this animation action.
  38219. */
  38220. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38221. fadeOutAction.fadeOut( duration );
  38222. this.fadeIn( duration );
  38223. if ( warp === true ) {
  38224. const fadeInDuration = this._clip.duration,
  38225. fadeOutDuration = fadeOutAction._clip.duration,
  38226. startEndRatio = fadeOutDuration / fadeInDuration,
  38227. endStartRatio = fadeInDuration / fadeOutDuration;
  38228. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38229. this.warp( endStartRatio, 1.0, duration );
  38230. }
  38231. return this;
  38232. }
  38233. /**
  38234. * Causes this action to fade out and the given action to fade in,
  38235. * within the passed time interval.
  38236. *
  38237. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38238. * @param {number} duration - The duration of the fade.
  38239. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38240. * @return {AnimationAction} A reference to this animation action.
  38241. */
  38242. crossFadeTo( fadeInAction, duration, warp = false ) {
  38243. return fadeInAction.crossFadeFrom( this, duration, warp );
  38244. }
  38245. /**
  38246. * Stops any fading which is applied to this action.
  38247. *
  38248. * @return {AnimationAction} A reference to this animation action.
  38249. */
  38250. stopFading() {
  38251. const weightInterpolant = this._weightInterpolant;
  38252. if ( weightInterpolant !== null ) {
  38253. this._weightInterpolant = null;
  38254. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38255. }
  38256. return this;
  38257. }
  38258. /**
  38259. * Sets the effective time scale of this action.
  38260. *
  38261. * An action has no effect and thus an effective time scale of zero when the
  38262. * action is paused.
  38263. *
  38264. * @param {number} timeScale - The time scale to set.
  38265. * @return {AnimationAction} A reference to this animation action.
  38266. */
  38267. setEffectiveTimeScale( timeScale ) {
  38268. this.timeScale = timeScale;
  38269. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38270. return this.stopWarping();
  38271. }
  38272. /**
  38273. * Returns the effective time scale of this action.
  38274. *
  38275. * @return {number} The effective time scale.
  38276. */
  38277. getEffectiveTimeScale() {
  38278. return this._effectiveTimeScale;
  38279. }
  38280. /**
  38281. * Sets the duration for a single loop of this action.
  38282. *
  38283. * @param {number} duration - The duration to set.
  38284. * @return {AnimationAction} A reference to this animation action.
  38285. */
  38286. setDuration( duration ) {
  38287. this.timeScale = this._clip.duration / duration;
  38288. return this.stopWarping();
  38289. }
  38290. /**
  38291. * Synchronizes this action with the passed other action.
  38292. *
  38293. * @param {AnimationAction} action - The action to sync with.
  38294. * @return {AnimationAction} A reference to this animation action.
  38295. */
  38296. syncWith( action ) {
  38297. this.time = action.time;
  38298. this.timeScale = action.timeScale;
  38299. return this.stopWarping();
  38300. }
  38301. /**
  38302. * Decelerates this animation's speed to `0` within the passed time interval.
  38303. *
  38304. * @param {number} duration - The duration.
  38305. * @return {AnimationAction} A reference to this animation action.
  38306. */
  38307. halt( duration ) {
  38308. return this.warp( this._effectiveTimeScale, 0, duration );
  38309. }
  38310. /**
  38311. * Changes the playback speed, within the passed time interval, by modifying
  38312. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38313. * `endTimeScale`.
  38314. *
  38315. * @param {number} startTimeScale - The start time scale.
  38316. * @param {number} endTimeScale - The end time scale.
  38317. * @param {number} duration - The duration.
  38318. * @return {AnimationAction} A reference to this animation action.
  38319. */
  38320. warp( startTimeScale, endTimeScale, duration ) {
  38321. const mixer = this._mixer,
  38322. now = mixer.time,
  38323. timeScale = this.timeScale;
  38324. let interpolant = this._timeScaleInterpolant;
  38325. if ( interpolant === null ) {
  38326. interpolant = mixer._lendControlInterpolant();
  38327. this._timeScaleInterpolant = interpolant;
  38328. }
  38329. const times = interpolant.parameterPositions,
  38330. values = interpolant.sampleValues;
  38331. times[ 0 ] = now;
  38332. times[ 1 ] = now + duration;
  38333. values[ 0 ] = startTimeScale / timeScale;
  38334. values[ 1 ] = endTimeScale / timeScale;
  38335. return this;
  38336. }
  38337. /**
  38338. * Stops any scheduled warping which is applied to this action.
  38339. *
  38340. * @return {AnimationAction} A reference to this animation action.
  38341. */
  38342. stopWarping() {
  38343. const timeScaleInterpolant = this._timeScaleInterpolant;
  38344. if ( timeScaleInterpolant !== null ) {
  38345. this._timeScaleInterpolant = null;
  38346. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38347. }
  38348. return this;
  38349. }
  38350. /**
  38351. * Returns the animation mixer of this animation action.
  38352. *
  38353. * @return {AnimationMixer} The animation mixer.
  38354. */
  38355. getMixer() {
  38356. return this._mixer;
  38357. }
  38358. /**
  38359. * Returns the animation clip of this animation action.
  38360. *
  38361. * @return {AnimationClip} The animation clip.
  38362. */
  38363. getClip() {
  38364. return this._clip;
  38365. }
  38366. /**
  38367. * Returns the root object of this animation action.
  38368. *
  38369. * @return {Object3D} The root object.
  38370. */
  38371. getRoot() {
  38372. return this._localRoot || this._mixer._root;
  38373. }
  38374. // Interna
  38375. _update( time, deltaTime, timeDirection, accuIndex ) {
  38376. // called by the mixer
  38377. if ( ! this.enabled ) {
  38378. // call ._updateWeight() to update ._effectiveWeight
  38379. this._updateWeight( time );
  38380. return;
  38381. }
  38382. const startTime = this._startTime;
  38383. if ( startTime !== null ) {
  38384. // check for scheduled start of action
  38385. const timeRunning = ( time - startTime ) * timeDirection;
  38386. if ( timeRunning < 0 || timeDirection === 0 ) {
  38387. deltaTime = 0;
  38388. } else {
  38389. this._startTime = null; // unschedule
  38390. deltaTime = timeDirection * timeRunning;
  38391. }
  38392. }
  38393. // apply time scale and advance time
  38394. deltaTime *= this._updateTimeScale( time );
  38395. const clipTime = this._updateTime( deltaTime );
  38396. // note: _updateTime may disable the action resulting in
  38397. // an effective weight of 0
  38398. const weight = this._updateWeight( time );
  38399. if ( weight > 0 ) {
  38400. const interpolants = this._interpolants;
  38401. const propertyMixers = this._propertyBindings;
  38402. switch ( this.blendMode ) {
  38403. case AdditiveAnimationBlendMode:
  38404. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38405. interpolants[ j ].evaluate( clipTime );
  38406. propertyMixers[ j ].accumulateAdditive( weight );
  38407. }
  38408. break;
  38409. case NormalAnimationBlendMode:
  38410. default:
  38411. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38412. interpolants[ j ].evaluate( clipTime );
  38413. propertyMixers[ j ].accumulate( accuIndex, weight );
  38414. }
  38415. }
  38416. }
  38417. }
  38418. _updateWeight( time ) {
  38419. let weight = 0;
  38420. if ( this.enabled ) {
  38421. weight = this.weight;
  38422. const interpolant = this._weightInterpolant;
  38423. if ( interpolant !== null ) {
  38424. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38425. weight *= interpolantValue;
  38426. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38427. this.stopFading();
  38428. if ( interpolantValue === 0 ) {
  38429. // faded out, disable
  38430. this.enabled = false;
  38431. }
  38432. }
  38433. }
  38434. }
  38435. this._effectiveWeight = weight;
  38436. return weight;
  38437. }
  38438. _updateTimeScale( time ) {
  38439. let timeScale = 0;
  38440. if ( ! this.paused ) {
  38441. timeScale = this.timeScale;
  38442. const interpolant = this._timeScaleInterpolant;
  38443. if ( interpolant !== null ) {
  38444. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38445. timeScale *= interpolantValue;
  38446. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38447. this.stopWarping();
  38448. if ( timeScale === 0 ) {
  38449. // motion has halted, pause
  38450. this.paused = true;
  38451. } else {
  38452. // warp done - apply final time scale
  38453. this.timeScale = timeScale;
  38454. }
  38455. }
  38456. }
  38457. }
  38458. this._effectiveTimeScale = timeScale;
  38459. return timeScale;
  38460. }
  38461. _updateTime( deltaTime ) {
  38462. const duration = this._clip.duration;
  38463. const loop = this.loop;
  38464. let time = this.time + deltaTime;
  38465. let loopCount = this._loopCount;
  38466. const pingPong = ( loop === LoopPingPong );
  38467. if ( deltaTime === 0 ) {
  38468. if ( loopCount === -1 ) return time;
  38469. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38470. }
  38471. if ( loop === LoopOnce ) {
  38472. if ( loopCount === -1 ) {
  38473. // just started
  38474. this._loopCount = 0;
  38475. this._setEndings( true, true, false );
  38476. }
  38477. handle_stop: {
  38478. if ( time >= duration ) {
  38479. time = duration;
  38480. } else if ( time < 0 ) {
  38481. time = 0;
  38482. } else {
  38483. this.time = time;
  38484. break handle_stop;
  38485. }
  38486. if ( this.clampWhenFinished ) this.paused = true;
  38487. else this.enabled = false;
  38488. this.time = time;
  38489. this._mixer.dispatchEvent( {
  38490. type: 'finished', action: this,
  38491. direction: deltaTime < 0 ? -1 : 1
  38492. } );
  38493. }
  38494. } else { // repetitive Repeat or PingPong
  38495. if ( loopCount === -1 ) {
  38496. // just started
  38497. if ( deltaTime >= 0 ) {
  38498. loopCount = 0;
  38499. this._setEndings( true, this.repetitions === 0, pingPong );
  38500. } else {
  38501. // when looping in reverse direction, the initial
  38502. // transition through zero counts as a repetition,
  38503. // so leave loopCount at -1
  38504. this._setEndings( this.repetitions === 0, true, pingPong );
  38505. }
  38506. }
  38507. if ( time >= duration || time < 0 ) {
  38508. // wrap around
  38509. const loopDelta = Math.floor( time / duration ); // signed
  38510. time -= duration * loopDelta;
  38511. loopCount += Math.abs( loopDelta );
  38512. const pending = this.repetitions - loopCount;
  38513. if ( pending <= 0 ) {
  38514. // have to stop (switch state, clamp time, fire event)
  38515. if ( this.clampWhenFinished ) this.paused = true;
  38516. else this.enabled = false;
  38517. time = deltaTime > 0 ? duration : 0;
  38518. this.time = time;
  38519. this._mixer.dispatchEvent( {
  38520. type: 'finished', action: this,
  38521. direction: deltaTime > 0 ? 1 : -1
  38522. } );
  38523. } else {
  38524. // keep running
  38525. if ( pending === 1 ) {
  38526. // entering the last round
  38527. const atStart = deltaTime < 0;
  38528. this._setEndings( atStart, ! atStart, pingPong );
  38529. } else {
  38530. this._setEndings( false, false, pingPong );
  38531. }
  38532. this._loopCount = loopCount;
  38533. this.time = time;
  38534. this._mixer.dispatchEvent( {
  38535. type: 'loop', action: this, loopDelta: loopDelta
  38536. } );
  38537. }
  38538. } else {
  38539. this.time = time;
  38540. }
  38541. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38542. // invert time for the "pong round"
  38543. return duration - time;
  38544. }
  38545. }
  38546. return time;
  38547. }
  38548. _setEndings( atStart, atEnd, pingPong ) {
  38549. const settings = this._interpolantSettings;
  38550. if ( pingPong ) {
  38551. settings.endingStart = ZeroSlopeEnding;
  38552. settings.endingEnd = ZeroSlopeEnding;
  38553. } else {
  38554. // assuming for LoopOnce atStart == atEnd == true
  38555. if ( atStart ) {
  38556. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38557. } else {
  38558. settings.endingStart = WrapAroundEnding;
  38559. }
  38560. if ( atEnd ) {
  38561. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38562. } else {
  38563. settings.endingEnd = WrapAroundEnding;
  38564. }
  38565. }
  38566. }
  38567. _scheduleFading( duration, weightNow, weightThen ) {
  38568. const mixer = this._mixer, now = mixer.time;
  38569. let interpolant = this._weightInterpolant;
  38570. if ( interpolant === null ) {
  38571. interpolant = mixer._lendControlInterpolant();
  38572. this._weightInterpolant = interpolant;
  38573. }
  38574. const times = interpolant.parameterPositions,
  38575. values = interpolant.sampleValues;
  38576. times[ 0 ] = now;
  38577. values[ 0 ] = weightNow;
  38578. times[ 1 ] = now + duration;
  38579. values[ 1 ] = weightThen;
  38580. return this;
  38581. }
  38582. }
  38583. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38584. /**
  38585. * `AnimationMixer` is a player for animations on a particular object in
  38586. * the scene. When multiple objects in the scene are animated independently,
  38587. * one `AnimationMixer` may be used for each object.
  38588. */
  38589. class AnimationMixer extends EventDispatcher {
  38590. /**
  38591. * Constructs a new animation mixer.
  38592. *
  38593. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38594. */
  38595. constructor( root ) {
  38596. super();
  38597. this._root = root;
  38598. this._initMemoryManager();
  38599. this._accuIndex = 0;
  38600. /**
  38601. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38602. *
  38603. * @type {number}
  38604. * @default 0
  38605. */
  38606. this.time = 0;
  38607. /**
  38608. * A scaling factor for the global time.
  38609. *
  38610. * Note: Setting this member to `0` and later back to `1` is a
  38611. * possibility to pause/unpause all actions that are controlled by this
  38612. * mixer.
  38613. *
  38614. * @type {number}
  38615. * @default 1
  38616. */
  38617. this.timeScale = 1.0;
  38618. }
  38619. _bindAction( action, prototypeAction ) {
  38620. const root = action._localRoot || this._root,
  38621. tracks = action._clip.tracks,
  38622. nTracks = tracks.length,
  38623. bindings = action._propertyBindings,
  38624. interpolants = action._interpolants,
  38625. rootUuid = root.uuid,
  38626. bindingsByRoot = this._bindingsByRootAndName;
  38627. let bindingsByName = bindingsByRoot[ rootUuid ];
  38628. if ( bindingsByName === undefined ) {
  38629. bindingsByName = {};
  38630. bindingsByRoot[ rootUuid ] = bindingsByName;
  38631. }
  38632. for ( let i = 0; i !== nTracks; ++ i ) {
  38633. const track = tracks[ i ],
  38634. trackName = track.name;
  38635. let binding = bindingsByName[ trackName ];
  38636. if ( binding !== undefined ) {
  38637. ++ binding.referenceCount;
  38638. bindings[ i ] = binding;
  38639. } else {
  38640. binding = bindings[ i ];
  38641. if ( binding !== undefined ) {
  38642. // existing binding, make sure the cache knows
  38643. if ( binding._cacheIndex === null ) {
  38644. ++ binding.referenceCount;
  38645. this._addInactiveBinding( binding, rootUuid, trackName );
  38646. }
  38647. continue;
  38648. }
  38649. const path = prototypeAction && prototypeAction.
  38650. _propertyBindings[ i ].binding.parsedPath;
  38651. binding = new PropertyMixer(
  38652. PropertyBinding.create( root, trackName, path ),
  38653. track.ValueTypeName, track.getValueSize() );
  38654. ++ binding.referenceCount;
  38655. this._addInactiveBinding( binding, rootUuid, trackName );
  38656. bindings[ i ] = binding;
  38657. }
  38658. interpolants[ i ].resultBuffer = binding.buffer;
  38659. }
  38660. }
  38661. _activateAction( action ) {
  38662. if ( ! this._isActiveAction( action ) ) {
  38663. if ( action._cacheIndex === null ) {
  38664. // this action has been forgotten by the cache, but the user
  38665. // appears to be still using it -> rebind
  38666. const rootUuid = ( action._localRoot || this._root ).uuid,
  38667. clipUuid = action._clip.uuid,
  38668. actionsForClip = this._actionsByClip[ clipUuid ];
  38669. this._bindAction( action,
  38670. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38671. this._addInactiveAction( action, clipUuid, rootUuid );
  38672. }
  38673. const bindings = action._propertyBindings;
  38674. // increment reference counts / sort out state
  38675. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38676. const binding = bindings[ i ];
  38677. if ( binding.useCount ++ === 0 ) {
  38678. this._lendBinding( binding );
  38679. binding.saveOriginalState();
  38680. }
  38681. }
  38682. this._lendAction( action );
  38683. }
  38684. }
  38685. _deactivateAction( action ) {
  38686. if ( this._isActiveAction( action ) ) {
  38687. const bindings = action._propertyBindings;
  38688. // decrement reference counts / sort out state
  38689. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38690. const binding = bindings[ i ];
  38691. if ( -- binding.useCount === 0 ) {
  38692. binding.restoreOriginalState();
  38693. this._takeBackBinding( binding );
  38694. }
  38695. }
  38696. this._takeBackAction( action );
  38697. }
  38698. }
  38699. // Memory manager
  38700. _initMemoryManager() {
  38701. this._actions = []; // 'nActiveActions' followed by inactive ones
  38702. this._nActiveActions = 0;
  38703. this._actionsByClip = {};
  38704. // inside:
  38705. // {
  38706. // knownActions: Array< AnimationAction > - used as prototypes
  38707. // actionByRoot: AnimationAction - lookup
  38708. // }
  38709. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38710. this._nActiveBindings = 0;
  38711. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38712. this._controlInterpolants = []; // same game as above
  38713. this._nActiveControlInterpolants = 0;
  38714. const scope = this;
  38715. this.stats = {
  38716. actions: {
  38717. get total() {
  38718. return scope._actions.length;
  38719. },
  38720. get inUse() {
  38721. return scope._nActiveActions;
  38722. }
  38723. },
  38724. bindings: {
  38725. get total() {
  38726. return scope._bindings.length;
  38727. },
  38728. get inUse() {
  38729. return scope._nActiveBindings;
  38730. }
  38731. },
  38732. controlInterpolants: {
  38733. get total() {
  38734. return scope._controlInterpolants.length;
  38735. },
  38736. get inUse() {
  38737. return scope._nActiveControlInterpolants;
  38738. }
  38739. }
  38740. };
  38741. }
  38742. // Memory management for AnimationAction objects
  38743. _isActiveAction( action ) {
  38744. const index = action._cacheIndex;
  38745. return index !== null && index < this._nActiveActions;
  38746. }
  38747. _addInactiveAction( action, clipUuid, rootUuid ) {
  38748. const actions = this._actions,
  38749. actionsByClip = this._actionsByClip;
  38750. let actionsForClip = actionsByClip[ clipUuid ];
  38751. if ( actionsForClip === undefined ) {
  38752. actionsForClip = {
  38753. knownActions: [ action ],
  38754. actionByRoot: {}
  38755. };
  38756. action._byClipCacheIndex = 0;
  38757. actionsByClip[ clipUuid ] = actionsForClip;
  38758. } else {
  38759. const knownActions = actionsForClip.knownActions;
  38760. action._byClipCacheIndex = knownActions.length;
  38761. knownActions.push( action );
  38762. }
  38763. action._cacheIndex = actions.length;
  38764. actions.push( action );
  38765. actionsForClip.actionByRoot[ rootUuid ] = action;
  38766. }
  38767. _removeInactiveAction( action ) {
  38768. const actions = this._actions,
  38769. lastInactiveAction = actions[ actions.length - 1 ],
  38770. cacheIndex = action._cacheIndex;
  38771. lastInactiveAction._cacheIndex = cacheIndex;
  38772. actions[ cacheIndex ] = lastInactiveAction;
  38773. actions.pop();
  38774. action._cacheIndex = null;
  38775. const clipUuid = action._clip.uuid,
  38776. actionsByClip = this._actionsByClip,
  38777. actionsForClip = actionsByClip[ clipUuid ],
  38778. knownActionsForClip = actionsForClip.knownActions,
  38779. lastKnownAction =
  38780. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38781. byClipCacheIndex = action._byClipCacheIndex;
  38782. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38783. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38784. knownActionsForClip.pop();
  38785. action._byClipCacheIndex = null;
  38786. const actionByRoot = actionsForClip.actionByRoot,
  38787. rootUuid = ( action._localRoot || this._root ).uuid;
  38788. delete actionByRoot[ rootUuid ];
  38789. if ( knownActionsForClip.length === 0 ) {
  38790. delete actionsByClip[ clipUuid ];
  38791. }
  38792. this._removeInactiveBindingsForAction( action );
  38793. }
  38794. _removeInactiveBindingsForAction( action ) {
  38795. const bindings = action._propertyBindings;
  38796. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38797. const binding = bindings[ i ];
  38798. if ( -- binding.referenceCount === 0 ) {
  38799. this._removeInactiveBinding( binding );
  38800. }
  38801. }
  38802. }
  38803. _lendAction( action ) {
  38804. // [ active actions | inactive actions ]
  38805. // [ active actions >| inactive actions ]
  38806. // s a
  38807. // <-swap->
  38808. // a s
  38809. const actions = this._actions,
  38810. prevIndex = action._cacheIndex,
  38811. lastActiveIndex = this._nActiveActions ++,
  38812. firstInactiveAction = actions[ lastActiveIndex ];
  38813. action._cacheIndex = lastActiveIndex;
  38814. actions[ lastActiveIndex ] = action;
  38815. firstInactiveAction._cacheIndex = prevIndex;
  38816. actions[ prevIndex ] = firstInactiveAction;
  38817. }
  38818. _takeBackAction( action ) {
  38819. // [ active actions | inactive actions ]
  38820. // [ active actions |< inactive actions ]
  38821. // a s
  38822. // <-swap->
  38823. // s a
  38824. const actions = this._actions,
  38825. prevIndex = action._cacheIndex,
  38826. firstInactiveIndex = -- this._nActiveActions,
  38827. lastActiveAction = actions[ firstInactiveIndex ];
  38828. action._cacheIndex = firstInactiveIndex;
  38829. actions[ firstInactiveIndex ] = action;
  38830. lastActiveAction._cacheIndex = prevIndex;
  38831. actions[ prevIndex ] = lastActiveAction;
  38832. }
  38833. // Memory management for PropertyMixer objects
  38834. _addInactiveBinding( binding, rootUuid, trackName ) {
  38835. const bindingsByRoot = this._bindingsByRootAndName,
  38836. bindings = this._bindings;
  38837. let bindingByName = bindingsByRoot[ rootUuid ];
  38838. if ( bindingByName === undefined ) {
  38839. bindingByName = {};
  38840. bindingsByRoot[ rootUuid ] = bindingByName;
  38841. }
  38842. bindingByName[ trackName ] = binding;
  38843. binding._cacheIndex = bindings.length;
  38844. bindings.push( binding );
  38845. }
  38846. _removeInactiveBinding( binding ) {
  38847. const bindings = this._bindings,
  38848. propBinding = binding.binding,
  38849. rootUuid = propBinding.rootNode.uuid,
  38850. trackName = propBinding.path,
  38851. bindingsByRoot = this._bindingsByRootAndName,
  38852. bindingByName = bindingsByRoot[ rootUuid ],
  38853. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38854. cacheIndex = binding._cacheIndex;
  38855. lastInactiveBinding._cacheIndex = cacheIndex;
  38856. bindings[ cacheIndex ] = lastInactiveBinding;
  38857. bindings.pop();
  38858. delete bindingByName[ trackName ];
  38859. if ( Object.keys( bindingByName ).length === 0 ) {
  38860. delete bindingsByRoot[ rootUuid ];
  38861. }
  38862. }
  38863. _lendBinding( binding ) {
  38864. const bindings = this._bindings,
  38865. prevIndex = binding._cacheIndex,
  38866. lastActiveIndex = this._nActiveBindings ++,
  38867. firstInactiveBinding = bindings[ lastActiveIndex ];
  38868. binding._cacheIndex = lastActiveIndex;
  38869. bindings[ lastActiveIndex ] = binding;
  38870. firstInactiveBinding._cacheIndex = prevIndex;
  38871. bindings[ prevIndex ] = firstInactiveBinding;
  38872. }
  38873. _takeBackBinding( binding ) {
  38874. const bindings = this._bindings,
  38875. prevIndex = binding._cacheIndex,
  38876. firstInactiveIndex = -- this._nActiveBindings,
  38877. lastActiveBinding = bindings[ firstInactiveIndex ];
  38878. binding._cacheIndex = firstInactiveIndex;
  38879. bindings[ firstInactiveIndex ] = binding;
  38880. lastActiveBinding._cacheIndex = prevIndex;
  38881. bindings[ prevIndex ] = lastActiveBinding;
  38882. }
  38883. // Memory management of Interpolants for weight and time scale
  38884. _lendControlInterpolant() {
  38885. const interpolants = this._controlInterpolants,
  38886. lastActiveIndex = this._nActiveControlInterpolants ++;
  38887. let interpolant = interpolants[ lastActiveIndex ];
  38888. if ( interpolant === undefined ) {
  38889. interpolant = new LinearInterpolant(
  38890. new Float32Array( 2 ), new Float32Array( 2 ),
  38891. 1, _controlInterpolantsResultBuffer );
  38892. interpolant.__cacheIndex = lastActiveIndex;
  38893. interpolants[ lastActiveIndex ] = interpolant;
  38894. }
  38895. return interpolant;
  38896. }
  38897. _takeBackControlInterpolant( interpolant ) {
  38898. const interpolants = this._controlInterpolants,
  38899. prevIndex = interpolant.__cacheIndex,
  38900. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38901. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38902. interpolant.__cacheIndex = firstInactiveIndex;
  38903. interpolants[ firstInactiveIndex ] = interpolant;
  38904. lastActiveInterpolant.__cacheIndex = prevIndex;
  38905. interpolants[ prevIndex ] = lastActiveInterpolant;
  38906. }
  38907. /**
  38908. * Returns an instance of {@link AnimationAction} for the passed clip.
  38909. *
  38910. * If an action fitting the clip and root parameters doesn't yet exist, it
  38911. * will be created by this method. Calling this method several times with the
  38912. * same clip and root parameters always returns the same action.
  38913. *
  38914. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38915. * @param {Object3D} [optionalRoot] - An alternative root object.
  38916. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38917. * @return {?AnimationAction} The animation action.
  38918. */
  38919. clipAction( clip, optionalRoot, blendMode ) {
  38920. const root = optionalRoot || this._root,
  38921. rootUuid = root.uuid;
  38922. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38923. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38924. const actionsForClip = this._actionsByClip[ clipUuid ];
  38925. let prototypeAction = null;
  38926. if ( blendMode === undefined ) {
  38927. if ( clipObject !== null ) {
  38928. blendMode = clipObject.blendMode;
  38929. } else {
  38930. blendMode = NormalAnimationBlendMode;
  38931. }
  38932. }
  38933. if ( actionsForClip !== undefined ) {
  38934. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38935. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38936. return existingAction;
  38937. }
  38938. // we know the clip, so we don't have to parse all
  38939. // the bindings again but can just copy
  38940. prototypeAction = actionsForClip.knownActions[ 0 ];
  38941. // also, take the clip from the prototype action
  38942. if ( clipObject === null )
  38943. clipObject = prototypeAction._clip;
  38944. }
  38945. // clip must be known when specified via string
  38946. if ( clipObject === null ) return null;
  38947. // allocate all resources required to run it
  38948. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38949. this._bindAction( newAction, prototypeAction );
  38950. // and make the action known to the memory manager
  38951. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38952. return newAction;
  38953. }
  38954. /**
  38955. * Returns an existing animation action for the passed clip.
  38956. *
  38957. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38958. * @param {Object3D} [optionalRoot] - An alternative root object.
  38959. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38960. */
  38961. existingAction( clip, optionalRoot ) {
  38962. const root = optionalRoot || this._root,
  38963. rootUuid = root.uuid,
  38964. clipObject = typeof clip === 'string' ?
  38965. AnimationClip.findByName( root, clip ) : clip,
  38966. clipUuid = clipObject ? clipObject.uuid : clip,
  38967. actionsForClip = this._actionsByClip[ clipUuid ];
  38968. if ( actionsForClip !== undefined ) {
  38969. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38970. }
  38971. return null;
  38972. }
  38973. /**
  38974. * Deactivates all previously scheduled actions on this mixer.
  38975. *
  38976. * @return {AnimationMixer} A reference to thi animation mixer.
  38977. */
  38978. stopAllAction() {
  38979. const actions = this._actions,
  38980. nActions = this._nActiveActions;
  38981. for ( let i = nActions - 1; i >= 0; -- i ) {
  38982. actions[ i ].stop();
  38983. }
  38984. return this;
  38985. }
  38986. /**
  38987. * Advances the global mixer time and updates the animation.
  38988. *
  38989. * This is usually done in the render loop by passing the delta
  38990. * time from {@link Clock} or {@link Timer}.
  38991. *
  38992. * @param {number} deltaTime - The delta time in seconds.
  38993. * @return {AnimationMixer} A reference to thi animation mixer.
  38994. */
  38995. update( deltaTime ) {
  38996. deltaTime *= this.timeScale;
  38997. const actions = this._actions,
  38998. nActions = this._nActiveActions,
  38999. time = this.time += deltaTime,
  39000. timeDirection = Math.sign( deltaTime ),
  39001. accuIndex = this._accuIndex ^= 1;
  39002. // run active actions
  39003. for ( let i = 0; i !== nActions; ++ i ) {
  39004. const action = actions[ i ];
  39005. action._update( time, deltaTime, timeDirection, accuIndex );
  39006. }
  39007. // update scene graph
  39008. const bindings = this._bindings,
  39009. nBindings = this._nActiveBindings;
  39010. for ( let i = 0; i !== nBindings; ++ i ) {
  39011. bindings[ i ].apply( accuIndex );
  39012. }
  39013. return this;
  39014. }
  39015. /**
  39016. * Sets the global mixer to a specific time and updates the animation accordingly.
  39017. *
  39018. * This is useful when you need to jump to an exact time in an animation. The
  39019. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39020. *
  39021. * @param {number} time - The time to set in seconds.
  39022. * @return {AnimationMixer} A reference to thi animation mixer.
  39023. */
  39024. setTime( time ) {
  39025. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39026. for ( let i = 0; i < this._actions.length; i ++ ) {
  39027. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39028. }
  39029. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39030. }
  39031. /**
  39032. * Returns this mixer's root object.
  39033. *
  39034. * @return {Object3D} The mixer's root object.
  39035. */
  39036. getRoot() {
  39037. return this._root;
  39038. }
  39039. /**
  39040. * Deallocates all memory resources for a clip. Before using this method make
  39041. * sure to call {@link AnimationAction#stop} for all related actions.
  39042. *
  39043. * @param {AnimationClip} clip - The clip to uncache.
  39044. */
  39045. uncacheClip( clip ) {
  39046. const actions = this._actions,
  39047. clipUuid = clip.uuid,
  39048. actionsByClip = this._actionsByClip,
  39049. actionsForClip = actionsByClip[ clipUuid ];
  39050. if ( actionsForClip !== undefined ) {
  39051. // note: just calling _removeInactiveAction would mess up the
  39052. // iteration state and also require updating the state we can
  39053. // just throw away
  39054. const actionsToRemove = actionsForClip.knownActions;
  39055. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39056. const action = actionsToRemove[ i ];
  39057. this._deactivateAction( action );
  39058. const cacheIndex = action._cacheIndex,
  39059. lastInactiveAction = actions[ actions.length - 1 ];
  39060. action._cacheIndex = null;
  39061. action._byClipCacheIndex = null;
  39062. lastInactiveAction._cacheIndex = cacheIndex;
  39063. actions[ cacheIndex ] = lastInactiveAction;
  39064. actions.pop();
  39065. this._removeInactiveBindingsForAction( action );
  39066. }
  39067. delete actionsByClip[ clipUuid ];
  39068. }
  39069. }
  39070. /**
  39071. * Deallocates all memory resources for a root object. Before using this
  39072. * method make sure to call {@link AnimationAction#stop} for all related
  39073. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39074. * mixer operates on a single root.
  39075. *
  39076. * @param {Object3D} root - The root object to uncache.
  39077. */
  39078. uncacheRoot( root ) {
  39079. const rootUuid = root.uuid,
  39080. actionsByClip = this._actionsByClip;
  39081. for ( const clipUuid in actionsByClip ) {
  39082. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39083. action = actionByRoot[ rootUuid ];
  39084. if ( action !== undefined ) {
  39085. this._deactivateAction( action );
  39086. this._removeInactiveAction( action );
  39087. }
  39088. }
  39089. const bindingsByRoot = this._bindingsByRootAndName,
  39090. bindingByName = bindingsByRoot[ rootUuid ];
  39091. if ( bindingByName !== undefined ) {
  39092. for ( const trackName in bindingByName ) {
  39093. const binding = bindingByName[ trackName ];
  39094. binding.restoreOriginalState();
  39095. this._removeInactiveBinding( binding );
  39096. }
  39097. }
  39098. }
  39099. /**
  39100. * Deallocates all memory resources for an action. The action is identified by the
  39101. * given clip and an optional root object. Before using this method make
  39102. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39103. *
  39104. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39105. * @param {Object3D} [optionalRoot] - An alternative root object.
  39106. */
  39107. uncacheAction( clip, optionalRoot ) {
  39108. const action = this.existingAction( clip, optionalRoot );
  39109. if ( action !== null ) {
  39110. this._deactivateAction( action );
  39111. this._removeInactiveAction( action );
  39112. }
  39113. }
  39114. }
  39115. /**
  39116. * Represents a 3D render target.
  39117. *
  39118. * @augments RenderTarget
  39119. */
  39120. class RenderTarget3D extends RenderTarget {
  39121. /**
  39122. * Constructs a new 3D render target.
  39123. *
  39124. * @param {number} [width=1] - The width of the render target.
  39125. * @param {number} [height=1] - The height of the render target.
  39126. * @param {number} [depth=1] - The height of the render target.
  39127. * @param {RenderTarget~Options} [options] - The configuration object.
  39128. */
  39129. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39130. super( width, height, options );
  39131. /**
  39132. * This flag can be used for type testing.
  39133. *
  39134. * @type {boolean}
  39135. * @readonly
  39136. * @default true
  39137. */
  39138. this.isRenderTarget3D = true;
  39139. this.depth = depth;
  39140. /**
  39141. * Overwritten with a different texture type.
  39142. *
  39143. * @type {Data3DTexture}
  39144. */
  39145. this.texture = new Data3DTexture( null, width, height, depth );
  39146. this._setTextureOptions( options );
  39147. this.texture.isRenderTargetTexture = true;
  39148. }
  39149. }
  39150. /**
  39151. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39152. *
  39153. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39154. * ```js
  39155. * uniforms: {
  39156. * time: { value: 1.0 },
  39157. * resolution: new Uniform( new Vector2() )
  39158. * };
  39159. * ```
  39160. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39161. * in {@link WebGLRenderer}.
  39162. */
  39163. class Uniform {
  39164. /**
  39165. * Constructs a new uniform.
  39166. *
  39167. * @param {any} value - The uniform value.
  39168. */
  39169. constructor( value ) {
  39170. /**
  39171. * The uniform value.
  39172. *
  39173. * @type {any}
  39174. */
  39175. this.value = value;
  39176. }
  39177. /**
  39178. * Returns a new uniform with copied values from this instance.
  39179. * If the value has a `clone()` method, the value is cloned as well.
  39180. *
  39181. * @return {Uniform} A clone of this instance.
  39182. */
  39183. clone() {
  39184. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39185. }
  39186. }
  39187. let _id$1 = 0;
  39188. /**
  39189. * A class for managing multiple uniforms in a single group. The renderer will process
  39190. * such a definition as a single UBO.
  39191. *
  39192. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39193. * in {@link WebGLRenderer}.
  39194. *
  39195. * @augments EventDispatcher
  39196. */
  39197. class UniformsGroup extends EventDispatcher {
  39198. /**
  39199. * Constructs a new uniforms group.
  39200. */
  39201. constructor() {
  39202. super();
  39203. /**
  39204. * This flag can be used for type testing.
  39205. *
  39206. * @type {boolean}
  39207. * @readonly
  39208. * @default true
  39209. */
  39210. this.isUniformsGroup = true;
  39211. /**
  39212. * The ID of the 3D object.
  39213. *
  39214. * @name UniformsGroup#id
  39215. * @type {number}
  39216. * @readonly
  39217. */
  39218. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39219. /**
  39220. * The name of the uniforms group.
  39221. *
  39222. * @type {string}
  39223. */
  39224. this.name = '';
  39225. /**
  39226. * The buffer usage.
  39227. *
  39228. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39229. * @default StaticDrawUsage
  39230. */
  39231. this.usage = StaticDrawUsage;
  39232. /**
  39233. * An array holding the uniforms.
  39234. *
  39235. * @type {Array<Uniform>}
  39236. */
  39237. this.uniforms = [];
  39238. }
  39239. /**
  39240. * Adds the given uniform to this uniforms group.
  39241. *
  39242. * @param {Uniform} uniform - The uniform to add.
  39243. * @return {UniformsGroup} A reference to this uniforms group.
  39244. */
  39245. add( uniform ) {
  39246. this.uniforms.push( uniform );
  39247. return this;
  39248. }
  39249. /**
  39250. * Removes the given uniform from this uniforms group.
  39251. *
  39252. * @param {Uniform} uniform - The uniform to remove.
  39253. * @return {UniformsGroup} A reference to this uniforms group.
  39254. */
  39255. remove( uniform ) {
  39256. const index = this.uniforms.indexOf( uniform );
  39257. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39258. return this;
  39259. }
  39260. /**
  39261. * Sets the name of this uniforms group.
  39262. *
  39263. * @param {string} name - The name to set.
  39264. * @return {UniformsGroup} A reference to this uniforms group.
  39265. */
  39266. setName( name ) {
  39267. this.name = name;
  39268. return this;
  39269. }
  39270. /**
  39271. * Sets the usage of this uniforms group.
  39272. *
  39273. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39274. * @return {UniformsGroup} A reference to this uniforms group.
  39275. */
  39276. setUsage( value ) {
  39277. this.usage = value;
  39278. return this;
  39279. }
  39280. /**
  39281. * Frees the GPU-related resources allocated by this instance. Call this
  39282. * method whenever this instance is no longer used in your app.
  39283. *
  39284. * @fires Texture#dispose
  39285. */
  39286. dispose() {
  39287. this.dispatchEvent( { type: 'dispose' } );
  39288. }
  39289. /**
  39290. * Copies the values of the given uniforms group to this instance.
  39291. *
  39292. * @param {UniformsGroup} source - The uniforms group to copy.
  39293. * @return {UniformsGroup} A reference to this uniforms group.
  39294. */
  39295. copy( source ) {
  39296. this.name = source.name;
  39297. this.usage = source.usage;
  39298. const uniformsSource = source.uniforms;
  39299. this.uniforms.length = 0;
  39300. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39301. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39302. for ( let j = 0; j < uniforms.length; j ++ ) {
  39303. this.uniforms.push( uniforms[ j ].clone() );
  39304. }
  39305. }
  39306. return this;
  39307. }
  39308. /**
  39309. * Returns a new uniforms group with copied values from this instance.
  39310. *
  39311. * @return {UniformsGroup} A clone of this instance.
  39312. */
  39313. clone() {
  39314. return new this.constructor().copy( this );
  39315. }
  39316. }
  39317. /**
  39318. * An instanced version of an interleaved buffer.
  39319. *
  39320. * @augments InterleavedBuffer
  39321. */
  39322. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39323. /**
  39324. * Constructs a new instanced interleaved buffer.
  39325. *
  39326. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39327. * @param {number} stride - The number of typed-array elements per vertex.
  39328. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39329. */
  39330. constructor( array, stride, meshPerAttribute = 1 ) {
  39331. super( array, stride );
  39332. /**
  39333. * This flag can be used for type testing.
  39334. *
  39335. * @type {boolean}
  39336. * @readonly
  39337. * @default true
  39338. */
  39339. this.isInstancedInterleavedBuffer = true;
  39340. /**
  39341. * Defines how often a value of this buffer attribute should be repeated,
  39342. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39343. *
  39344. * @type {number}
  39345. * @default 1
  39346. */
  39347. this.meshPerAttribute = meshPerAttribute;
  39348. }
  39349. copy( source ) {
  39350. super.copy( source );
  39351. this.meshPerAttribute = source.meshPerAttribute;
  39352. return this;
  39353. }
  39354. clone( data ) {
  39355. const ib = super.clone( data );
  39356. ib.meshPerAttribute = this.meshPerAttribute;
  39357. return ib;
  39358. }
  39359. toJSON( data ) {
  39360. const json = super.toJSON( data );
  39361. json.isInstancedInterleavedBuffer = true;
  39362. json.meshPerAttribute = this.meshPerAttribute;
  39363. return json;
  39364. }
  39365. }
  39366. /**
  39367. * An alternative version of a buffer attribute with more control over the VBO.
  39368. *
  39369. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39370. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39371. *
  39372. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39373. * or even produces the VBOs in question.
  39374. *
  39375. * Notice that this class can only be used with {@link WebGLRenderer}.
  39376. */
  39377. class GLBufferAttribute {
  39378. /**
  39379. * Constructs a new GL buffer attribute.
  39380. *
  39381. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39382. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39383. * @param {number} itemSize - The item size.
  39384. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39385. * @param {number} count - The expected number of vertices in VBO.
  39386. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39387. */
  39388. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39389. /**
  39390. * This flag can be used for type testing.
  39391. *
  39392. * @type {boolean}
  39393. * @readonly
  39394. * @default true
  39395. */
  39396. this.isGLBufferAttribute = true;
  39397. /**
  39398. * The name of the buffer attribute.
  39399. *
  39400. * @type {string}
  39401. */
  39402. this.name = '';
  39403. /**
  39404. * The native WebGL buffer.
  39405. *
  39406. * @type {WebGLBuffer}
  39407. */
  39408. this.buffer = buffer;
  39409. /**
  39410. * The native data type.
  39411. *
  39412. * @type {number}
  39413. */
  39414. this.type = type;
  39415. /**
  39416. * The item size, see {@link BufferAttribute#itemSize}.
  39417. *
  39418. * @type {number}
  39419. */
  39420. this.itemSize = itemSize;
  39421. /**
  39422. * The corresponding size (in bytes) for the given `type` parameter.
  39423. *
  39424. * @type {number}
  39425. */
  39426. this.elementSize = elementSize;
  39427. /**
  39428. * The expected number of vertices in VBO.
  39429. *
  39430. * @type {number}
  39431. */
  39432. this.count = count;
  39433. /**
  39434. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39435. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39436. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39437. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39438. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39439. *
  39440. * @type {boolean}
  39441. */
  39442. this.normalized = normalized;
  39443. /**
  39444. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39445. *
  39446. * @type {number}
  39447. */
  39448. this.version = 0;
  39449. }
  39450. /**
  39451. * Flag to indicate that this attribute has changed and should be re-sent to
  39452. * the GPU. Set this to `true` when you modify the value of the array.
  39453. *
  39454. * @type {number}
  39455. * @default false
  39456. * @param {boolean} value
  39457. */
  39458. set needsUpdate( value ) {
  39459. if ( value === true ) this.version ++;
  39460. }
  39461. /**
  39462. * Sets the given native WebGL buffer.
  39463. *
  39464. * @param {WebGLBuffer} buffer - The buffer to set.
  39465. * @return {BufferAttribute} A reference to this instance.
  39466. */
  39467. setBuffer( buffer ) {
  39468. this.buffer = buffer;
  39469. return this;
  39470. }
  39471. /**
  39472. * Sets the given native data type and element size.
  39473. *
  39474. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39475. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39476. * @return {BufferAttribute} A reference to this instance.
  39477. */
  39478. setType( type, elementSize ) {
  39479. this.type = type;
  39480. this.elementSize = elementSize;
  39481. return this;
  39482. }
  39483. /**
  39484. * Sets the item size.
  39485. *
  39486. * @param {number} itemSize - The item size.
  39487. * @return {BufferAttribute} A reference to this instance.
  39488. */
  39489. setItemSize( itemSize ) {
  39490. this.itemSize = itemSize;
  39491. return this;
  39492. }
  39493. /**
  39494. * Sets the count (the expected number of vertices in VBO).
  39495. *
  39496. * @param {number} count - The count.
  39497. * @return {BufferAttribute} A reference to this instance.
  39498. */
  39499. setCount( count ) {
  39500. this.count = count;
  39501. return this;
  39502. }
  39503. }
  39504. const _matrix = /*@__PURE__*/ new Matrix4();
  39505. /**
  39506. * This class is designed to assist with raycasting. Raycasting is used for
  39507. * mouse picking (working out what objects in the 3d space the mouse is over)
  39508. * amongst other things.
  39509. */
  39510. class Raycaster {
  39511. /**
  39512. * Constructs a new raycaster.
  39513. *
  39514. * @param {Vector3} origin - The origin vector where the ray casts from.
  39515. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39516. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39517. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39518. */
  39519. constructor( origin, direction, near = 0, far = Infinity ) {
  39520. /**
  39521. * The ray used for raycasting.
  39522. *
  39523. * @type {Ray}
  39524. */
  39525. this.ray = new Ray( origin, direction );
  39526. /**
  39527. * All results returned are further away than near. Near can't be negative.
  39528. *
  39529. * @type {number}
  39530. * @default 0
  39531. */
  39532. this.near = near;
  39533. /**
  39534. * All results returned are further away than near. Near can't be negative.
  39535. *
  39536. * @type {number}
  39537. * @default Infinity
  39538. */
  39539. this.far = far;
  39540. /**
  39541. * The camera to use when raycasting against view-dependent objects such as
  39542. * billboarded objects like sprites. This field can be set manually or
  39543. * is set when calling `setFromCamera()`.
  39544. *
  39545. * @type {?Camera}
  39546. * @default null
  39547. */
  39548. this.camera = null;
  39549. /**
  39550. * Allows to selectively ignore 3D objects when performing intersection tests.
  39551. * The following code example ensures that only 3D objects on layer `1` will be
  39552. * honored by raycaster.
  39553. * ```js
  39554. * raycaster.layers.set( 1 );
  39555. * object.layers.enable( 1 );
  39556. * ```
  39557. *
  39558. * @type {Layers}
  39559. */
  39560. this.layers = new Layers();
  39561. /**
  39562. * A parameter object that configures the raycasting. It has the structure:
  39563. *
  39564. * ```
  39565. * {
  39566. * Mesh: {},
  39567. * Line: { threshold: 1 },
  39568. * LOD: {},
  39569. * Points: { threshold: 1 },
  39570. * Sprite: {}
  39571. * }
  39572. * ```
  39573. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39574. *
  39575. * @type {Object}
  39576. */
  39577. this.params = {
  39578. Mesh: {},
  39579. Line: { threshold: 1 },
  39580. LOD: {},
  39581. Points: { threshold: 1 },
  39582. Sprite: {}
  39583. };
  39584. }
  39585. /**
  39586. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39587. *
  39588. * @param {Vector3} origin - The origin vector where the ray casts from.
  39589. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39590. */
  39591. set( origin, direction ) {
  39592. // direction is assumed to be normalized (for accurate distance calculations)
  39593. this.ray.set( origin, direction );
  39594. }
  39595. /**
  39596. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39597. *
  39598. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39599. * X and Y components should be between `-1` and `1`.
  39600. * @param {Camera} camera - The camera from which the ray should originate.
  39601. */
  39602. setFromCamera( coords, camera ) {
  39603. if ( camera.isPerspectiveCamera ) {
  39604. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39605. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39606. this.camera = camera;
  39607. } else if ( camera.isOrthographicCamera ) {
  39608. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39609. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39610. this.camera = camera;
  39611. } else {
  39612. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39613. }
  39614. }
  39615. /**
  39616. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39617. *
  39618. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39619. * @return {Raycaster} A reference to this raycaster.
  39620. */
  39621. setFromXRController( controller ) {
  39622. _matrix.identity().extractRotation( controller.matrixWorld );
  39623. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39624. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39625. return this;
  39626. }
  39627. /**
  39628. * The intersection point of a raycaster intersection test.
  39629. * @typedef {Object} Raycaster~Intersection
  39630. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39631. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39632. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39633. * @property {Vector3} point - The intersection point, in world coordinates.
  39634. * @property {Object} face - The face that has been intersected.
  39635. * @property {number} faceIndex - The face index.
  39636. * @property {Object3D} object - The 3D object that has been intersected.
  39637. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39638. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39639. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39640. * @property {number} instanceId - The index number of the instance where the ray
  39641. * intersects the {@link InstancedMesh}.
  39642. */
  39643. /**
  39644. * Checks all intersection between the ray and the object with or without the
  39645. * descendants. Intersections are returned sorted by distance, closest first.
  39646. *
  39647. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39648. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39649. * differently to ray casting than lines or points.
  39650. *
  39651. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39652. * to be detected; intersections of the ray passing through the back of a face will not
  39653. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39654. * to `THREE.DoubleSide`.
  39655. *
  39656. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39657. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39658. * Otherwise it only checks intersection with the object.
  39659. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39660. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39661. */
  39662. intersectObject( object, recursive = true, intersects = [] ) {
  39663. intersect( object, this, intersects, recursive );
  39664. intersects.sort( ascSort );
  39665. return intersects;
  39666. }
  39667. /**
  39668. * Checks all intersection between the ray and the objects with or without
  39669. * the descendants. Intersections are returned sorted by distance, closest first.
  39670. *
  39671. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39672. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39673. * Otherwise it only checks intersection with the object.
  39674. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39675. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39676. */
  39677. intersectObjects( objects, recursive = true, intersects = [] ) {
  39678. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39679. intersect( objects[ i ], this, intersects, recursive );
  39680. }
  39681. intersects.sort( ascSort );
  39682. return intersects;
  39683. }
  39684. }
  39685. function ascSort( a, b ) {
  39686. return a.distance - b.distance;
  39687. }
  39688. function intersect( object, raycaster, intersects, recursive ) {
  39689. let propagate = true;
  39690. if ( object.layers.test( raycaster.layers ) ) {
  39691. const result = object.raycast( raycaster, intersects );
  39692. if ( result === false ) propagate = false;
  39693. }
  39694. if ( propagate === true && recursive === true ) {
  39695. const children = object.children;
  39696. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39697. intersect( children[ i ], raycaster, intersects, true );
  39698. }
  39699. }
  39700. }
  39701. /**
  39702. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39703. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39704. *
  39705. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39706. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39707. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39708. * is inactive (e.g. tab switched or browser hidden).
  39709. *
  39710. * ```js
  39711. * const timer = new Timer();
  39712. * timer.connect( document ); // use Page Visibility API
  39713. * ```
  39714. */
  39715. class Timer {
  39716. /**
  39717. * Constructs a new timer.
  39718. */
  39719. constructor() {
  39720. this._previousTime = 0;
  39721. this._currentTime = 0;
  39722. this._startTime = performance.now();
  39723. this._delta = 0;
  39724. this._elapsed = 0;
  39725. this._timescale = 1;
  39726. this._document = null;
  39727. this._pageVisibilityHandler = null;
  39728. }
  39729. /**
  39730. * Connect the timer to the given document.Calling this method is not mandatory to
  39731. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39732. * delta values.
  39733. *
  39734. * @param {Document} document - The document.
  39735. */
  39736. connect( document ) {
  39737. this._document = document;
  39738. // use Page Visibility API to avoid large time delta values
  39739. if ( document.hidden !== undefined ) {
  39740. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39741. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39742. }
  39743. }
  39744. /**
  39745. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39746. */
  39747. disconnect() {
  39748. if ( this._pageVisibilityHandler !== null ) {
  39749. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39750. this._pageVisibilityHandler = null;
  39751. }
  39752. this._document = null;
  39753. }
  39754. /**
  39755. * Returns the time delta in seconds.
  39756. *
  39757. * @return {number} The time delta in second.
  39758. */
  39759. getDelta() {
  39760. return this._delta / 1000;
  39761. }
  39762. /**
  39763. * Returns the elapsed time in seconds.
  39764. *
  39765. * @return {number} The elapsed time in second.
  39766. */
  39767. getElapsed() {
  39768. return this._elapsed / 1000;
  39769. }
  39770. /**
  39771. * Returns the timescale.
  39772. *
  39773. * @return {number} The timescale.
  39774. */
  39775. getTimescale() {
  39776. return this._timescale;
  39777. }
  39778. /**
  39779. * Sets the given timescale which scale the time delta computation
  39780. * in `update()`.
  39781. *
  39782. * @param {number} timescale - The timescale to set.
  39783. * @return {Timer} A reference to this timer.
  39784. */
  39785. setTimescale( timescale ) {
  39786. this._timescale = timescale;
  39787. return this;
  39788. }
  39789. /**
  39790. * Resets the time computation for the current simulation step.
  39791. *
  39792. * @return {Timer} A reference to this timer.
  39793. */
  39794. reset() {
  39795. this._currentTime = performance.now() - this._startTime;
  39796. return this;
  39797. }
  39798. /**
  39799. * Can be used to free all internal resources. Usually called when
  39800. * the timer instance isn't required anymore.
  39801. */
  39802. dispose() {
  39803. this.disconnect();
  39804. }
  39805. /**
  39806. * Updates the internal state of the timer. This method should be called
  39807. * once per simulation step and before you perform queries against the timer
  39808. * (e.g. via `getDelta()`).
  39809. *
  39810. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39811. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39812. * time will be determined with `performance.now`.
  39813. * @return {Timer} A reference to this timer.
  39814. */
  39815. update( timestamp ) {
  39816. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39817. this._delta = 0;
  39818. } else {
  39819. this._previousTime = this._currentTime;
  39820. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39821. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39822. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39823. }
  39824. return this;
  39825. }
  39826. }
  39827. function handleVisibilityChange() {
  39828. if ( this._document.hidden === false ) this.reset();
  39829. }
  39830. /**
  39831. * This class can be used to represent points in 3D space as
  39832. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39833. */
  39834. class Spherical {
  39835. /**
  39836. * Constructs a new spherical.
  39837. *
  39838. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39839. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39840. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39841. */
  39842. constructor( radius = 1, phi = 0, theta = 0 ) {
  39843. /**
  39844. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39845. *
  39846. * @type {number}
  39847. * @default 1
  39848. */
  39849. this.radius = radius;
  39850. /**
  39851. * The polar angle in radians from the y (up) axis.
  39852. *
  39853. * @type {number}
  39854. * @default 0
  39855. */
  39856. this.phi = phi;
  39857. /**
  39858. * The equator/azimuthal angle in radians around the y (up) axis.
  39859. *
  39860. * @type {number}
  39861. * @default 0
  39862. */
  39863. this.theta = theta;
  39864. }
  39865. /**
  39866. * Sets the spherical components by copying the given values.
  39867. *
  39868. * @param {number} radius - The radius.
  39869. * @param {number} phi - The polar angle.
  39870. * @param {number} theta - The azimuthal angle.
  39871. * @return {Spherical} A reference to this spherical.
  39872. */
  39873. set( radius, phi, theta ) {
  39874. this.radius = radius;
  39875. this.phi = phi;
  39876. this.theta = theta;
  39877. return this;
  39878. }
  39879. /**
  39880. * Copies the values of the given spherical to this instance.
  39881. *
  39882. * @param {Spherical} other - The spherical to copy.
  39883. * @return {Spherical} A reference to this spherical.
  39884. */
  39885. copy( other ) {
  39886. this.radius = other.radius;
  39887. this.phi = other.phi;
  39888. this.theta = other.theta;
  39889. return this;
  39890. }
  39891. /**
  39892. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39893. * `0.000001`.
  39894. *
  39895. * @return {Spherical} A reference to this spherical.
  39896. */
  39897. makeSafe() {
  39898. const EPS = 0.000001;
  39899. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39900. return this;
  39901. }
  39902. /**
  39903. * Sets the spherical components from the given vector which is assumed to hold
  39904. * Cartesian coordinates.
  39905. *
  39906. * @param {Vector3} v - The vector to set.
  39907. * @return {Spherical} A reference to this spherical.
  39908. */
  39909. setFromVector3( v ) {
  39910. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39911. }
  39912. /**
  39913. * Sets the spherical components from the given Cartesian coordinates.
  39914. *
  39915. * @param {number} x - The x value.
  39916. * @param {number} y - The y value.
  39917. * @param {number} z - The z value.
  39918. * @return {Spherical} A reference to this spherical.
  39919. */
  39920. setFromCartesianCoords( x, y, z ) {
  39921. this.radius = Math.sqrt( x * x + y * y + z * z );
  39922. if ( this.radius === 0 ) {
  39923. this.theta = 0;
  39924. this.phi = 0;
  39925. } else {
  39926. this.theta = Math.atan2( x, z );
  39927. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39928. }
  39929. return this;
  39930. }
  39931. /**
  39932. * Returns a new spherical with copied values from this instance.
  39933. *
  39934. * @return {Spherical} A clone of this instance.
  39935. */
  39936. clone() {
  39937. return new this.constructor().copy( this );
  39938. }
  39939. }
  39940. /**
  39941. * This class can be used to represent points in 3D space as
  39942. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39943. */
  39944. class Cylindrical {
  39945. /**
  39946. * Constructs a new cylindrical.
  39947. *
  39948. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39949. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39950. * @param {number} [y=0] - The height above the x-z plane.
  39951. */
  39952. constructor( radius = 1, theta = 0, y = 0 ) {
  39953. /**
  39954. * The distance from the origin to a point in the x-z plane.
  39955. *
  39956. * @type {number}
  39957. * @default 1
  39958. */
  39959. this.radius = radius;
  39960. /**
  39961. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39962. *
  39963. * @type {number}
  39964. * @default 0
  39965. */
  39966. this.theta = theta;
  39967. /**
  39968. * The height above the x-z plane.
  39969. *
  39970. * @type {number}
  39971. * @default 0
  39972. */
  39973. this.y = y;
  39974. }
  39975. /**
  39976. * Sets the cylindrical components by copying the given values.
  39977. *
  39978. * @param {number} radius - The radius.
  39979. * @param {number} theta - The theta angle.
  39980. * @param {number} y - The height value.
  39981. * @return {Cylindrical} A reference to this cylindrical.
  39982. */
  39983. set( radius, theta, y ) {
  39984. this.radius = radius;
  39985. this.theta = theta;
  39986. this.y = y;
  39987. return this;
  39988. }
  39989. /**
  39990. * Copies the values of the given cylindrical to this instance.
  39991. *
  39992. * @param {Cylindrical} other - The cylindrical to copy.
  39993. * @return {Cylindrical} A reference to this cylindrical.
  39994. */
  39995. copy( other ) {
  39996. this.radius = other.radius;
  39997. this.theta = other.theta;
  39998. this.y = other.y;
  39999. return this;
  40000. }
  40001. /**
  40002. * Sets the cylindrical components from the given vector which is assumed to hold
  40003. * Cartesian coordinates.
  40004. *
  40005. * @param {Vector3} v - The vector to set.
  40006. * @return {Cylindrical} A reference to this cylindrical.
  40007. */
  40008. setFromVector3( v ) {
  40009. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40010. }
  40011. /**
  40012. * Sets the cylindrical components from the given Cartesian coordinates.
  40013. *
  40014. * @param {number} x - The x value.
  40015. * @param {number} y - The x value.
  40016. * @param {number} z - The x value.
  40017. * @return {Cylindrical} A reference to this cylindrical.
  40018. */
  40019. setFromCartesianCoords( x, y, z ) {
  40020. this.radius = Math.sqrt( x * x + z * z );
  40021. this.theta = Math.atan2( x, z );
  40022. this.y = y;
  40023. return this;
  40024. }
  40025. /**
  40026. * Returns a new cylindrical with copied values from this instance.
  40027. *
  40028. * @return {Cylindrical} A clone of this instance.
  40029. */
  40030. clone() {
  40031. return new this.constructor().copy( this );
  40032. }
  40033. }
  40034. /**
  40035. * Represents a 2x2 matrix.
  40036. *
  40037. * A Note on Row-Major and Column-Major Ordering:
  40038. *
  40039. * The constructor and {@link Matrix2#set} method take arguments in
  40040. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40041. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40042. * This means that calling:
  40043. * ```js
  40044. * const m = new THREE.Matrix2();
  40045. * m.set( 11, 12,
  40046. * 21, 22 );
  40047. * ```
  40048. * will result in the elements array containing:
  40049. * ```js
  40050. * m.elements = [ 11, 21,
  40051. * 12, 22 ];
  40052. * ```
  40053. * and internally all calculations are performed using column-major ordering.
  40054. * However, as the actual ordering makes no difference mathematically and
  40055. * most people are used to thinking about matrices in row-major order, the
  40056. * three.js documentation shows matrices in row-major order. Just bear in
  40057. * mind that if you are reading the source code, you'll have to take the
  40058. * transpose of any matrices outlined here to make sense of the calculations.
  40059. */
  40060. class Matrix2 {
  40061. /**
  40062. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40063. * in row-major order. If no arguments are provided, the constructor
  40064. * initializes the matrix as an identity matrix.
  40065. *
  40066. * @param {number} [n11] - 1-1 matrix element.
  40067. * @param {number} [n12] - 1-2 matrix element.
  40068. * @param {number} [n21] - 2-1 matrix element.
  40069. * @param {number} [n22] - 2-2 matrix element.
  40070. */
  40071. constructor( n11, n12, n21, n22 ) {
  40072. /**
  40073. * This flag can be used for type testing.
  40074. *
  40075. * @type {boolean}
  40076. * @readonly
  40077. * @default true
  40078. */
  40079. Matrix2.prototype.isMatrix2 = true;
  40080. /**
  40081. * A column-major list of matrix values.
  40082. *
  40083. * @type {Array<number>}
  40084. */
  40085. this.elements = [
  40086. 1, 0,
  40087. 0, 1,
  40088. ];
  40089. if ( n11 !== undefined ) {
  40090. this.set( n11, n12, n21, n22 );
  40091. }
  40092. }
  40093. /**
  40094. * Sets this matrix to the 2x2 identity matrix.
  40095. *
  40096. * @return {Matrix2} A reference to this matrix.
  40097. */
  40098. identity() {
  40099. this.set(
  40100. 1, 0,
  40101. 0, 1,
  40102. );
  40103. return this;
  40104. }
  40105. /**
  40106. * Sets the elements of the matrix from the given array.
  40107. *
  40108. * @param {Array<number>} array - The matrix elements in column-major order.
  40109. * @param {number} [offset=0] - Index of the first element in the array.
  40110. * @return {Matrix2} A reference to this matrix.
  40111. */
  40112. fromArray( array, offset = 0 ) {
  40113. for ( let i = 0; i < 4; i ++ ) {
  40114. this.elements[ i ] = array[ i + offset ];
  40115. }
  40116. return this;
  40117. }
  40118. /**
  40119. * Sets the elements of the matrix.The arguments are supposed to be
  40120. * in row-major order.
  40121. *
  40122. * @param {number} n11 - 1-1 matrix element.
  40123. * @param {number} n12 - 1-2 matrix element.
  40124. * @param {number} n21 - 2-1 matrix element.
  40125. * @param {number} n22 - 2-2 matrix element.
  40126. * @return {Matrix2} A reference to this matrix.
  40127. */
  40128. set( n11, n12, n21, n22 ) {
  40129. const te = this.elements;
  40130. te[ 0 ] = n11; te[ 2 ] = n12;
  40131. te[ 1 ] = n21; te[ 3 ] = n22;
  40132. return this;
  40133. }
  40134. }
  40135. const _vector$4 = /*@__PURE__*/ new Vector2();
  40136. /**
  40137. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40138. */
  40139. class Box2 {
  40140. /**
  40141. * Constructs a new bounding box.
  40142. *
  40143. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40144. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40145. */
  40146. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40147. /**
  40148. * This flag can be used for type testing.
  40149. *
  40150. * @type {boolean}
  40151. * @readonly
  40152. * @default true
  40153. */
  40154. this.isBox2 = true;
  40155. /**
  40156. * The lower boundary of the box.
  40157. *
  40158. * @type {Vector2}
  40159. */
  40160. this.min = min;
  40161. /**
  40162. * The upper boundary of the box.
  40163. *
  40164. * @type {Vector2}
  40165. */
  40166. this.max = max;
  40167. }
  40168. /**
  40169. * Sets the lower and upper boundaries of this box.
  40170. * Please note that this method only copies the values from the given objects.
  40171. *
  40172. * @param {Vector2} min - The lower boundary of the box.
  40173. * @param {Vector2} max - The upper boundary of the box.
  40174. * @return {Box2} A reference to this bounding box.
  40175. */
  40176. set( min, max ) {
  40177. this.min.copy( min );
  40178. this.max.copy( max );
  40179. return this;
  40180. }
  40181. /**
  40182. * Sets the upper and lower bounds of this box so it encloses the position data
  40183. * in the given array.
  40184. *
  40185. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40186. * @return {Box2} A reference to this bounding box.
  40187. */
  40188. setFromPoints( points ) {
  40189. this.makeEmpty();
  40190. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40191. this.expandByPoint( points[ i ] );
  40192. }
  40193. return this;
  40194. }
  40195. /**
  40196. * Centers this box on the given center vector and sets this box's width, height and
  40197. * depth to the given size values.
  40198. *
  40199. * @param {Vector2} center - The center of the box.
  40200. * @param {Vector2} size - The x and y dimensions of the box.
  40201. * @return {Box2} A reference to this bounding box.
  40202. */
  40203. setFromCenterAndSize( center, size ) {
  40204. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40205. this.min.copy( center ).sub( halfSize );
  40206. this.max.copy( center ).add( halfSize );
  40207. return this;
  40208. }
  40209. /**
  40210. * Returns a new box with copied values from this instance.
  40211. *
  40212. * @return {Box2} A clone of this instance.
  40213. */
  40214. clone() {
  40215. return new this.constructor().copy( this );
  40216. }
  40217. /**
  40218. * Copies the values of the given box to this instance.
  40219. *
  40220. * @param {Box2} box - The box to copy.
  40221. * @return {Box2} A reference to this bounding box.
  40222. */
  40223. copy( box ) {
  40224. this.min.copy( box.min );
  40225. this.max.copy( box.max );
  40226. return this;
  40227. }
  40228. /**
  40229. * Makes this box empty which means in encloses a zero space in 2D.
  40230. *
  40231. * @return {Box2} A reference to this bounding box.
  40232. */
  40233. makeEmpty() {
  40234. this.min.x = this.min.y = + Infinity;
  40235. this.max.x = this.max.y = - Infinity;
  40236. return this;
  40237. }
  40238. /**
  40239. * Returns true if this box includes zero points within its bounds.
  40240. * Note that a box with equal lower and upper bounds still includes one
  40241. * point, the one both bounds share.
  40242. *
  40243. * @return {boolean} Whether this box is empty or not.
  40244. */
  40245. isEmpty() {
  40246. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40247. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40248. }
  40249. /**
  40250. * Returns the center point of this box.
  40251. *
  40252. * @param {Vector2} target - The target vector that is used to store the method's result.
  40253. * @return {Vector2} The center point.
  40254. */
  40255. getCenter( target ) {
  40256. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40257. }
  40258. /**
  40259. * Returns the dimensions of this box.
  40260. *
  40261. * @param {Vector2} target - The target vector that is used to store the method's result.
  40262. * @return {Vector2} The size.
  40263. */
  40264. getSize( target ) {
  40265. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40266. }
  40267. /**
  40268. * Expands the boundaries of this box to include the given point.
  40269. *
  40270. * @param {Vector2} point - The point that should be included by the bounding box.
  40271. * @return {Box2} A reference to this bounding box.
  40272. */
  40273. expandByPoint( point ) {
  40274. this.min.min( point );
  40275. this.max.max( point );
  40276. return this;
  40277. }
  40278. /**
  40279. * Expands this box equilaterally by the given vector. The width of this
  40280. * box will be expanded by the x component of the vector in both
  40281. * directions. The height of this box will be expanded by the y component of
  40282. * the vector in both directions.
  40283. *
  40284. * @param {Vector2} vector - The vector that should expand the bounding box.
  40285. * @return {Box2} A reference to this bounding box.
  40286. */
  40287. expandByVector( vector ) {
  40288. this.min.sub( vector );
  40289. this.max.add( vector );
  40290. return this;
  40291. }
  40292. /**
  40293. * Expands each dimension of the box by the given scalar. If negative, the
  40294. * dimensions of the box will be contracted.
  40295. *
  40296. * @param {number} scalar - The scalar value that should expand the bounding box.
  40297. * @return {Box2} A reference to this bounding box.
  40298. */
  40299. expandByScalar( scalar ) {
  40300. this.min.addScalar( - scalar );
  40301. this.max.addScalar( scalar );
  40302. return this;
  40303. }
  40304. /**
  40305. * Returns `true` if the given point lies within or on the boundaries of this box.
  40306. *
  40307. * @param {Vector2} point - The point to test.
  40308. * @return {boolean} Whether the bounding box contains the given point or not.
  40309. */
  40310. containsPoint( point ) {
  40311. return point.x >= this.min.x && point.x <= this.max.x &&
  40312. point.y >= this.min.y && point.y <= this.max.y;
  40313. }
  40314. /**
  40315. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40316. * If this box and the given one are identical, this function also returns `true`.
  40317. *
  40318. * @param {Box2} box - The bounding box to test.
  40319. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40320. */
  40321. containsBox( box ) {
  40322. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40323. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40324. }
  40325. /**
  40326. * Returns a point as a proportion of this box's width and height.
  40327. *
  40328. * @param {Vector2} point - A point in 2D space.
  40329. * @param {Vector2} target - The target vector that is used to store the method's result.
  40330. * @return {Vector2} A point as a proportion of this box's width and height.
  40331. */
  40332. getParameter( point, target ) {
  40333. // This can potentially have a divide by zero if the box
  40334. // has a size dimension of 0.
  40335. return target.set(
  40336. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40337. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40338. );
  40339. }
  40340. /**
  40341. * Returns `true` if the given bounding box intersects with this bounding box.
  40342. *
  40343. * @param {Box2} box - The bounding box to test.
  40344. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40345. */
  40346. intersectsBox( box ) {
  40347. // using 4 splitting planes to rule out intersections
  40348. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40349. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40350. }
  40351. /**
  40352. * Clamps the given point within the bounds of this box.
  40353. *
  40354. * @param {Vector2} point - The point to clamp.
  40355. * @param {Vector2} target - The target vector that is used to store the method's result.
  40356. * @return {Vector2} The clamped point.
  40357. */
  40358. clampPoint( point, target ) {
  40359. return target.copy( point ).clamp( this.min, this.max );
  40360. }
  40361. /**
  40362. * Returns the euclidean distance from any edge of this box to the specified point. If
  40363. * the given point lies inside of this box, the distance will be `0`.
  40364. *
  40365. * @param {Vector2} point - The point to compute the distance to.
  40366. * @return {number} The euclidean distance.
  40367. */
  40368. distanceToPoint( point ) {
  40369. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40370. }
  40371. /**
  40372. * Computes the intersection of this bounding box and the given one, setting the upper
  40373. * bound of this box to the lesser of the two boxes' upper bounds and the
  40374. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40375. * there's no overlap, makes this box empty.
  40376. *
  40377. * @param {Box2} box - The bounding box to intersect with.
  40378. * @return {Box2} A reference to this bounding box.
  40379. */
  40380. intersect( box ) {
  40381. this.min.max( box.min );
  40382. this.max.min( box.max );
  40383. if ( this.isEmpty() ) this.makeEmpty();
  40384. return this;
  40385. }
  40386. /**
  40387. * Computes the union of this box and another and the given one, setting the upper
  40388. * bound of this box to the greater of the two boxes' upper bounds and the
  40389. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40390. *
  40391. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40392. * @return {Box2} A reference to this bounding box.
  40393. */
  40394. union( box ) {
  40395. this.min.min( box.min );
  40396. this.max.max( box.max );
  40397. return this;
  40398. }
  40399. /**
  40400. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40401. * effectively moving it in 2D space.
  40402. *
  40403. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40404. * @return {Box2} A reference to this bounding box.
  40405. */
  40406. translate( offset ) {
  40407. this.min.add( offset );
  40408. this.max.add( offset );
  40409. return this;
  40410. }
  40411. /**
  40412. * Returns `true` if this bounding box is equal with the given one.
  40413. *
  40414. * @param {Box2} box - The box to test for equality.
  40415. * @return {boolean} Whether this bounding box is equal with the given one.
  40416. */
  40417. equals( box ) {
  40418. return box.min.equals( this.min ) && box.max.equals( this.max );
  40419. }
  40420. }
  40421. const _startP = /*@__PURE__*/ new Vector3();
  40422. const _startEnd = /*@__PURE__*/ new Vector3();
  40423. const _d1 = /*@__PURE__*/ new Vector3();
  40424. const _d2 = /*@__PURE__*/ new Vector3();
  40425. const _r = /*@__PURE__*/ new Vector3();
  40426. const _c1 = /*@__PURE__*/ new Vector3();
  40427. const _c2 = /*@__PURE__*/ new Vector3();
  40428. /**
  40429. * An analytical line segment in 3D space represented by a start and end point.
  40430. */
  40431. class Line3 {
  40432. /**
  40433. * Constructs a new line segment.
  40434. *
  40435. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40436. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40437. */
  40438. constructor( start = new Vector3(), end = new Vector3() ) {
  40439. /**
  40440. * Start of the line segment.
  40441. *
  40442. * @type {Vector3}
  40443. */
  40444. this.start = start;
  40445. /**
  40446. * End of the line segment.
  40447. *
  40448. * @type {Vector3}
  40449. */
  40450. this.end = end;
  40451. }
  40452. /**
  40453. * Sets the start and end values by copying the given vectors.
  40454. *
  40455. * @param {Vector3} start - The start point.
  40456. * @param {Vector3} end - The end point.
  40457. * @return {Line3} A reference to this line segment.
  40458. */
  40459. set( start, end ) {
  40460. this.start.copy( start );
  40461. this.end.copy( end );
  40462. return this;
  40463. }
  40464. /**
  40465. * Copies the values of the given line segment to this instance.
  40466. *
  40467. * @param {Line3} line - The line segment to copy.
  40468. * @return {Line3} A reference to this line segment.
  40469. */
  40470. copy( line ) {
  40471. this.start.copy( line.start );
  40472. this.end.copy( line.end );
  40473. return this;
  40474. }
  40475. /**
  40476. * Returns the center of the line segment.
  40477. *
  40478. * @param {Vector3} target - The target vector that is used to store the method's result.
  40479. * @return {Vector3} The center point.
  40480. */
  40481. getCenter( target ) {
  40482. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40483. }
  40484. /**
  40485. * Returns the delta vector of the line segment's start and end point.
  40486. *
  40487. * @param {Vector3} target - The target vector that is used to store the method's result.
  40488. * @return {Vector3} The delta vector.
  40489. */
  40490. delta( target ) {
  40491. return target.subVectors( this.end, this.start );
  40492. }
  40493. /**
  40494. * Returns the squared Euclidean distance between the line' start and end point.
  40495. *
  40496. * @return {number} The squared Euclidean distance.
  40497. */
  40498. distanceSq() {
  40499. return this.start.distanceToSquared( this.end );
  40500. }
  40501. /**
  40502. * Returns the Euclidean distance between the line' start and end point.
  40503. *
  40504. * @return {number} The Euclidean distance.
  40505. */
  40506. distance() {
  40507. return this.start.distanceTo( this.end );
  40508. }
  40509. /**
  40510. * Returns a vector at a certain position along the line segment.
  40511. *
  40512. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40513. * @param {Vector3} target - The target vector that is used to store the method's result.
  40514. * @return {Vector3} The delta vector.
  40515. */
  40516. at( t, target ) {
  40517. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40518. }
  40519. /**
  40520. * Returns a point parameter based on the closest point as projected on the line segment.
  40521. *
  40522. * @param {Vector3} point - The point for which to return a point parameter.
  40523. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40524. * @return {number} The point parameter.
  40525. */
  40526. closestPointToPointParameter( point, clampToLine ) {
  40527. _startP.subVectors( point, this.start );
  40528. _startEnd.subVectors( this.end, this.start );
  40529. const startEnd2 = _startEnd.dot( _startEnd );
  40530. const startEnd_startP = _startEnd.dot( _startP );
  40531. let t = startEnd_startP / startEnd2;
  40532. if ( clampToLine ) {
  40533. t = clamp( t, 0, 1 );
  40534. }
  40535. return t;
  40536. }
  40537. /**
  40538. * Returns the closest point on the line for a given point.
  40539. *
  40540. * @param {Vector3} point - The point to compute the closest point on the line for.
  40541. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40542. * @param {Vector3} target - The target vector that is used to store the method's result.
  40543. * @return {Vector3} The closest point on the line.
  40544. */
  40545. closestPointToPoint( point, clampToLine, target ) {
  40546. const t = this.closestPointToPointParameter( point, clampToLine );
  40547. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40548. }
  40549. /**
  40550. * Returns the closest squared distance between this line segment and the given one.
  40551. *
  40552. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40553. * @param {Vector3} [c1] - The closest point on this line segment.
  40554. * @param {Vector3} [c2] - The closest point on the given line segment.
  40555. * @return {number} The squared distance between this line segment and the given one.
  40556. */
  40557. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40558. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40559. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40560. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40561. // distance between between S1(s) and S2(t)
  40562. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40563. let s, t;
  40564. const p1 = this.start;
  40565. const p2 = line.start;
  40566. const q1 = this.end;
  40567. const q2 = line.end;
  40568. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40569. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40570. _r.subVectors( p1, p2 );
  40571. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40572. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40573. const f = _d2.dot( _r );
  40574. // Check if either or both segments degenerate into points
  40575. if ( a <= EPSILON && e <= EPSILON ) {
  40576. // Both segments degenerate into points
  40577. c1.copy( p1 );
  40578. c2.copy( p2 );
  40579. c1.sub( c2 );
  40580. return c1.dot( c1 );
  40581. }
  40582. if ( a <= EPSILON ) {
  40583. // First segment degenerates into a point
  40584. s = 0;
  40585. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40586. t = clamp( t, 0, 1 );
  40587. } else {
  40588. const c = _d1.dot( _r );
  40589. if ( e <= EPSILON ) {
  40590. // Second segment degenerates into a point
  40591. t = 0;
  40592. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40593. } else {
  40594. // The general nondegenerate case starts here
  40595. const b = _d1.dot( _d2 );
  40596. const denom = a * e - b * b; // Always nonnegative
  40597. // If segments not parallel, compute closest point on L1 to L2 and
  40598. // clamp to segment S1. Else pick arbitrary s (here 0)
  40599. if ( denom !== 0 ) {
  40600. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40601. } else {
  40602. s = 0;
  40603. }
  40604. // Compute point on L2 closest to S1(s) using
  40605. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40606. t = ( b * s + f ) / e;
  40607. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40608. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40609. // and clamp s to [0, 1]
  40610. if ( t < 0 ) {
  40611. t = 0.;
  40612. s = clamp( - c / a, 0, 1 );
  40613. } else if ( t > 1 ) {
  40614. t = 1;
  40615. s = clamp( ( b - c ) / a, 0, 1 );
  40616. }
  40617. }
  40618. }
  40619. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40620. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40621. c1.sub( c2 );
  40622. return c1.dot( c1 );
  40623. }
  40624. /**
  40625. * Applies a 4x4 transformation matrix to this line segment.
  40626. *
  40627. * @param {Matrix4} matrix - The transformation matrix.
  40628. * @return {Line3} A reference to this line segment.
  40629. */
  40630. applyMatrix4( matrix ) {
  40631. this.start.applyMatrix4( matrix );
  40632. this.end.applyMatrix4( matrix );
  40633. return this;
  40634. }
  40635. /**
  40636. * Returns `true` if this line segment is equal with the given one.
  40637. *
  40638. * @param {Line3} line - The line segment to test for equality.
  40639. * @return {boolean} Whether this line segment is equal with the given one.
  40640. */
  40641. equals( line ) {
  40642. return line.start.equals( this.start ) && line.end.equals( this.end );
  40643. }
  40644. /**
  40645. * Returns a new line segment with copied values from this instance.
  40646. *
  40647. * @return {Line3} A clone of this instance.
  40648. */
  40649. clone() {
  40650. return new this.constructor().copy( this );
  40651. }
  40652. }
  40653. const _vector$3 = /*@__PURE__*/ new Vector3();
  40654. /**
  40655. * This displays a cone shaped helper object for a {@link SpotLight}.
  40656. *
  40657. * ```js
  40658. * const spotLight = new THREE.SpotLight( 0xffffff );
  40659. * spotLight.position.set( 10, 10, 10 );
  40660. * scene.add( spotLight );
  40661. *
  40662. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40663. * scene.add( spotLightHelper );
  40664. * ```
  40665. *
  40666. * @augments Object3D
  40667. */
  40668. class SpotLightHelper extends Object3D {
  40669. /**
  40670. * Constructs a new spot light helper.
  40671. *
  40672. * @param {HemisphereLight} light - The light to be visualized.
  40673. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40674. * the color of the light.
  40675. */
  40676. constructor( light, color ) {
  40677. super();
  40678. /**
  40679. * The light being visualized.
  40680. *
  40681. * @type {SpotLight}
  40682. */
  40683. this.light = light;
  40684. this.matrixAutoUpdate = false;
  40685. /**
  40686. * The color parameter passed in the constructor.
  40687. * If not set, the helper will take the color of the light.
  40688. *
  40689. * @type {number|Color|string}
  40690. */
  40691. this.color = color;
  40692. this.type = 'SpotLightHelper';
  40693. const geometry = new BufferGeometry();
  40694. const positions = [
  40695. 0, 0, 0, 0, 0, 1,
  40696. 0, 0, 0, 1, 0, 1,
  40697. 0, 0, 0, -1, 0, 1,
  40698. 0, 0, 0, 0, 1, 1,
  40699. 0, 0, 0, 0, -1, 1
  40700. ];
  40701. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40702. const p1 = ( i / l ) * Math.PI * 2;
  40703. const p2 = ( j / l ) * Math.PI * 2;
  40704. positions.push(
  40705. Math.cos( p1 ), Math.sin( p1 ), 1,
  40706. Math.cos( p2 ), Math.sin( p2 ), 1
  40707. );
  40708. }
  40709. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40710. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40711. this.cone = new LineSegments( geometry, material );
  40712. this.add( this.cone );
  40713. this.update();
  40714. }
  40715. /**
  40716. * Frees the GPU-related resources allocated by this instance. Call this
  40717. * method whenever this instance is no longer used in your app.
  40718. */
  40719. dispose() {
  40720. this.cone.geometry.dispose();
  40721. this.cone.material.dispose();
  40722. }
  40723. /**
  40724. * Updates the helper to match the position and direction of the
  40725. * light being visualized.
  40726. */
  40727. update() {
  40728. this.light.updateWorldMatrix( true, false );
  40729. this.light.target.updateWorldMatrix( true, false );
  40730. // update the local matrix based on the parent and light target transforms
  40731. if ( this.parent ) {
  40732. this.parent.updateWorldMatrix( true );
  40733. this.matrix
  40734. .copy( this.parent.matrixWorld )
  40735. .invert()
  40736. .multiply( this.light.matrixWorld );
  40737. } else {
  40738. this.matrix.copy( this.light.matrixWorld );
  40739. }
  40740. this.matrixWorld.copy( this.light.matrixWorld );
  40741. const coneLength = this.light.distance ? this.light.distance : 1000;
  40742. const coneWidth = coneLength * Math.tan( this.light.angle );
  40743. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40744. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40745. this.cone.lookAt( _vector$3 );
  40746. if ( this.color !== undefined ) {
  40747. this.cone.material.color.set( this.color );
  40748. } else {
  40749. this.cone.material.color.copy( this.light.color );
  40750. }
  40751. }
  40752. }
  40753. const _vector$2 = /*@__PURE__*/ new Vector3();
  40754. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40755. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40756. /**
  40757. * A helper object to assist with visualizing a {@link Skeleton}.
  40758. *
  40759. * ```js
  40760. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40761. * scene.add( helper );
  40762. * ```
  40763. *
  40764. * @augments LineSegments
  40765. */
  40766. class SkeletonHelper extends LineSegments {
  40767. /**
  40768. * Constructs a new skeleton helper.
  40769. *
  40770. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40771. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40772. */
  40773. constructor( object ) {
  40774. const bones = getBoneList( object );
  40775. const geometry = new BufferGeometry();
  40776. const vertices = [];
  40777. const colors = [];
  40778. for ( let i = 0; i < bones.length; i ++ ) {
  40779. const bone = bones[ i ];
  40780. if ( bone.parent && bone.parent.isBone ) {
  40781. vertices.push( 0, 0, 0 );
  40782. vertices.push( 0, 0, 0 );
  40783. colors.push( 0, 0, 0 );
  40784. colors.push( 0, 0, 0 );
  40785. }
  40786. }
  40787. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40788. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40789. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40790. super( geometry, material );
  40791. /**
  40792. * This flag can be used for type testing.
  40793. *
  40794. * @type {boolean}
  40795. * @readonly
  40796. * @default true
  40797. */
  40798. this.isSkeletonHelper = true;
  40799. this.type = 'SkeletonHelper';
  40800. /**
  40801. * The object being visualized.
  40802. *
  40803. * @type {Object3D}
  40804. */
  40805. this.root = object;
  40806. /**
  40807. * The list of bones that the helper visualizes.
  40808. *
  40809. * @type {Array<Bone>}
  40810. */
  40811. this.bones = bones;
  40812. this.matrix = object.matrixWorld;
  40813. this.matrixAutoUpdate = false;
  40814. // colors
  40815. const color1 = new Color( 0x0000ff );
  40816. const color2 = new Color( 0x00ff00 );
  40817. this.setColors( color1, color2 );
  40818. }
  40819. updateMatrixWorld( force ) {
  40820. const bones = this.bones;
  40821. const geometry = this.geometry;
  40822. const position = geometry.getAttribute( 'position' );
  40823. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40824. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40825. const bone = bones[ i ];
  40826. if ( bone.parent && bone.parent.isBone ) {
  40827. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40828. _vector$2.setFromMatrixPosition( _boneMatrix );
  40829. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40830. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40831. _vector$2.setFromMatrixPosition( _boneMatrix );
  40832. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40833. j += 2;
  40834. }
  40835. }
  40836. geometry.getAttribute( 'position' ).needsUpdate = true;
  40837. super.updateMatrixWorld( force );
  40838. }
  40839. /**
  40840. * Defines the colors of the helper.
  40841. *
  40842. * @param {Color} color1 - The first line color for each bone.
  40843. * @param {Color} color2 - The second line color for each bone.
  40844. * @return {SkeletonHelper} A reference to this helper.
  40845. */
  40846. setColors( color1, color2 ) {
  40847. const geometry = this.geometry;
  40848. const colorAttribute = geometry.getAttribute( 'color' );
  40849. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40850. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40851. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40852. }
  40853. colorAttribute.needsUpdate = true;
  40854. return this;
  40855. }
  40856. /**
  40857. * Frees the GPU-related resources allocated by this instance. Call this
  40858. * method whenever this instance is no longer used in your app.
  40859. */
  40860. dispose() {
  40861. this.geometry.dispose();
  40862. this.material.dispose();
  40863. }
  40864. }
  40865. function getBoneList( object ) {
  40866. const boneList = [];
  40867. if ( object.isBone === true ) {
  40868. boneList.push( object );
  40869. }
  40870. for ( let i = 0; i < object.children.length; i ++ ) {
  40871. boneList.push( ...getBoneList( object.children[ i ] ) );
  40872. }
  40873. return boneList;
  40874. }
  40875. /**
  40876. * This displays a helper object consisting of a spherical mesh for
  40877. * visualizing an instance of {@link PointLight}.
  40878. *
  40879. * ```js
  40880. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40881. * pointLight.position.set( 10, 10, 10 );
  40882. * scene.add( pointLight );
  40883. *
  40884. * const sphereSize = 1;
  40885. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40886. * scene.add( pointLightHelper );
  40887. * ```
  40888. *
  40889. * @augments Mesh
  40890. */
  40891. class PointLightHelper extends Mesh {
  40892. /**
  40893. * Constructs a new point light helper.
  40894. *
  40895. * @param {PointLight} light - The light to be visualized.
  40896. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40897. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40898. * the color of the light.
  40899. */
  40900. constructor( light, sphereSize, color ) {
  40901. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40902. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40903. super( geometry, material );
  40904. /**
  40905. * The light being visualized.
  40906. *
  40907. * @type {HemisphereLight}
  40908. */
  40909. this.light = light;
  40910. /**
  40911. * The color parameter passed in the constructor.
  40912. * If not set, the helper will take the color of the light.
  40913. *
  40914. * @type {number|Color|string}
  40915. */
  40916. this.color = color;
  40917. this.type = 'PointLightHelper';
  40918. this.matrix = this.light.matrixWorld;
  40919. this.matrixAutoUpdate = false;
  40920. this.update();
  40921. /*
  40922. // TODO: delete this comment?
  40923. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40924. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40925. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40926. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40927. const d = light.distance;
  40928. if ( d === 0.0 ) {
  40929. this.lightDistance.visible = false;
  40930. } else {
  40931. this.lightDistance.scale.set( d, d, d );
  40932. }
  40933. this.add( this.lightDistance );
  40934. */
  40935. }
  40936. /**
  40937. * Frees the GPU-related resources allocated by this instance. Call this
  40938. * method whenever this instance is no longer used in your app.
  40939. */
  40940. dispose() {
  40941. this.geometry.dispose();
  40942. this.material.dispose();
  40943. }
  40944. /**
  40945. * Updates the helper to match the position of the
  40946. * light being visualized.
  40947. */
  40948. update() {
  40949. this.light.updateWorldMatrix( true, false );
  40950. if ( this.color !== undefined ) {
  40951. this.material.color.set( this.color );
  40952. } else {
  40953. this.material.color.copy( this.light.color );
  40954. }
  40955. /*
  40956. const d = this.light.distance;
  40957. if ( d === 0.0 ) {
  40958. this.lightDistance.visible = false;
  40959. } else {
  40960. this.lightDistance.visible = true;
  40961. this.lightDistance.scale.set( d, d, d );
  40962. }
  40963. */
  40964. }
  40965. }
  40966. const _vector$1 = /*@__PURE__*/ new Vector3();
  40967. const _color1 = /*@__PURE__*/ new Color();
  40968. const _color2 = /*@__PURE__*/ new Color();
  40969. /**
  40970. * Creates a visual aid consisting of a spherical mesh for a
  40971. * given {@link HemisphereLight}.
  40972. *
  40973. * ```js
  40974. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40975. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40976. * scene.add( helper );
  40977. * ```
  40978. *
  40979. * @augments Object3D
  40980. */
  40981. class HemisphereLightHelper extends Object3D {
  40982. /**
  40983. * Constructs a new hemisphere light helper.
  40984. *
  40985. * @param {HemisphereLight} light - The light to be visualized.
  40986. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40987. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40988. * the color of the light.
  40989. */
  40990. constructor( light, size, color ) {
  40991. super();
  40992. /**
  40993. * The light being visualized.
  40994. *
  40995. * @type {HemisphereLight}
  40996. */
  40997. this.light = light;
  40998. this.matrix = light.matrixWorld;
  40999. this.matrixAutoUpdate = false;
  41000. /**
  41001. * The color parameter passed in the constructor.
  41002. * If not set, the helper will take the color of the light.
  41003. *
  41004. * @type {number|Color|string}
  41005. */
  41006. this.color = color;
  41007. this.type = 'HemisphereLightHelper';
  41008. const geometry = new OctahedronGeometry( size );
  41009. geometry.rotateY( Math.PI * 0.5 );
  41010. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41011. if ( this.color === undefined ) this.material.vertexColors = true;
  41012. const position = geometry.getAttribute( 'position' );
  41013. const colors = new Float32Array( position.count * 3 );
  41014. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41015. this.add( new Mesh( geometry, this.material ) );
  41016. this.update();
  41017. }
  41018. /**
  41019. * Frees the GPU-related resources allocated by this instance. Call this
  41020. * method whenever this instance is no longer used in your app.
  41021. */
  41022. dispose() {
  41023. this.children[ 0 ].geometry.dispose();
  41024. this.children[ 0 ].material.dispose();
  41025. }
  41026. /**
  41027. * Updates the helper to match the position and direction of the
  41028. * light being visualized.
  41029. */
  41030. update() {
  41031. const mesh = this.children[ 0 ];
  41032. if ( this.color !== undefined ) {
  41033. this.material.color.set( this.color );
  41034. } else {
  41035. const colors = mesh.geometry.getAttribute( 'color' );
  41036. _color1.copy( this.light.color );
  41037. _color2.copy( this.light.groundColor );
  41038. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41039. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41040. colors.setXYZ( i, color.r, color.g, color.b );
  41041. }
  41042. colors.needsUpdate = true;
  41043. }
  41044. this.light.updateWorldMatrix( true, false );
  41045. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41046. }
  41047. }
  41048. /**
  41049. * The helper is an object to define grids. Grids are two-dimensional
  41050. * arrays of lines.
  41051. *
  41052. * ```js
  41053. * const size = 10;
  41054. * const divisions = 10;
  41055. *
  41056. * const gridHelper = new THREE.GridHelper( size, divisions );
  41057. * scene.add( gridHelper );
  41058. * ```
  41059. *
  41060. * @augments LineSegments
  41061. */
  41062. class GridHelper extends LineSegments {
  41063. /**
  41064. * Constructs a new grid helper.
  41065. *
  41066. * @param {number} [size=10] - The size of the grid.
  41067. * @param {number} [divisions=10] - The number of divisions across the grid.
  41068. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41069. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41070. */
  41071. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41072. color1 = new Color( color1 );
  41073. color2 = new Color( color2 );
  41074. const center = divisions / 2;
  41075. const step = size / divisions;
  41076. const halfSize = size / 2;
  41077. const vertices = [], colors = [];
  41078. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41079. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41080. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41081. const color = i === center ? color1 : color2;
  41082. color.toArray( colors, j ); j += 3;
  41083. color.toArray( colors, j ); j += 3;
  41084. color.toArray( colors, j ); j += 3;
  41085. color.toArray( colors, j ); j += 3;
  41086. }
  41087. const geometry = new BufferGeometry();
  41088. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41089. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41090. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41091. super( geometry, material );
  41092. this.type = 'GridHelper';
  41093. }
  41094. /**
  41095. * Frees the GPU-related resources allocated by this instance. Call this
  41096. * method whenever this instance is no longer used in your app.
  41097. */
  41098. dispose() {
  41099. this.geometry.dispose();
  41100. this.material.dispose();
  41101. }
  41102. }
  41103. /**
  41104. * This helper is an object to define polar grids. Grids are
  41105. * two-dimensional arrays of lines.
  41106. *
  41107. * ```js
  41108. * const radius = 10;
  41109. * const sectors = 16;
  41110. * const rings = 8;
  41111. * const divisions = 64;
  41112. *
  41113. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41114. * scene.add( helper );
  41115. * ```
  41116. *
  41117. * @augments LineSegments
  41118. */
  41119. class PolarGridHelper extends LineSegments {
  41120. /**
  41121. * Constructs a new polar grid helper.
  41122. *
  41123. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41124. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41125. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41126. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41127. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41128. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41129. */
  41130. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41131. color1 = new Color( color1 );
  41132. color2 = new Color( color2 );
  41133. const vertices = [];
  41134. const colors = [];
  41135. // create the sectors
  41136. if ( sectors > 1 ) {
  41137. for ( let i = 0; i < sectors; i ++ ) {
  41138. const v = ( i / sectors ) * ( Math.PI * 2 );
  41139. const x = Math.sin( v ) * radius;
  41140. const z = Math.cos( v ) * radius;
  41141. vertices.push( 0, 0, 0 );
  41142. vertices.push( x, 0, z );
  41143. const color = ( i & 1 ) ? color1 : color2;
  41144. colors.push( color.r, color.g, color.b );
  41145. colors.push( color.r, color.g, color.b );
  41146. }
  41147. }
  41148. // create the rings
  41149. for ( let i = 0; i < rings; i ++ ) {
  41150. const color = ( i & 1 ) ? color1 : color2;
  41151. const r = radius - ( radius / rings * i );
  41152. for ( let j = 0; j < divisions; j ++ ) {
  41153. // first vertex
  41154. let v = ( j / divisions ) * ( Math.PI * 2 );
  41155. let x = Math.sin( v ) * r;
  41156. let z = Math.cos( v ) * r;
  41157. vertices.push( x, 0, z );
  41158. colors.push( color.r, color.g, color.b );
  41159. // second vertex
  41160. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41161. x = Math.sin( v ) * r;
  41162. z = Math.cos( v ) * r;
  41163. vertices.push( x, 0, z );
  41164. colors.push( color.r, color.g, color.b );
  41165. }
  41166. }
  41167. const geometry = new BufferGeometry();
  41168. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41169. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41170. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41171. super( geometry, material );
  41172. this.type = 'PolarGridHelper';
  41173. }
  41174. /**
  41175. * Frees the GPU-related resources allocated by this instance. Call this
  41176. * method whenever this instance is no longer used in your app.
  41177. */
  41178. dispose() {
  41179. this.geometry.dispose();
  41180. this.material.dispose();
  41181. }
  41182. }
  41183. const _v1 = /*@__PURE__*/ new Vector3();
  41184. const _v2 = /*@__PURE__*/ new Vector3();
  41185. const _v3 = /*@__PURE__*/ new Vector3();
  41186. /**
  41187. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41188. * effect on the scene. This consists of plane and a line representing the
  41189. * light's position and direction.
  41190. *
  41191. * ```js
  41192. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41193. * scene.add( light );
  41194. *
  41195. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41196. * scene.add( helper );
  41197. * ```
  41198. *
  41199. * @augments Object3D
  41200. */
  41201. class DirectionalLightHelper extends Object3D {
  41202. /**
  41203. * Constructs a new directional light helper.
  41204. *
  41205. * @param {DirectionalLight} light - The light to be visualized.
  41206. * @param {number} [size=1] - The dimensions of the plane.
  41207. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41208. * the color of the light.
  41209. */
  41210. constructor( light, size, color ) {
  41211. super();
  41212. /**
  41213. * The light being visualized.
  41214. *
  41215. * @type {DirectionalLight}
  41216. */
  41217. this.light = light;
  41218. this.matrix = light.matrixWorld;
  41219. this.matrixAutoUpdate = false;
  41220. /**
  41221. * The color parameter passed in the constructor.
  41222. * If not set, the helper will take the color of the light.
  41223. *
  41224. * @type {number|Color|string}
  41225. */
  41226. this.color = color;
  41227. this.type = 'DirectionalLightHelper';
  41228. if ( size === undefined ) size = 1;
  41229. let geometry = new BufferGeometry();
  41230. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41231. - size, size, 0,
  41232. size, size, 0,
  41233. size, - size, 0,
  41234. - size, - size, 0,
  41235. - size, size, 0
  41236. ], 3 ) );
  41237. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41238. /**
  41239. * Contains the line showing the location of the directional light.
  41240. *
  41241. * @type {Line}
  41242. */
  41243. this.lightPlane = new Line( geometry, material );
  41244. this.add( this.lightPlane );
  41245. geometry = new BufferGeometry();
  41246. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41247. /**
  41248. * Represents the target line of the directional light.
  41249. *
  41250. * @type {Line}
  41251. */
  41252. this.targetLine = new Line( geometry, material );
  41253. this.add( this.targetLine );
  41254. this.update();
  41255. }
  41256. /**
  41257. * Frees the GPU-related resources allocated by this instance. Call this
  41258. * method whenever this instance is no longer used in your app.
  41259. */
  41260. dispose() {
  41261. this.lightPlane.geometry.dispose();
  41262. this.lightPlane.material.dispose();
  41263. this.targetLine.geometry.dispose();
  41264. this.targetLine.material.dispose();
  41265. }
  41266. /**
  41267. * Updates the helper to match the position and direction of the
  41268. * light being visualized.
  41269. */
  41270. update() {
  41271. this.light.updateWorldMatrix( true, false );
  41272. this.light.target.updateWorldMatrix( true, false );
  41273. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41274. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41275. _v3.subVectors( _v2, _v1 );
  41276. this.lightPlane.lookAt( _v2 );
  41277. if ( this.color !== undefined ) {
  41278. this.lightPlane.material.color.set( this.color );
  41279. this.targetLine.material.color.set( this.color );
  41280. } else {
  41281. this.lightPlane.material.color.copy( this.light.color );
  41282. this.targetLine.material.color.copy( this.light.color );
  41283. }
  41284. this.targetLine.lookAt( _v2 );
  41285. this.targetLine.scale.z = _v3.length();
  41286. }
  41287. }
  41288. const _vector = /*@__PURE__*/ new Vector3();
  41289. const _camera = /*@__PURE__*/ new Camera();
  41290. /**
  41291. * This helps with visualizing what a camera contains in its frustum. It
  41292. * visualizes the frustum of a camera using a line segments.
  41293. *
  41294. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41295. *
  41296. * `CameraHelper` must be a child of the scene.
  41297. *
  41298. * ```js
  41299. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41300. * const helper = new THREE.CameraHelper( camera );
  41301. * scene.add( helper );
  41302. * ```
  41303. *
  41304. * @augments LineSegments
  41305. */
  41306. class CameraHelper extends LineSegments {
  41307. /**
  41308. * Constructs a new arrow helper.
  41309. *
  41310. * @param {Camera} camera - The camera to visualize.
  41311. */
  41312. constructor( camera ) {
  41313. const geometry = new BufferGeometry();
  41314. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41315. const vertices = [];
  41316. const colors = [];
  41317. const pointMap = {};
  41318. // near
  41319. addLine( 'n1', 'n2' );
  41320. addLine( 'n2', 'n4' );
  41321. addLine( 'n4', 'n3' );
  41322. addLine( 'n3', 'n1' );
  41323. // far
  41324. addLine( 'f1', 'f2' );
  41325. addLine( 'f2', 'f4' );
  41326. addLine( 'f4', 'f3' );
  41327. addLine( 'f3', 'f1' );
  41328. // sides
  41329. addLine( 'n1', 'f1' );
  41330. addLine( 'n2', 'f2' );
  41331. addLine( 'n3', 'f3' );
  41332. addLine( 'n4', 'f4' );
  41333. // cone
  41334. addLine( 'p', 'n1' );
  41335. addLine( 'p', 'n2' );
  41336. addLine( 'p', 'n3' );
  41337. addLine( 'p', 'n4' );
  41338. // up
  41339. addLine( 'u1', 'u2' );
  41340. addLine( 'u2', 'u3' );
  41341. addLine( 'u3', 'u1' );
  41342. // target
  41343. addLine( 'c', 't' );
  41344. addLine( 'p', 'c' );
  41345. // cross
  41346. addLine( 'cn1', 'cn2' );
  41347. addLine( 'cn3', 'cn4' );
  41348. addLine( 'cf1', 'cf2' );
  41349. addLine( 'cf3', 'cf4' );
  41350. function addLine( a, b ) {
  41351. addPoint( a );
  41352. addPoint( b );
  41353. }
  41354. function addPoint( id ) {
  41355. vertices.push( 0, 0, 0 );
  41356. colors.push( 0, 0, 0 );
  41357. if ( pointMap[ id ] === undefined ) {
  41358. pointMap[ id ] = [];
  41359. }
  41360. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41361. }
  41362. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41363. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41364. super( geometry, material );
  41365. this.type = 'CameraHelper';
  41366. /**
  41367. * The camera being visualized.
  41368. *
  41369. * @type {Camera}
  41370. */
  41371. this.camera = camera;
  41372. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41373. this.matrix = camera.matrixWorld;
  41374. this.matrixAutoUpdate = false;
  41375. /**
  41376. * This contains the points used to visualize the camera.
  41377. *
  41378. * @type {Object<string,Array<number>>}
  41379. */
  41380. this.pointMap = pointMap;
  41381. this.update();
  41382. // colors
  41383. const colorFrustum = new Color( 0xffaa00 );
  41384. const colorCone = new Color( 0xff0000 );
  41385. const colorUp = new Color( 0x00aaff );
  41386. const colorTarget = new Color( 0xffffff );
  41387. const colorCross = new Color( 0x333333 );
  41388. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41389. }
  41390. /**
  41391. * Defines the colors of the helper.
  41392. *
  41393. * @param {Color} frustum - The frustum line color.
  41394. * @param {Color} cone - The cone line color.
  41395. * @param {Color} up - The up line color.
  41396. * @param {Color} target - The target line color.
  41397. * @param {Color} cross - The cross line color.
  41398. * @return {CameraHelper} A reference to this helper.
  41399. */
  41400. setColors( frustum, cone, up, target, cross ) {
  41401. const geometry = this.geometry;
  41402. const colorAttribute = geometry.getAttribute( 'color' );
  41403. // near
  41404. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41405. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41406. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41407. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41408. // far
  41409. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41410. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41411. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41412. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41413. // sides
  41414. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41415. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41416. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41417. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41418. // cone
  41419. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41420. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41421. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41422. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41423. // up
  41424. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41425. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41426. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41427. // target
  41428. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41429. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41430. // cross
  41431. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41432. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41433. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41434. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41435. colorAttribute.needsUpdate = true;
  41436. return this;
  41437. }
  41438. /**
  41439. * Updates the helper based on the projection matrix of the camera.
  41440. */
  41441. update() {
  41442. const geometry = this.geometry;
  41443. const pointMap = this.pointMap;
  41444. const w = 1, h = 1;
  41445. let nearZ, farZ;
  41446. // we need just camera projection matrix inverse
  41447. // world matrix must be identity
  41448. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41449. // Adjust z values based on coordinate system
  41450. if ( this.camera.reversedDepth === true ) {
  41451. nearZ = 1;
  41452. farZ = 0;
  41453. } else {
  41454. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41455. nearZ = -1;
  41456. farZ = 1;
  41457. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41458. nearZ = 0;
  41459. farZ = 1;
  41460. } else {
  41461. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41462. }
  41463. }
  41464. // center / target
  41465. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41466. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41467. // near
  41468. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41469. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41470. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41471. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41472. // far
  41473. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41474. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41475. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41476. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41477. // up
  41478. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41479. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41480. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41481. // cross
  41482. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41483. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41484. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41485. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41486. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41487. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41488. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41489. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41490. geometry.getAttribute( 'position' ).needsUpdate = true;
  41491. }
  41492. /**
  41493. * Frees the GPU-related resources allocated by this instance. Call this
  41494. * method whenever this instance is no longer used in your app.
  41495. */
  41496. dispose() {
  41497. this.geometry.dispose();
  41498. this.material.dispose();
  41499. }
  41500. }
  41501. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41502. _vector.set( x, y, z ).unproject( camera );
  41503. const points = pointMap[ point ];
  41504. if ( points !== undefined ) {
  41505. const position = geometry.getAttribute( 'position' );
  41506. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41507. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41508. }
  41509. }
  41510. }
  41511. const _box = /*@__PURE__*/ new Box3();
  41512. /**
  41513. * Helper object to graphically show the world-axis-aligned bounding box
  41514. * around an object. The actual bounding box is handled with {@link Box3},
  41515. * this is just a visual helper for debugging. It can be automatically
  41516. * resized with {@link BoxHelper#update} when the object it's created from
  41517. * is transformed. Note that the object must have a geometry for this to work,
  41518. * so it won't work with sprites.
  41519. *
  41520. * ```js
  41521. * const sphere = new THREE.SphereGeometry();
  41522. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41523. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41524. * scene.add( box );
  41525. * ```
  41526. *
  41527. * @augments LineSegments
  41528. */
  41529. class BoxHelper extends LineSegments {
  41530. /**
  41531. * Constructs a new box helper.
  41532. *
  41533. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41534. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41535. */
  41536. constructor( object, color = 0xffff00 ) {
  41537. 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 ] );
  41538. const positions = new Float32Array( 8 * 3 );
  41539. const geometry = new BufferGeometry();
  41540. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41541. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41542. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41543. /**
  41544. * The 3D object being visualized.
  41545. *
  41546. * @type {Object3D}
  41547. */
  41548. this.object = object;
  41549. this.type = 'BoxHelper';
  41550. this.matrixAutoUpdate = false;
  41551. this.update();
  41552. }
  41553. /**
  41554. * Updates the helper's geometry to match the dimensions of the object,
  41555. * including any children.
  41556. */
  41557. update() {
  41558. if ( this.object !== undefined ) {
  41559. _box.setFromObject( this.object );
  41560. }
  41561. if ( _box.isEmpty() ) return;
  41562. const min = _box.min;
  41563. const max = _box.max;
  41564. /*
  41565. 5____4
  41566. 1/___0/|
  41567. | 6__|_7
  41568. 2/___3/
  41569. 0: max.x, max.y, max.z
  41570. 1: min.x, max.y, max.z
  41571. 2: min.x, min.y, max.z
  41572. 3: max.x, min.y, max.z
  41573. 4: max.x, max.y, min.z
  41574. 5: min.x, max.y, min.z
  41575. 6: min.x, min.y, min.z
  41576. 7: max.x, min.y, min.z
  41577. */
  41578. const position = this.geometry.attributes.position;
  41579. const array = position.array;
  41580. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41581. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41582. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41583. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41584. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41585. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41586. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41587. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41588. position.needsUpdate = true;
  41589. this.geometry.computeBoundingSphere();
  41590. }
  41591. /**
  41592. * Updates the wireframe box for the passed object.
  41593. *
  41594. * @param {Object3D} object - The 3D object to create the helper for.
  41595. * @return {BoxHelper} A reference to this instance.
  41596. */
  41597. setFromObject( object ) {
  41598. this.object = object;
  41599. this.update();
  41600. return this;
  41601. }
  41602. copy( source, recursive ) {
  41603. super.copy( source, recursive );
  41604. this.object = source.object;
  41605. return this;
  41606. }
  41607. /**
  41608. * Frees the GPU-related resources allocated by this instance. Call this
  41609. * method whenever this instance is no longer used in your app.
  41610. */
  41611. dispose() {
  41612. this.geometry.dispose();
  41613. this.material.dispose();
  41614. }
  41615. }
  41616. /**
  41617. * A helper object to visualize an instance of {@link Box3}.
  41618. *
  41619. * ```js
  41620. * const box = new THREE.Box3();
  41621. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41622. *
  41623. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41624. * scene.add( helper )
  41625. * ```
  41626. *
  41627. * @augments LineSegments
  41628. */
  41629. class Box3Helper extends LineSegments {
  41630. /**
  41631. * Constructs a new box3 helper.
  41632. *
  41633. * @param {Box3} box - The box to visualize.
  41634. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41635. */
  41636. constructor( box, color = 0xffff00 ) {
  41637. 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 ] );
  41638. 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 ];
  41639. const geometry = new BufferGeometry();
  41640. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41641. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41642. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41643. /**
  41644. * The box being visualized.
  41645. *
  41646. * @type {Box3}
  41647. */
  41648. this.box = box;
  41649. this.type = 'Box3Helper';
  41650. this.geometry.computeBoundingSphere();
  41651. }
  41652. updateMatrixWorld( force ) {
  41653. const box = this.box;
  41654. if ( box.isEmpty() ) return;
  41655. box.getCenter( this.position );
  41656. box.getSize( this.scale );
  41657. this.scale.multiplyScalar( 0.5 );
  41658. super.updateMatrixWorld( force );
  41659. }
  41660. /**
  41661. * Frees the GPU-related resources allocated by this instance. Call this
  41662. * method whenever this instance is no longer used in your app.
  41663. */
  41664. dispose() {
  41665. this.geometry.dispose();
  41666. this.material.dispose();
  41667. }
  41668. }
  41669. /**
  41670. * A helper object to visualize an instance of {@link Plane}.
  41671. *
  41672. * ```js
  41673. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41674. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41675. * scene.add( helper );
  41676. * ```
  41677. *
  41678. * @augments Line
  41679. */
  41680. class PlaneHelper extends Line {
  41681. /**
  41682. * Constructs a new plane helper.
  41683. *
  41684. * @param {Plane} plane - The plane to be visualized.
  41685. * @param {number} [size=1] - The side length of plane helper.
  41686. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41687. */
  41688. constructor( plane, size = 1, hex = 0xffff00 ) {
  41689. const color = hex;
  41690. 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 ];
  41691. const geometry = new BufferGeometry();
  41692. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41693. geometry.computeBoundingSphere();
  41694. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41695. this.type = 'PlaneHelper';
  41696. /**
  41697. * The plane being visualized.
  41698. *
  41699. * @type {Plane}
  41700. */
  41701. this.plane = plane;
  41702. /**
  41703. * The side length of plane helper.
  41704. *
  41705. * @type {number}
  41706. * @default 1
  41707. */
  41708. this.size = size;
  41709. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41710. const geometry2 = new BufferGeometry();
  41711. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41712. geometry2.computeBoundingSphere();
  41713. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41714. }
  41715. updateMatrixWorld( force ) {
  41716. this.position.set( 0, 0, 0 );
  41717. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41718. this.lookAt( this.plane.normal );
  41719. this.translateZ( - this.plane.constant );
  41720. super.updateMatrixWorld( force );
  41721. }
  41722. /**
  41723. * Updates the helper to match the position and direction of the
  41724. * light being visualized.
  41725. */
  41726. dispose() {
  41727. this.geometry.dispose();
  41728. this.material.dispose();
  41729. this.children[ 0 ].geometry.dispose();
  41730. this.children[ 0 ].material.dispose();
  41731. }
  41732. }
  41733. const _axis = /*@__PURE__*/ new Vector3();
  41734. let _lineGeometry, _coneGeometry;
  41735. /**
  41736. * An 3D arrow object for visualizing directions.
  41737. *
  41738. * ```js
  41739. * const dir = new THREE.Vector3( 1, 2, 0 );
  41740. *
  41741. * //normalize the direction vector (convert to vector of length 1)
  41742. * dir.normalize();
  41743. *
  41744. * const origin = new THREE.Vector3( 0, 0, 0 );
  41745. * const length = 1;
  41746. * const hex = 0xffff00;
  41747. *
  41748. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41749. * scene.add( arrowHelper );
  41750. * ```
  41751. *
  41752. * @augments Object3D
  41753. */
  41754. class ArrowHelper extends Object3D {
  41755. /**
  41756. * Constructs a new arrow helper.
  41757. *
  41758. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41759. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41760. * @param {number} [length=1] - Length of the arrow in world units.
  41761. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41762. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41763. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41764. */
  41765. 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 ) {
  41766. super();
  41767. this.type = 'ArrowHelper';
  41768. if ( _lineGeometry === undefined ) {
  41769. _lineGeometry = new BufferGeometry();
  41770. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41771. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41772. _coneGeometry.translate( 0, -0.5, 0 );
  41773. }
  41774. this.position.copy( origin );
  41775. /**
  41776. * The line part of the arrow helper.
  41777. *
  41778. * @type {Line}
  41779. */
  41780. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41781. this.line.matrixAutoUpdate = false;
  41782. this.add( this.line );
  41783. /**
  41784. * The cone part of the arrow helper.
  41785. *
  41786. * @type {Mesh}
  41787. */
  41788. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41789. this.cone.matrixAutoUpdate = false;
  41790. this.add( this.cone );
  41791. this.setDirection( dir );
  41792. this.setLength( length, headLength, headWidth );
  41793. }
  41794. /**
  41795. * Sets the direction of the helper.
  41796. *
  41797. * @param {Vector3} dir - The normalized direction vector.
  41798. */
  41799. setDirection( dir ) {
  41800. // dir is assumed to be normalized
  41801. if ( dir.y > 0.99999 ) {
  41802. this.quaternion.set( 0, 0, 0, 1 );
  41803. } else if ( dir.y < -0.99999 ) {
  41804. this.quaternion.set( 1, 0, 0, 0 );
  41805. } else {
  41806. _axis.set( dir.z, 0, - dir.x ).normalize();
  41807. const radians = Math.acos( dir.y );
  41808. this.quaternion.setFromAxisAngle( _axis, radians );
  41809. }
  41810. }
  41811. /**
  41812. * Sets the length of the helper.
  41813. *
  41814. * @param {number} length - Length of the arrow in world units.
  41815. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41816. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41817. */
  41818. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41819. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41820. this.line.updateMatrix();
  41821. this.cone.scale.set( headWidth, headLength, headWidth );
  41822. this.cone.position.y = length;
  41823. this.cone.updateMatrix();
  41824. }
  41825. /**
  41826. * Sets the color of the helper.
  41827. *
  41828. * @param {number|Color|string} color - The color to set.
  41829. */
  41830. setColor( color ) {
  41831. this.line.material.color.set( color );
  41832. this.cone.material.color.set( color );
  41833. }
  41834. copy( source ) {
  41835. super.copy( source, false );
  41836. this.line.copy( source.line );
  41837. this.cone.copy( source.cone );
  41838. return this;
  41839. }
  41840. /**
  41841. * Frees the GPU-related resources allocated by this instance. Call this
  41842. * method whenever this instance is no longer used in your app.
  41843. */
  41844. dispose() {
  41845. this.line.geometry.dispose();
  41846. this.line.material.dispose();
  41847. this.cone.geometry.dispose();
  41848. this.cone.material.dispose();
  41849. }
  41850. }
  41851. /**
  41852. * An axis object to visualize the 3 axes in a simple way.
  41853. * The X axis is red. The Y axis is green. The Z axis is blue.
  41854. *
  41855. * ```js
  41856. * const axesHelper = new THREE.AxesHelper( 5 );
  41857. * scene.add( axesHelper );
  41858. * ```
  41859. *
  41860. * @augments LineSegments
  41861. */
  41862. class AxesHelper extends LineSegments {
  41863. /**
  41864. * Constructs a new axes helper.
  41865. *
  41866. * @param {number} [size=1] - Size of the lines representing the axes.
  41867. */
  41868. constructor( size = 1 ) {
  41869. const vertices = [
  41870. 0, 0, 0, size, 0, 0,
  41871. 0, 0, 0, 0, size, 0,
  41872. 0, 0, 0, 0, 0, size
  41873. ];
  41874. const colors = [
  41875. 1, 0, 0, 1, 0.6, 0,
  41876. 0, 1, 0, 0.6, 1, 0,
  41877. 0, 0, 1, 0, 0.6, 1
  41878. ];
  41879. const geometry = new BufferGeometry();
  41880. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41881. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41882. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41883. super( geometry, material );
  41884. this.type = 'AxesHelper';
  41885. }
  41886. /**
  41887. * Defines the colors of the axes helper.
  41888. *
  41889. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41890. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41891. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41892. * @return {AxesHelper} A reference to this axes helper.
  41893. */
  41894. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41895. const color = new Color();
  41896. const array = this.geometry.attributes.color.array;
  41897. color.set( xAxisColor );
  41898. color.toArray( array, 0 );
  41899. color.toArray( array, 3 );
  41900. color.set( yAxisColor );
  41901. color.toArray( array, 6 );
  41902. color.toArray( array, 9 );
  41903. color.set( zAxisColor );
  41904. color.toArray( array, 12 );
  41905. color.toArray( array, 15 );
  41906. this.geometry.attributes.color.needsUpdate = true;
  41907. return this;
  41908. }
  41909. /**
  41910. * Frees the GPU-related resources allocated by this instance. Call this
  41911. * method whenever this instance is no longer used in your app.
  41912. */
  41913. dispose() {
  41914. this.geometry.dispose();
  41915. this.material.dispose();
  41916. }
  41917. }
  41918. /**
  41919. * This class is used to convert a series of paths to an array of
  41920. * shapes. It is specifically used in context of fonts and SVG.
  41921. */
  41922. class ShapePath {
  41923. /**
  41924. * Constructs a new shape path.
  41925. */
  41926. constructor() {
  41927. this.type = 'ShapePath';
  41928. /**
  41929. * The color of the shape.
  41930. *
  41931. * @type {Color}
  41932. */
  41933. this.color = new Color();
  41934. /**
  41935. * The paths that have been generated for this shape.
  41936. *
  41937. * @type {Array<Path>}
  41938. * @default null
  41939. */
  41940. this.subPaths = [];
  41941. /**
  41942. * The current path that is being generated.
  41943. *
  41944. * @type {?Path}
  41945. * @default null
  41946. */
  41947. this.currentPath = null;
  41948. }
  41949. /**
  41950. * Creates a new path and moves it current point to the given one.
  41951. *
  41952. * @param {number} x - The x coordinate.
  41953. * @param {number} y - The y coordinate.
  41954. * @return {ShapePath} A reference to this shape path.
  41955. */
  41956. moveTo( x, y ) {
  41957. this.currentPath = new Path();
  41958. this.subPaths.push( this.currentPath );
  41959. this.currentPath.moveTo( x, y );
  41960. return this;
  41961. }
  41962. /**
  41963. * Adds an instance of {@link LineCurve} to the path by connecting
  41964. * the current point with the given one.
  41965. *
  41966. * @param {number} x - The x coordinate of the end point.
  41967. * @param {number} y - The y coordinate of the end point.
  41968. * @return {ShapePath} A reference to this shape path.
  41969. */
  41970. lineTo( x, y ) {
  41971. this.currentPath.lineTo( x, y );
  41972. return this;
  41973. }
  41974. /**
  41975. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41976. * the current point with the given one.
  41977. *
  41978. * @param {number} aCPx - The x coordinate of the control point.
  41979. * @param {number} aCPy - The y coordinate of the control point.
  41980. * @param {number} aX - The x coordinate of the end point.
  41981. * @param {number} aY - The y coordinate of the end point.
  41982. * @return {ShapePath} A reference to this shape path.
  41983. */
  41984. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41985. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41986. return this;
  41987. }
  41988. /**
  41989. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41990. * the current point with the given one.
  41991. *
  41992. * @param {number} aCP1x - The x coordinate of the first control point.
  41993. * @param {number} aCP1y - The y coordinate of the first control point.
  41994. * @param {number} aCP2x - The x coordinate of the second control point.
  41995. * @param {number} aCP2y - The y coordinate of the second control point.
  41996. * @param {number} aX - The x coordinate of the end point.
  41997. * @param {number} aY - The y coordinate of the end point.
  41998. * @return {ShapePath} A reference to this shape path.
  41999. */
  42000. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42001. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42002. return this;
  42003. }
  42004. /**
  42005. * Adds an instance of {@link SplineCurve} to the path by connecting
  42006. * the current point with the given list of points.
  42007. *
  42008. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42009. * @return {ShapePath} A reference to this shape path.
  42010. */
  42011. splineThru( pts ) {
  42012. this.currentPath.splineThru( pts );
  42013. return this;
  42014. }
  42015. /**
  42016. * Converts the paths into an array of shapes.
  42017. *
  42018. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42019. * If this flag is set to `true`, then those are flipped.
  42020. * @return {Array<Shape>} An array of shapes.
  42021. */
  42022. toShapes( isCCW ) {
  42023. function toShapesNoHoles( inSubpaths ) {
  42024. const shapes = [];
  42025. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42026. const tmpPath = inSubpaths[ i ];
  42027. const tmpShape = new Shape();
  42028. tmpShape.curves = tmpPath.curves;
  42029. shapes.push( tmpShape );
  42030. }
  42031. return shapes;
  42032. }
  42033. function isPointInsidePolygon( inPt, inPolygon ) {
  42034. const polyLen = inPolygon.length;
  42035. // inPt on polygon contour => immediate success or
  42036. // toggling of inside/outside at every single! intersection point of an edge
  42037. // with the horizontal line through inPt, left of inPt
  42038. // not counting lowerY endpoints of edges and whole edges on that line
  42039. let inside = false;
  42040. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42041. let edgeLowPt = inPolygon[ p ];
  42042. let edgeHighPt = inPolygon[ q ];
  42043. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42044. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42045. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42046. // not parallel
  42047. if ( edgeDy < 0 ) {
  42048. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42049. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42050. }
  42051. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42052. if ( inPt.y === edgeLowPt.y ) {
  42053. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42054. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42055. } else {
  42056. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42057. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42058. if ( perpEdge < 0 ) continue;
  42059. inside = ! inside; // true intersection left of inPt
  42060. }
  42061. } else {
  42062. // parallel or collinear
  42063. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42064. // edge lies on the same horizontal line as inPt
  42065. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42066. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42067. // continue;
  42068. }
  42069. }
  42070. return inside;
  42071. }
  42072. const isClockWise = ShapeUtils.isClockWise;
  42073. const subPaths = this.subPaths;
  42074. if ( subPaths.length === 0 ) return [];
  42075. let solid, tmpPath, tmpShape;
  42076. const shapes = [];
  42077. if ( subPaths.length === 1 ) {
  42078. tmpPath = subPaths[ 0 ];
  42079. tmpShape = new Shape();
  42080. tmpShape.curves = tmpPath.curves;
  42081. shapes.push( tmpShape );
  42082. return shapes;
  42083. }
  42084. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42085. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42086. // console.log("Holes first", holesFirst);
  42087. const betterShapeHoles = [];
  42088. const newShapes = [];
  42089. let newShapeHoles = [];
  42090. let mainIdx = 0;
  42091. let tmpPoints;
  42092. newShapes[ mainIdx ] = undefined;
  42093. newShapeHoles[ mainIdx ] = [];
  42094. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42095. tmpPath = subPaths[ i ];
  42096. tmpPoints = tmpPath.getPoints();
  42097. solid = isClockWise( tmpPoints );
  42098. solid = isCCW ? ! solid : solid;
  42099. if ( solid ) {
  42100. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42101. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42102. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42103. if ( holesFirst ) mainIdx ++;
  42104. newShapeHoles[ mainIdx ] = [];
  42105. //console.log('cw', i);
  42106. } else {
  42107. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42108. //console.log('ccw', i);
  42109. }
  42110. }
  42111. // only Holes? -> probably all Shapes with wrong orientation
  42112. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42113. if ( newShapes.length > 1 ) {
  42114. let ambiguous = false;
  42115. let toChange = 0;
  42116. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42117. betterShapeHoles[ sIdx ] = [];
  42118. }
  42119. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42120. const sho = newShapeHoles[ sIdx ];
  42121. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42122. const ho = sho[ hIdx ];
  42123. let hole_unassigned = true;
  42124. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42125. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42126. if ( sIdx !== s2Idx ) toChange ++;
  42127. if ( hole_unassigned ) {
  42128. hole_unassigned = false;
  42129. betterShapeHoles[ s2Idx ].push( ho );
  42130. } else {
  42131. ambiguous = true;
  42132. }
  42133. }
  42134. }
  42135. if ( hole_unassigned ) {
  42136. betterShapeHoles[ sIdx ].push( ho );
  42137. }
  42138. }
  42139. }
  42140. if ( toChange > 0 && ambiguous === false ) {
  42141. newShapeHoles = betterShapeHoles;
  42142. }
  42143. }
  42144. let tmpHoles;
  42145. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42146. tmpShape = newShapes[ i ].s;
  42147. shapes.push( tmpShape );
  42148. tmpHoles = newShapeHoles[ i ];
  42149. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42150. tmpShape.holes.push( tmpHoles[ j ].h );
  42151. }
  42152. }
  42153. //console.log("shape", shapes);
  42154. return shapes;
  42155. }
  42156. }
  42157. /**
  42158. * Abstract base class for controls.
  42159. *
  42160. * @abstract
  42161. * @augments EventDispatcher
  42162. */
  42163. class Controls extends EventDispatcher {
  42164. /**
  42165. * Constructs a new controls instance.
  42166. *
  42167. * @param {Object3D} object - The object that is managed by the controls.
  42168. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42169. */
  42170. constructor( object, domElement = null ) {
  42171. super();
  42172. /**
  42173. * The object that is managed by the controls.
  42174. *
  42175. * @type {Object3D}
  42176. */
  42177. this.object = object;
  42178. /**
  42179. * The HTML element used for event listeners.
  42180. *
  42181. * @type {?HTMLDOMElement}
  42182. * @default null
  42183. */
  42184. this.domElement = domElement;
  42185. /**
  42186. * Whether the controls responds to user input or not.
  42187. *
  42188. * @type {boolean}
  42189. * @default true
  42190. */
  42191. this.enabled = true;
  42192. /**
  42193. * The internal state of the controls.
  42194. *
  42195. * @type {number}
  42196. * @default -1
  42197. */
  42198. this.state = -1;
  42199. /**
  42200. * This object defines the keyboard input of the controls.
  42201. *
  42202. * @type {Object}
  42203. */
  42204. this.keys = {};
  42205. /**
  42206. * This object defines what type of actions are assigned to the available mouse buttons.
  42207. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42208. *
  42209. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42210. */
  42211. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42212. /**
  42213. * This object defines what type of actions are assigned to what kind of touch interaction.
  42214. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42215. *
  42216. * @type {{ONE: ?number, TWO: ?number}}
  42217. */
  42218. this.touches = { ONE: null, TWO: null };
  42219. }
  42220. /**
  42221. * Connects the controls to the DOM. This method has so called "side effects" since
  42222. * it adds the module's event listeners to the DOM.
  42223. *
  42224. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42225. */
  42226. connect( element ) {
  42227. if ( element === undefined ) {
  42228. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42229. return;
  42230. }
  42231. if ( this.domElement !== null ) this.disconnect();
  42232. this.domElement = element;
  42233. }
  42234. /**
  42235. * Disconnects the controls from the DOM.
  42236. */
  42237. disconnect() {}
  42238. /**
  42239. * Call this method if you no longer want use to the controls. It frees all internal
  42240. * resources and removes all event listeners.
  42241. */
  42242. dispose() {}
  42243. /**
  42244. * Controls should implement this method if they have to update their internal state
  42245. * per simulation step.
  42246. *
  42247. * @param {number} [delta] - The time delta in seconds.
  42248. */
  42249. update( /* delta */ ) {}
  42250. }
  42251. /**
  42252. * Scales the texture as large as possible within its surface without cropping
  42253. * or stretching the texture. The method preserves the original aspect ratio of
  42254. * the texture. Akin to CSS `object-fit: contain`
  42255. *
  42256. * @param {Texture} texture - The texture.
  42257. * @param {number} aspect - The texture's aspect ratio.
  42258. * @return {Texture} The updated texture.
  42259. */
  42260. function contain( texture, aspect ) {
  42261. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42262. if ( imageAspect > aspect ) {
  42263. texture.repeat.x = 1;
  42264. texture.repeat.y = imageAspect / aspect;
  42265. texture.offset.x = 0;
  42266. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42267. } else {
  42268. texture.repeat.x = aspect / imageAspect;
  42269. texture.repeat.y = 1;
  42270. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42271. texture.offset.y = 0;
  42272. }
  42273. return texture;
  42274. }
  42275. /**
  42276. * Scales the texture to the smallest possible size to fill the surface, leaving
  42277. * no empty space. The method preserves the original aspect ratio of the texture.
  42278. * Akin to CSS `object-fit: cover`.
  42279. *
  42280. * @param {Texture} texture - The texture.
  42281. * @param {number} aspect - The texture's aspect ratio.
  42282. * @return {Texture} The updated texture.
  42283. */
  42284. function cover( texture, aspect ) {
  42285. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42286. if ( imageAspect > aspect ) {
  42287. texture.repeat.x = aspect / imageAspect;
  42288. texture.repeat.y = 1;
  42289. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42290. texture.offset.y = 0;
  42291. } else {
  42292. texture.repeat.x = 1;
  42293. texture.repeat.y = imageAspect / aspect;
  42294. texture.offset.x = 0;
  42295. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42296. }
  42297. return texture;
  42298. }
  42299. /**
  42300. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42301. *
  42302. * @param {Texture} texture - The texture.
  42303. * @return {Texture} The updated texture.
  42304. */
  42305. function fill( texture ) {
  42306. texture.repeat.x = 1;
  42307. texture.repeat.y = 1;
  42308. texture.offset.x = 0;
  42309. texture.offset.y = 0;
  42310. return texture;
  42311. }
  42312. /**
  42313. * Determines how many bytes must be used to represent the texture.
  42314. *
  42315. * @param {number} width - The width of the texture.
  42316. * @param {number} height - The height of the texture.
  42317. * @param {number} format - The texture's format.
  42318. * @param {number} type - The texture's type.
  42319. * @return {number} The byte length.
  42320. */
  42321. function getByteLength( width, height, format, type ) {
  42322. const typeByteLength = getTextureTypeByteLength( type );
  42323. switch ( format ) {
  42324. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42325. case AlphaFormat:
  42326. return width * height;
  42327. case RedFormat:
  42328. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42329. case RedIntegerFormat:
  42330. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42331. case RGFormat:
  42332. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42333. case RGIntegerFormat:
  42334. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42335. case RGBFormat:
  42336. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42337. case RGBAFormat:
  42338. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42339. case RGBAIntegerFormat:
  42340. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42341. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42342. case RGB_S3TC_DXT1_Format:
  42343. case RGBA_S3TC_DXT1_Format:
  42344. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42345. case RGBA_S3TC_DXT3_Format:
  42346. case RGBA_S3TC_DXT5_Format:
  42347. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42348. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42349. case RGB_PVRTC_2BPPV1_Format:
  42350. case RGBA_PVRTC_2BPPV1_Format:
  42351. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42352. case RGB_PVRTC_4BPPV1_Format:
  42353. case RGBA_PVRTC_4BPPV1_Format:
  42354. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42355. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42356. case RGB_ETC1_Format:
  42357. case RGB_ETC2_Format:
  42358. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42359. case RGBA_ETC2_EAC_Format:
  42360. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42361. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42362. case RGBA_ASTC_4x4_Format:
  42363. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42364. case RGBA_ASTC_5x4_Format:
  42365. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42366. case RGBA_ASTC_5x5_Format:
  42367. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42368. case RGBA_ASTC_6x5_Format:
  42369. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42370. case RGBA_ASTC_6x6_Format:
  42371. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42372. case RGBA_ASTC_8x5_Format:
  42373. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42374. case RGBA_ASTC_8x6_Format:
  42375. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42376. case RGBA_ASTC_8x8_Format:
  42377. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42378. case RGBA_ASTC_10x5_Format:
  42379. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42380. case RGBA_ASTC_10x6_Format:
  42381. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42382. case RGBA_ASTC_10x8_Format:
  42383. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42384. case RGBA_ASTC_10x10_Format:
  42385. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42386. case RGBA_ASTC_12x10_Format:
  42387. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42388. case RGBA_ASTC_12x12_Format:
  42389. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42390. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42391. case RGBA_BPTC_Format:
  42392. case RGB_BPTC_SIGNED_Format:
  42393. case RGB_BPTC_UNSIGNED_Format:
  42394. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42395. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42396. case RED_RGTC1_Format:
  42397. case SIGNED_RED_RGTC1_Format:
  42398. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42399. case RED_GREEN_RGTC2_Format:
  42400. case SIGNED_RED_GREEN_RGTC2_Format:
  42401. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42402. }
  42403. throw new Error(
  42404. `Unable to determine texture byte length for ${format} format.`,
  42405. );
  42406. }
  42407. function getTextureTypeByteLength( type ) {
  42408. switch ( type ) {
  42409. case UnsignedByteType:
  42410. case ByteType:
  42411. return { byteLength: 1, components: 1 };
  42412. case UnsignedShortType:
  42413. case ShortType:
  42414. case HalfFloatType:
  42415. return { byteLength: 2, components: 1 };
  42416. case UnsignedShort4444Type:
  42417. case UnsignedShort5551Type:
  42418. return { byteLength: 2, components: 4 };
  42419. case UnsignedIntType:
  42420. case IntType:
  42421. case FloatType:
  42422. return { byteLength: 4, components: 1 };
  42423. case UnsignedInt5999Type:
  42424. return { byteLength: 4, components: 3 };
  42425. }
  42426. throw new Error( `Unknown texture type ${type}.` );
  42427. }
  42428. /**
  42429. * A class containing utility functions for textures.
  42430. *
  42431. * @hideconstructor
  42432. */
  42433. class TextureUtils {
  42434. /**
  42435. * Scales the texture as large as possible within its surface without cropping
  42436. * or stretching the texture. The method preserves the original aspect ratio of
  42437. * the texture. Akin to CSS `object-fit: contain`
  42438. *
  42439. * @param {Texture} texture - The texture.
  42440. * @param {number} aspect - The texture's aspect ratio.
  42441. * @return {Texture} The updated texture.
  42442. */
  42443. static contain( texture, aspect ) {
  42444. return contain( texture, aspect );
  42445. }
  42446. /**
  42447. * Scales the texture to the smallest possible size to fill the surface, leaving
  42448. * no empty space. The method preserves the original aspect ratio of the texture.
  42449. * Akin to CSS `object-fit: cover`.
  42450. *
  42451. * @param {Texture} texture - The texture.
  42452. * @param {number} aspect - The texture's aspect ratio.
  42453. * @return {Texture} The updated texture.
  42454. */
  42455. static cover( texture, aspect ) {
  42456. return cover( texture, aspect );
  42457. }
  42458. /**
  42459. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42460. *
  42461. * @param {Texture} texture - The texture.
  42462. * @return {Texture} The updated texture.
  42463. */
  42464. static fill( texture ) {
  42465. return fill( texture );
  42466. }
  42467. /**
  42468. * Determines how many bytes must be used to represent the texture.
  42469. *
  42470. * @param {number} width - The width of the texture.
  42471. * @param {number} height - The height of the texture.
  42472. * @param {number} format - The texture's format.
  42473. * @param {number} type - The texture's type.
  42474. * @return {number} The byte length.
  42475. */
  42476. static getByteLength( width, height, format, type ) {
  42477. return getByteLength( width, height, format, type );
  42478. }
  42479. }
  42480. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42481. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42482. revision: REVISION,
  42483. } } ) );
  42484. }
  42485. if ( typeof window !== 'undefined' ) {
  42486. if ( window.__THREE__ ) {
  42487. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42488. } else {
  42489. window.__THREE__ = REVISION;
  42490. }
  42491. }
  42492. function WebGLAnimation() {
  42493. let context = null;
  42494. let isAnimating = false;
  42495. let animationLoop = null;
  42496. let requestId = null;
  42497. function onAnimationFrame( time, frame ) {
  42498. animationLoop( time, frame );
  42499. requestId = context.requestAnimationFrame( onAnimationFrame );
  42500. }
  42501. return {
  42502. start: function () {
  42503. if ( isAnimating === true ) return;
  42504. if ( animationLoop === null ) return;
  42505. requestId = context.requestAnimationFrame( onAnimationFrame );
  42506. isAnimating = true;
  42507. },
  42508. stop: function () {
  42509. context.cancelAnimationFrame( requestId );
  42510. isAnimating = false;
  42511. },
  42512. setAnimationLoop: function ( callback ) {
  42513. animationLoop = callback;
  42514. },
  42515. setContext: function ( value ) {
  42516. context = value;
  42517. }
  42518. };
  42519. }
  42520. function WebGLAttributes( gl ) {
  42521. const buffers = new WeakMap();
  42522. function createBuffer( attribute, bufferType ) {
  42523. const array = attribute.array;
  42524. const usage = attribute.usage;
  42525. const size = array.byteLength;
  42526. const buffer = gl.createBuffer();
  42527. gl.bindBuffer( bufferType, buffer );
  42528. gl.bufferData( bufferType, array, usage );
  42529. attribute.onUploadCallback();
  42530. let type;
  42531. if ( array instanceof Float32Array ) {
  42532. type = gl.FLOAT;
  42533. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42534. type = gl.HALF_FLOAT;
  42535. } else if ( array instanceof Uint16Array ) {
  42536. if ( attribute.isFloat16BufferAttribute ) {
  42537. type = gl.HALF_FLOAT;
  42538. } else {
  42539. type = gl.UNSIGNED_SHORT;
  42540. }
  42541. } else if ( array instanceof Int16Array ) {
  42542. type = gl.SHORT;
  42543. } else if ( array instanceof Uint32Array ) {
  42544. type = gl.UNSIGNED_INT;
  42545. } else if ( array instanceof Int32Array ) {
  42546. type = gl.INT;
  42547. } else if ( array instanceof Int8Array ) {
  42548. type = gl.BYTE;
  42549. } else if ( array instanceof Uint8Array ) {
  42550. type = gl.UNSIGNED_BYTE;
  42551. } else if ( array instanceof Uint8ClampedArray ) {
  42552. type = gl.UNSIGNED_BYTE;
  42553. } else {
  42554. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42555. }
  42556. return {
  42557. buffer: buffer,
  42558. type: type,
  42559. bytesPerElement: array.BYTES_PER_ELEMENT,
  42560. version: attribute.version,
  42561. size: size
  42562. };
  42563. }
  42564. function updateBuffer( buffer, attribute, bufferType ) {
  42565. const array = attribute.array;
  42566. const updateRanges = attribute.updateRanges;
  42567. gl.bindBuffer( bufferType, buffer );
  42568. if ( updateRanges.length === 0 ) {
  42569. // Not using update ranges
  42570. gl.bufferSubData( bufferType, 0, array );
  42571. } else {
  42572. // Before applying update ranges, we merge any adjacent / overlapping
  42573. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42574. // to performance improvements for applications which make heavy use of
  42575. // update ranges. Likely due to GPU command overhead.
  42576. //
  42577. // Note that to reduce garbage collection between frames, we merge the
  42578. // update ranges in-place. This is safe because this method will clear the
  42579. // update ranges once updated.
  42580. updateRanges.sort( ( a, b ) => a.start - b.start );
  42581. // To merge the update ranges in-place, we work from left to right in the
  42582. // existing updateRanges array, merging ranges. This may result in a final
  42583. // array which is smaller than the original. This index tracks the last
  42584. // index representing a merged range, any data after this index can be
  42585. // trimmed once the merge algorithm is completed.
  42586. let mergeIndex = 0;
  42587. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42588. const previousRange = updateRanges[ mergeIndex ];
  42589. const range = updateRanges[ i ];
  42590. // We add one here to merge adjacent ranges. This is safe because ranges
  42591. // operate over positive integers.
  42592. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42593. previousRange.count = Math.max(
  42594. previousRange.count,
  42595. range.start + range.count - previousRange.start
  42596. );
  42597. } else {
  42598. ++ mergeIndex;
  42599. updateRanges[ mergeIndex ] = range;
  42600. }
  42601. }
  42602. // Trim the array to only contain the merged ranges.
  42603. updateRanges.length = mergeIndex + 1;
  42604. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42605. const range = updateRanges[ i ];
  42606. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42607. array, range.start, range.count );
  42608. }
  42609. attribute.clearUpdateRanges();
  42610. }
  42611. attribute.onUploadCallback();
  42612. }
  42613. //
  42614. function get( attribute ) {
  42615. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42616. return buffers.get( attribute );
  42617. }
  42618. function remove( attribute ) {
  42619. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42620. const data = buffers.get( attribute );
  42621. if ( data ) {
  42622. gl.deleteBuffer( data.buffer );
  42623. buffers.delete( attribute );
  42624. }
  42625. }
  42626. function update( attribute, bufferType ) {
  42627. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42628. if ( attribute.isGLBufferAttribute ) {
  42629. const cached = buffers.get( attribute );
  42630. if ( ! cached || cached.version < attribute.version ) {
  42631. buffers.set( attribute, {
  42632. buffer: attribute.buffer,
  42633. type: attribute.type,
  42634. bytesPerElement: attribute.elementSize,
  42635. version: attribute.version
  42636. } );
  42637. }
  42638. return;
  42639. }
  42640. const data = buffers.get( attribute );
  42641. if ( data === undefined ) {
  42642. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42643. } else if ( data.version < attribute.version ) {
  42644. if ( data.size !== attribute.array.byteLength ) {
  42645. 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.' );
  42646. }
  42647. updateBuffer( data.buffer, attribute, bufferType );
  42648. data.version = attribute.version;
  42649. }
  42650. }
  42651. return {
  42652. get: get,
  42653. remove: remove,
  42654. update: update
  42655. };
  42656. }
  42657. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42658. 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";
  42659. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42660. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42661. 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";
  42662. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42663. 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";
  42664. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42665. 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";
  42666. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42667. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42668. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42669. 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";
  42670. 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";
  42671. 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";
  42672. 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";
  42673. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42674. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42675. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42676. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42677. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42678. 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";
  42679. 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";
  42680. 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";
  42681. 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";
  42682. 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";
  42683. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42684. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42685. 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";
  42686. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42687. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42688. 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}";
  42689. 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";
  42690. 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";
  42691. 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";
  42692. 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";
  42693. 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";
  42694. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42695. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42696. 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";
  42697. 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";
  42698. 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}";
  42699. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42700. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42701. 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";
  42702. 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";
  42703. 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";
  42704. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42705. 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";
  42706. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42707. 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";
  42708. 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";
  42709. 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}";
  42710. 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";
  42711. 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";
  42712. 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";
  42713. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  42714. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42715. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42716. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42717. 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";
  42718. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42719. 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";
  42720. 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";
  42721. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42722. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42723. 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";
  42724. 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";
  42725. 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";
  42726. 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";
  42727. 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";
  42728. 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;";
  42729. 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";
  42730. 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";
  42731. 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";
  42732. 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";
  42733. 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";
  42734. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  42735. 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";
  42736. 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";
  42737. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  42738. 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 );";
  42739. 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}";
  42740. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  42741. 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;";
  42742. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  42743. 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";
  42744. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  42745. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  42746. 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\tfloat depth = unpackRGBAToDepth( texture2D( depths, uv ) );\n\t\t#ifdef USE_REVERSEDEPTHBUF\n\t\t\treturn step( depth, compare );\n\t\t#else\n\t\t\treturn step( compare, depth );\n\t\t#endif\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\t#ifdef USE_REVERSEDEPTHBUF\n\t\t\tfloat hard_shadow = step( distribution.x, compare );\n\t\t#else\n\t\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\t#endif\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";
  42747. 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";
  42748. 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";
  42749. 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}";
  42750. 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";
  42751. 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";
  42752. 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";
  42753. 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";
  42754. 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";
  42755. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  42756. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  42757. 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; }";
  42758. 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";
  42759. 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";
  42760. 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";
  42761. 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";
  42762. 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";
  42763. 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";
  42764. 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}";
  42765. 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}";
  42766. 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}";
  42767. 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}";
  42768. 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}";
  42769. 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}";
  42770. 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}";
  42771. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSEDEPTHBUF\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  42772. 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}";
  42773. 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}";
  42774. 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}";
  42775. 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}";
  42776. 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}";
  42777. 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}";
  42778. 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}";
  42779. 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}";
  42780. 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}";
  42781. 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}";
  42782. 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}";
  42783. 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}";
  42784. 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}";
  42785. 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}";
  42786. 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}";
  42787. 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}";
  42788. 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}";
  42789. 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}";
  42790. 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}";
  42791. 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}";
  42792. 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}";
  42793. 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}";
  42794. 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}";
  42795. 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}";
  42796. 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}";
  42797. 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}";
  42798. const ShaderChunk = {
  42799. alphahash_fragment: alphahash_fragment,
  42800. alphahash_pars_fragment: alphahash_pars_fragment,
  42801. alphamap_fragment: alphamap_fragment,
  42802. alphamap_pars_fragment: alphamap_pars_fragment,
  42803. alphatest_fragment: alphatest_fragment,
  42804. alphatest_pars_fragment: alphatest_pars_fragment,
  42805. aomap_fragment: aomap_fragment,
  42806. aomap_pars_fragment: aomap_pars_fragment,
  42807. batching_pars_vertex: batching_pars_vertex,
  42808. batching_vertex: batching_vertex,
  42809. begin_vertex: begin_vertex,
  42810. beginnormal_vertex: beginnormal_vertex,
  42811. bsdfs: bsdfs,
  42812. iridescence_fragment: iridescence_fragment,
  42813. bumpmap_pars_fragment: bumpmap_pars_fragment,
  42814. clipping_planes_fragment: clipping_planes_fragment,
  42815. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  42816. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  42817. clipping_planes_vertex: clipping_planes_vertex,
  42818. color_fragment: color_fragment,
  42819. color_pars_fragment: color_pars_fragment,
  42820. color_pars_vertex: color_pars_vertex,
  42821. color_vertex: color_vertex,
  42822. common: common,
  42823. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  42824. defaultnormal_vertex: defaultnormal_vertex,
  42825. displacementmap_pars_vertex: displacementmap_pars_vertex,
  42826. displacementmap_vertex: displacementmap_vertex,
  42827. emissivemap_fragment: emissivemap_fragment,
  42828. emissivemap_pars_fragment: emissivemap_pars_fragment,
  42829. colorspace_fragment: colorspace_fragment,
  42830. colorspace_pars_fragment: colorspace_pars_fragment,
  42831. envmap_fragment: envmap_fragment,
  42832. envmap_common_pars_fragment: envmap_common_pars_fragment,
  42833. envmap_pars_fragment: envmap_pars_fragment,
  42834. envmap_pars_vertex: envmap_pars_vertex,
  42835. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  42836. envmap_vertex: envmap_vertex,
  42837. fog_vertex: fog_vertex,
  42838. fog_pars_vertex: fog_pars_vertex,
  42839. fog_fragment: fog_fragment,
  42840. fog_pars_fragment: fog_pars_fragment,
  42841. gradientmap_pars_fragment: gradientmap_pars_fragment,
  42842. lightmap_pars_fragment: lightmap_pars_fragment,
  42843. lights_lambert_fragment: lights_lambert_fragment,
  42844. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  42845. lights_pars_begin: lights_pars_begin,
  42846. lights_toon_fragment: lights_toon_fragment,
  42847. lights_toon_pars_fragment: lights_toon_pars_fragment,
  42848. lights_phong_fragment: lights_phong_fragment,
  42849. lights_phong_pars_fragment: lights_phong_pars_fragment,
  42850. lights_physical_fragment: lights_physical_fragment,
  42851. lights_physical_pars_fragment: lights_physical_pars_fragment,
  42852. lights_fragment_begin: lights_fragment_begin,
  42853. lights_fragment_maps: lights_fragment_maps,
  42854. lights_fragment_end: lights_fragment_end,
  42855. logdepthbuf_fragment: logdepthbuf_fragment,
  42856. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  42857. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  42858. logdepthbuf_vertex: logdepthbuf_vertex,
  42859. map_fragment: map_fragment,
  42860. map_pars_fragment: map_pars_fragment,
  42861. map_particle_fragment: map_particle_fragment,
  42862. map_particle_pars_fragment: map_particle_pars_fragment,
  42863. metalnessmap_fragment: metalnessmap_fragment,
  42864. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  42865. morphinstance_vertex: morphinstance_vertex,
  42866. morphcolor_vertex: morphcolor_vertex,
  42867. morphnormal_vertex: morphnormal_vertex,
  42868. morphtarget_pars_vertex: morphtarget_pars_vertex,
  42869. morphtarget_vertex: morphtarget_vertex,
  42870. normal_fragment_begin: normal_fragment_begin,
  42871. normal_fragment_maps: normal_fragment_maps,
  42872. normal_pars_fragment: normal_pars_fragment,
  42873. normal_pars_vertex: normal_pars_vertex,
  42874. normal_vertex: normal_vertex,
  42875. normalmap_pars_fragment: normalmap_pars_fragment,
  42876. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  42877. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  42878. clearcoat_pars_fragment: clearcoat_pars_fragment,
  42879. iridescence_pars_fragment: iridescence_pars_fragment,
  42880. opaque_fragment: opaque_fragment,
  42881. packing: packing,
  42882. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  42883. project_vertex: project_vertex,
  42884. dithering_fragment: dithering_fragment,
  42885. dithering_pars_fragment: dithering_pars_fragment,
  42886. roughnessmap_fragment: roughnessmap_fragment,
  42887. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  42888. shadowmap_pars_fragment: shadowmap_pars_fragment,
  42889. shadowmap_pars_vertex: shadowmap_pars_vertex,
  42890. shadowmap_vertex: shadowmap_vertex,
  42891. shadowmask_pars_fragment: shadowmask_pars_fragment,
  42892. skinbase_vertex: skinbase_vertex,
  42893. skinning_pars_vertex: skinning_pars_vertex,
  42894. skinning_vertex: skinning_vertex,
  42895. skinnormal_vertex: skinnormal_vertex,
  42896. specularmap_fragment: specularmap_fragment,
  42897. specularmap_pars_fragment: specularmap_pars_fragment,
  42898. tonemapping_fragment: tonemapping_fragment,
  42899. tonemapping_pars_fragment: tonemapping_pars_fragment,
  42900. transmission_fragment: transmission_fragment,
  42901. transmission_pars_fragment: transmission_pars_fragment,
  42902. uv_pars_fragment: uv_pars_fragment,
  42903. uv_pars_vertex: uv_pars_vertex,
  42904. uv_vertex: uv_vertex,
  42905. worldpos_vertex: worldpos_vertex,
  42906. background_vert: vertex$h,
  42907. background_frag: fragment$h,
  42908. backgroundCube_vert: vertex$g,
  42909. backgroundCube_frag: fragment$g,
  42910. cube_vert: vertex$f,
  42911. cube_frag: fragment$f,
  42912. depth_vert: vertex$e,
  42913. depth_frag: fragment$e,
  42914. distanceRGBA_vert: vertex$d,
  42915. distanceRGBA_frag: fragment$d,
  42916. equirect_vert: vertex$c,
  42917. equirect_frag: fragment$c,
  42918. linedashed_vert: vertex$b,
  42919. linedashed_frag: fragment$b,
  42920. meshbasic_vert: vertex$a,
  42921. meshbasic_frag: fragment$a,
  42922. meshlambert_vert: vertex$9,
  42923. meshlambert_frag: fragment$9,
  42924. meshmatcap_vert: vertex$8,
  42925. meshmatcap_frag: fragment$8,
  42926. meshnormal_vert: vertex$7,
  42927. meshnormal_frag: fragment$7,
  42928. meshphong_vert: vertex$6,
  42929. meshphong_frag: fragment$6,
  42930. meshphysical_vert: vertex$5,
  42931. meshphysical_frag: fragment$5,
  42932. meshtoon_vert: vertex$4,
  42933. meshtoon_frag: fragment$4,
  42934. points_vert: vertex$3,
  42935. points_frag: fragment$3,
  42936. shadow_vert: vertex$2,
  42937. shadow_frag: fragment$2,
  42938. sprite_vert: vertex$1,
  42939. sprite_frag: fragment$1
  42940. };
  42941. // Uniforms library for shared webgl shaders
  42942. const UniformsLib = {
  42943. common: {
  42944. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42945. opacity: { value: 1.0 },
  42946. map: { value: null },
  42947. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42948. alphaMap: { value: null },
  42949. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42950. alphaTest: { value: 0 }
  42951. },
  42952. specularmap: {
  42953. specularMap: { value: null },
  42954. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42955. },
  42956. envmap: {
  42957. envMap: { value: null },
  42958. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  42959. flipEnvMap: { value: -1 },
  42960. reflectivity: { value: 1.0 }, // basic, lambert, phong
  42961. ior: { value: 1.5 }, // physical
  42962. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  42963. },
  42964. aomap: {
  42965. aoMap: { value: null },
  42966. aoMapIntensity: { value: 1 },
  42967. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42968. },
  42969. lightmap: {
  42970. lightMap: { value: null },
  42971. lightMapIntensity: { value: 1 },
  42972. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42973. },
  42974. bumpmap: {
  42975. bumpMap: { value: null },
  42976. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42977. bumpScale: { value: 1 }
  42978. },
  42979. normalmap: {
  42980. normalMap: { value: null },
  42981. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42982. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  42983. },
  42984. displacementmap: {
  42985. displacementMap: { value: null },
  42986. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42987. displacementScale: { value: 1 },
  42988. displacementBias: { value: 0 }
  42989. },
  42990. emissivemap: {
  42991. emissiveMap: { value: null },
  42992. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42993. },
  42994. metalnessmap: {
  42995. metalnessMap: { value: null },
  42996. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42997. },
  42998. roughnessmap: {
  42999. roughnessMap: { value: null },
  43000. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43001. },
  43002. gradientmap: {
  43003. gradientMap: { value: null }
  43004. },
  43005. fog: {
  43006. fogDensity: { value: 0.00025 },
  43007. fogNear: { value: 1 },
  43008. fogFar: { value: 2000 },
  43009. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43010. },
  43011. lights: {
  43012. ambientLightColor: { value: [] },
  43013. lightProbe: { value: [] },
  43014. directionalLights: { value: [], properties: {
  43015. direction: {},
  43016. color: {}
  43017. } },
  43018. directionalLightShadows: { value: [], properties: {
  43019. shadowIntensity: 1,
  43020. shadowBias: {},
  43021. shadowNormalBias: {},
  43022. shadowRadius: {},
  43023. shadowMapSize: {}
  43024. } },
  43025. directionalShadowMap: { value: [] },
  43026. directionalShadowMatrix: { value: [] },
  43027. spotLights: { value: [], properties: {
  43028. color: {},
  43029. position: {},
  43030. direction: {},
  43031. distance: {},
  43032. coneCos: {},
  43033. penumbraCos: {},
  43034. decay: {}
  43035. } },
  43036. spotLightShadows: { value: [], properties: {
  43037. shadowIntensity: 1,
  43038. shadowBias: {},
  43039. shadowNormalBias: {},
  43040. shadowRadius: {},
  43041. shadowMapSize: {}
  43042. } },
  43043. spotLightMap: { value: [] },
  43044. spotShadowMap: { value: [] },
  43045. spotLightMatrix: { value: [] },
  43046. pointLights: { value: [], properties: {
  43047. color: {},
  43048. position: {},
  43049. decay: {},
  43050. distance: {}
  43051. } },
  43052. pointLightShadows: { value: [], properties: {
  43053. shadowIntensity: 1,
  43054. shadowBias: {},
  43055. shadowNormalBias: {},
  43056. shadowRadius: {},
  43057. shadowMapSize: {},
  43058. shadowCameraNear: {},
  43059. shadowCameraFar: {}
  43060. } },
  43061. pointShadowMap: { value: [] },
  43062. pointShadowMatrix: { value: [] },
  43063. hemisphereLights: { value: [], properties: {
  43064. direction: {},
  43065. skyColor: {},
  43066. groundColor: {}
  43067. } },
  43068. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43069. rectAreaLights: { value: [], properties: {
  43070. color: {},
  43071. position: {},
  43072. width: {},
  43073. height: {}
  43074. } },
  43075. ltc_1: { value: null },
  43076. ltc_2: { value: null }
  43077. },
  43078. points: {
  43079. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43080. opacity: { value: 1.0 },
  43081. size: { value: 1.0 },
  43082. scale: { value: 1.0 },
  43083. map: { value: null },
  43084. alphaMap: { value: null },
  43085. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43086. alphaTest: { value: 0 },
  43087. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43088. },
  43089. sprite: {
  43090. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43091. opacity: { value: 1.0 },
  43092. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43093. rotation: { value: 0.0 },
  43094. map: { value: null },
  43095. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43096. alphaMap: { value: null },
  43097. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43098. alphaTest: { value: 0 }
  43099. }
  43100. };
  43101. const ShaderLib = {
  43102. basic: {
  43103. uniforms: /*@__PURE__*/ mergeUniforms( [
  43104. UniformsLib.common,
  43105. UniformsLib.specularmap,
  43106. UniformsLib.envmap,
  43107. UniformsLib.aomap,
  43108. UniformsLib.lightmap,
  43109. UniformsLib.fog
  43110. ] ),
  43111. vertexShader: ShaderChunk.meshbasic_vert,
  43112. fragmentShader: ShaderChunk.meshbasic_frag
  43113. },
  43114. lambert: {
  43115. uniforms: /*@__PURE__*/ mergeUniforms( [
  43116. UniformsLib.common,
  43117. UniformsLib.specularmap,
  43118. UniformsLib.envmap,
  43119. UniformsLib.aomap,
  43120. UniformsLib.lightmap,
  43121. UniformsLib.emissivemap,
  43122. UniformsLib.bumpmap,
  43123. UniformsLib.normalmap,
  43124. UniformsLib.displacementmap,
  43125. UniformsLib.fog,
  43126. UniformsLib.lights,
  43127. {
  43128. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43129. }
  43130. ] ),
  43131. vertexShader: ShaderChunk.meshlambert_vert,
  43132. fragmentShader: ShaderChunk.meshlambert_frag
  43133. },
  43134. phong: {
  43135. uniforms: /*@__PURE__*/ mergeUniforms( [
  43136. UniformsLib.common,
  43137. UniformsLib.specularmap,
  43138. UniformsLib.envmap,
  43139. UniformsLib.aomap,
  43140. UniformsLib.lightmap,
  43141. UniformsLib.emissivemap,
  43142. UniformsLib.bumpmap,
  43143. UniformsLib.normalmap,
  43144. UniformsLib.displacementmap,
  43145. UniformsLib.fog,
  43146. UniformsLib.lights,
  43147. {
  43148. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43149. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43150. shininess: { value: 30 }
  43151. }
  43152. ] ),
  43153. vertexShader: ShaderChunk.meshphong_vert,
  43154. fragmentShader: ShaderChunk.meshphong_frag
  43155. },
  43156. standard: {
  43157. uniforms: /*@__PURE__*/ mergeUniforms( [
  43158. UniformsLib.common,
  43159. UniformsLib.envmap,
  43160. UniformsLib.aomap,
  43161. UniformsLib.lightmap,
  43162. UniformsLib.emissivemap,
  43163. UniformsLib.bumpmap,
  43164. UniformsLib.normalmap,
  43165. UniformsLib.displacementmap,
  43166. UniformsLib.roughnessmap,
  43167. UniformsLib.metalnessmap,
  43168. UniformsLib.fog,
  43169. UniformsLib.lights,
  43170. {
  43171. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43172. roughness: { value: 1.0 },
  43173. metalness: { value: 0.0 },
  43174. envMapIntensity: { value: 1 }
  43175. }
  43176. ] ),
  43177. vertexShader: ShaderChunk.meshphysical_vert,
  43178. fragmentShader: ShaderChunk.meshphysical_frag
  43179. },
  43180. toon: {
  43181. uniforms: /*@__PURE__*/ mergeUniforms( [
  43182. UniformsLib.common,
  43183. UniformsLib.aomap,
  43184. UniformsLib.lightmap,
  43185. UniformsLib.emissivemap,
  43186. UniformsLib.bumpmap,
  43187. UniformsLib.normalmap,
  43188. UniformsLib.displacementmap,
  43189. UniformsLib.gradientmap,
  43190. UniformsLib.fog,
  43191. UniformsLib.lights,
  43192. {
  43193. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43194. }
  43195. ] ),
  43196. vertexShader: ShaderChunk.meshtoon_vert,
  43197. fragmentShader: ShaderChunk.meshtoon_frag
  43198. },
  43199. matcap: {
  43200. uniforms: /*@__PURE__*/ mergeUniforms( [
  43201. UniformsLib.common,
  43202. UniformsLib.bumpmap,
  43203. UniformsLib.normalmap,
  43204. UniformsLib.displacementmap,
  43205. UniformsLib.fog,
  43206. {
  43207. matcap: { value: null }
  43208. }
  43209. ] ),
  43210. vertexShader: ShaderChunk.meshmatcap_vert,
  43211. fragmentShader: ShaderChunk.meshmatcap_frag
  43212. },
  43213. points: {
  43214. uniforms: /*@__PURE__*/ mergeUniforms( [
  43215. UniformsLib.points,
  43216. UniformsLib.fog
  43217. ] ),
  43218. vertexShader: ShaderChunk.points_vert,
  43219. fragmentShader: ShaderChunk.points_frag
  43220. },
  43221. dashed: {
  43222. uniforms: /*@__PURE__*/ mergeUniforms( [
  43223. UniformsLib.common,
  43224. UniformsLib.fog,
  43225. {
  43226. scale: { value: 1 },
  43227. dashSize: { value: 1 },
  43228. totalSize: { value: 2 }
  43229. }
  43230. ] ),
  43231. vertexShader: ShaderChunk.linedashed_vert,
  43232. fragmentShader: ShaderChunk.linedashed_frag
  43233. },
  43234. depth: {
  43235. uniforms: /*@__PURE__*/ mergeUniforms( [
  43236. UniformsLib.common,
  43237. UniformsLib.displacementmap
  43238. ] ),
  43239. vertexShader: ShaderChunk.depth_vert,
  43240. fragmentShader: ShaderChunk.depth_frag
  43241. },
  43242. normal: {
  43243. uniforms: /*@__PURE__*/ mergeUniforms( [
  43244. UniformsLib.common,
  43245. UniformsLib.bumpmap,
  43246. UniformsLib.normalmap,
  43247. UniformsLib.displacementmap,
  43248. {
  43249. opacity: { value: 1.0 }
  43250. }
  43251. ] ),
  43252. vertexShader: ShaderChunk.meshnormal_vert,
  43253. fragmentShader: ShaderChunk.meshnormal_frag
  43254. },
  43255. sprite: {
  43256. uniforms: /*@__PURE__*/ mergeUniforms( [
  43257. UniformsLib.sprite,
  43258. UniformsLib.fog
  43259. ] ),
  43260. vertexShader: ShaderChunk.sprite_vert,
  43261. fragmentShader: ShaderChunk.sprite_frag
  43262. },
  43263. background: {
  43264. uniforms: {
  43265. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43266. t2D: { value: null },
  43267. backgroundIntensity: { value: 1 }
  43268. },
  43269. vertexShader: ShaderChunk.background_vert,
  43270. fragmentShader: ShaderChunk.background_frag
  43271. },
  43272. backgroundCube: {
  43273. uniforms: {
  43274. envMap: { value: null },
  43275. flipEnvMap: { value: -1 },
  43276. backgroundBlurriness: { value: 0 },
  43277. backgroundIntensity: { value: 1 },
  43278. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43279. },
  43280. vertexShader: ShaderChunk.backgroundCube_vert,
  43281. fragmentShader: ShaderChunk.backgroundCube_frag
  43282. },
  43283. cube: {
  43284. uniforms: {
  43285. tCube: { value: null },
  43286. tFlip: { value: -1 },
  43287. opacity: { value: 1.0 }
  43288. },
  43289. vertexShader: ShaderChunk.cube_vert,
  43290. fragmentShader: ShaderChunk.cube_frag
  43291. },
  43292. equirect: {
  43293. uniforms: {
  43294. tEquirect: { value: null },
  43295. },
  43296. vertexShader: ShaderChunk.equirect_vert,
  43297. fragmentShader: ShaderChunk.equirect_frag
  43298. },
  43299. distanceRGBA: {
  43300. uniforms: /*@__PURE__*/ mergeUniforms( [
  43301. UniformsLib.common,
  43302. UniformsLib.displacementmap,
  43303. {
  43304. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43305. nearDistance: { value: 1 },
  43306. farDistance: { value: 1000 }
  43307. }
  43308. ] ),
  43309. vertexShader: ShaderChunk.distanceRGBA_vert,
  43310. fragmentShader: ShaderChunk.distanceRGBA_frag
  43311. },
  43312. shadow: {
  43313. uniforms: /*@__PURE__*/ mergeUniforms( [
  43314. UniformsLib.lights,
  43315. UniformsLib.fog,
  43316. {
  43317. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43318. opacity: { value: 1.0 }
  43319. },
  43320. ] ),
  43321. vertexShader: ShaderChunk.shadow_vert,
  43322. fragmentShader: ShaderChunk.shadow_frag
  43323. }
  43324. };
  43325. ShaderLib.physical = {
  43326. uniforms: /*@__PURE__*/ mergeUniforms( [
  43327. ShaderLib.standard.uniforms,
  43328. {
  43329. clearcoat: { value: 0 },
  43330. clearcoatMap: { value: null },
  43331. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43332. clearcoatNormalMap: { value: null },
  43333. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43334. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43335. clearcoatRoughness: { value: 0 },
  43336. clearcoatRoughnessMap: { value: null },
  43337. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43338. dispersion: { value: 0 },
  43339. iridescence: { value: 0 },
  43340. iridescenceMap: { value: null },
  43341. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43342. iridescenceIOR: { value: 1.3 },
  43343. iridescenceThicknessMinimum: { value: 100 },
  43344. iridescenceThicknessMaximum: { value: 400 },
  43345. iridescenceThicknessMap: { value: null },
  43346. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43347. sheen: { value: 0 },
  43348. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43349. sheenColorMap: { value: null },
  43350. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43351. sheenRoughness: { value: 1 },
  43352. sheenRoughnessMap: { value: null },
  43353. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43354. transmission: { value: 0 },
  43355. transmissionMap: { value: null },
  43356. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43357. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43358. transmissionSamplerMap: { value: null },
  43359. thickness: { value: 0 },
  43360. thicknessMap: { value: null },
  43361. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43362. attenuationDistance: { value: 0 },
  43363. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43364. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43365. specularColorMap: { value: null },
  43366. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43367. specularIntensity: { value: 1 },
  43368. specularIntensityMap: { value: null },
  43369. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43370. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43371. anisotropyMap: { value: null },
  43372. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43373. }
  43374. ] ),
  43375. vertexShader: ShaderChunk.meshphysical_vert,
  43376. fragmentShader: ShaderChunk.meshphysical_frag
  43377. };
  43378. const _rgb = { r: 0, b: 0, g: 0 };
  43379. const _e1$1 = /*@__PURE__*/ new Euler();
  43380. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43381. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43382. const clearColor = new Color( 0x000000 );
  43383. let clearAlpha = alpha === true ? 0 : 1;
  43384. let planeMesh;
  43385. let boxMesh;
  43386. let currentBackground = null;
  43387. let currentBackgroundVersion = 0;
  43388. let currentTonemapping = null;
  43389. function getBackground( scene ) {
  43390. let background = scene.isScene === true ? scene.background : null;
  43391. if ( background && background.isTexture ) {
  43392. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43393. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43394. }
  43395. return background;
  43396. }
  43397. function render( scene ) {
  43398. let forceClear = false;
  43399. const background = getBackground( scene );
  43400. if ( background === null ) {
  43401. setClear( clearColor, clearAlpha );
  43402. } else if ( background && background.isColor ) {
  43403. setClear( background, 1 );
  43404. forceClear = true;
  43405. }
  43406. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43407. if ( environmentBlendMode === 'additive' ) {
  43408. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43409. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43410. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43411. }
  43412. if ( renderer.autoClear || forceClear ) {
  43413. // buffers might not be writable which is required to ensure a correct clear
  43414. state.buffers.depth.setTest( true );
  43415. state.buffers.depth.setMask( true );
  43416. state.buffers.color.setMask( true );
  43417. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43418. }
  43419. }
  43420. function addToRenderList( renderList, scene ) {
  43421. const background = getBackground( scene );
  43422. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43423. if ( boxMesh === undefined ) {
  43424. boxMesh = new Mesh(
  43425. new BoxGeometry( 1, 1, 1 ),
  43426. new ShaderMaterial( {
  43427. name: 'BackgroundCubeMaterial',
  43428. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43429. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43430. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43431. side: BackSide,
  43432. depthTest: false,
  43433. depthWrite: false,
  43434. fog: false,
  43435. allowOverride: false
  43436. } )
  43437. );
  43438. boxMesh.geometry.deleteAttribute( 'normal' );
  43439. boxMesh.geometry.deleteAttribute( 'uv' );
  43440. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43441. this.matrixWorld.copyPosition( camera.matrixWorld );
  43442. };
  43443. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43444. Object.defineProperty( boxMesh.material, 'envMap', {
  43445. get: function () {
  43446. return this.uniforms.envMap.value;
  43447. }
  43448. } );
  43449. objects.update( boxMesh );
  43450. }
  43451. _e1$1.copy( scene.backgroundRotation );
  43452. // accommodate left-handed frame
  43453. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43454. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43455. // environment maps which are not cube render targets or PMREMs follow a different convention
  43456. _e1$1.y *= -1;
  43457. _e1$1.z *= -1;
  43458. }
  43459. boxMesh.material.uniforms.envMap.value = background;
  43460. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43461. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43462. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43463. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43464. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43465. if ( currentBackground !== background ||
  43466. currentBackgroundVersion !== background.version ||
  43467. currentTonemapping !== renderer.toneMapping ) {
  43468. boxMesh.material.needsUpdate = true;
  43469. currentBackground = background;
  43470. currentBackgroundVersion = background.version;
  43471. currentTonemapping = renderer.toneMapping;
  43472. }
  43473. boxMesh.layers.enableAll();
  43474. // push to the pre-sorted opaque render list
  43475. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43476. } else if ( background && background.isTexture ) {
  43477. if ( planeMesh === undefined ) {
  43478. planeMesh = new Mesh(
  43479. new PlaneGeometry( 2, 2 ),
  43480. new ShaderMaterial( {
  43481. name: 'BackgroundMaterial',
  43482. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43483. vertexShader: ShaderLib.background.vertexShader,
  43484. fragmentShader: ShaderLib.background.fragmentShader,
  43485. side: FrontSide,
  43486. depthTest: false,
  43487. depthWrite: false,
  43488. fog: false,
  43489. allowOverride: false
  43490. } )
  43491. );
  43492. planeMesh.geometry.deleteAttribute( 'normal' );
  43493. // add "map" material property so the renderer can evaluate it like for built-in materials
  43494. Object.defineProperty( planeMesh.material, 'map', {
  43495. get: function () {
  43496. return this.uniforms.t2D.value;
  43497. }
  43498. } );
  43499. objects.update( planeMesh );
  43500. }
  43501. planeMesh.material.uniforms.t2D.value = background;
  43502. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43503. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43504. if ( background.matrixAutoUpdate === true ) {
  43505. background.updateMatrix();
  43506. }
  43507. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43508. if ( currentBackground !== background ||
  43509. currentBackgroundVersion !== background.version ||
  43510. currentTonemapping !== renderer.toneMapping ) {
  43511. planeMesh.material.needsUpdate = true;
  43512. currentBackground = background;
  43513. currentBackgroundVersion = background.version;
  43514. currentTonemapping = renderer.toneMapping;
  43515. }
  43516. planeMesh.layers.enableAll();
  43517. // push to the pre-sorted opaque render list
  43518. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43519. }
  43520. }
  43521. function setClear( color, alpha ) {
  43522. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43523. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43524. }
  43525. function dispose() {
  43526. if ( boxMesh !== undefined ) {
  43527. boxMesh.geometry.dispose();
  43528. boxMesh.material.dispose();
  43529. boxMesh = undefined;
  43530. }
  43531. if ( planeMesh !== undefined ) {
  43532. planeMesh.geometry.dispose();
  43533. planeMesh.material.dispose();
  43534. planeMesh = undefined;
  43535. }
  43536. }
  43537. return {
  43538. getClearColor: function () {
  43539. return clearColor;
  43540. },
  43541. setClearColor: function ( color, alpha = 1 ) {
  43542. clearColor.set( color );
  43543. clearAlpha = alpha;
  43544. setClear( clearColor, clearAlpha );
  43545. },
  43546. getClearAlpha: function () {
  43547. return clearAlpha;
  43548. },
  43549. setClearAlpha: function ( alpha ) {
  43550. clearAlpha = alpha;
  43551. setClear( clearColor, clearAlpha );
  43552. },
  43553. render: render,
  43554. addToRenderList: addToRenderList,
  43555. dispose: dispose
  43556. };
  43557. }
  43558. function WebGLBindingStates( gl, attributes ) {
  43559. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43560. const bindingStates = {};
  43561. const defaultState = createBindingState( null );
  43562. let currentState = defaultState;
  43563. let forceUpdate = false;
  43564. function setup( object, material, program, geometry, index ) {
  43565. let updateBuffers = false;
  43566. const state = getBindingState( geometry, program, material );
  43567. if ( currentState !== state ) {
  43568. currentState = state;
  43569. bindVertexArrayObject( currentState.object );
  43570. }
  43571. updateBuffers = needsUpdate( object, geometry, program, index );
  43572. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43573. if ( index !== null ) {
  43574. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43575. }
  43576. if ( updateBuffers || forceUpdate ) {
  43577. forceUpdate = false;
  43578. setupVertexAttributes( object, material, program, geometry );
  43579. if ( index !== null ) {
  43580. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43581. }
  43582. }
  43583. }
  43584. function createVertexArrayObject() {
  43585. return gl.createVertexArray();
  43586. }
  43587. function bindVertexArrayObject( vao ) {
  43588. return gl.bindVertexArray( vao );
  43589. }
  43590. function deleteVertexArrayObject( vao ) {
  43591. return gl.deleteVertexArray( vao );
  43592. }
  43593. function getBindingState( geometry, program, material ) {
  43594. const wireframe = ( material.wireframe === true );
  43595. let programMap = bindingStates[ geometry.id ];
  43596. if ( programMap === undefined ) {
  43597. programMap = {};
  43598. bindingStates[ geometry.id ] = programMap;
  43599. }
  43600. let stateMap = programMap[ program.id ];
  43601. if ( stateMap === undefined ) {
  43602. stateMap = {};
  43603. programMap[ program.id ] = stateMap;
  43604. }
  43605. let state = stateMap[ wireframe ];
  43606. if ( state === undefined ) {
  43607. state = createBindingState( createVertexArrayObject() );
  43608. stateMap[ wireframe ] = state;
  43609. }
  43610. return state;
  43611. }
  43612. function createBindingState( vao ) {
  43613. const newAttributes = [];
  43614. const enabledAttributes = [];
  43615. const attributeDivisors = [];
  43616. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43617. newAttributes[ i ] = 0;
  43618. enabledAttributes[ i ] = 0;
  43619. attributeDivisors[ i ] = 0;
  43620. }
  43621. return {
  43622. // for backward compatibility on non-VAO support browser
  43623. geometry: null,
  43624. program: null,
  43625. wireframe: false,
  43626. newAttributes: newAttributes,
  43627. enabledAttributes: enabledAttributes,
  43628. attributeDivisors: attributeDivisors,
  43629. object: vao,
  43630. attributes: {},
  43631. index: null
  43632. };
  43633. }
  43634. function needsUpdate( object, geometry, program, index ) {
  43635. const cachedAttributes = currentState.attributes;
  43636. const geometryAttributes = geometry.attributes;
  43637. let attributesNum = 0;
  43638. const programAttributes = program.getAttributes();
  43639. for ( const name in programAttributes ) {
  43640. const programAttribute = programAttributes[ name ];
  43641. if ( programAttribute.location >= 0 ) {
  43642. const cachedAttribute = cachedAttributes[ name ];
  43643. let geometryAttribute = geometryAttributes[ name ];
  43644. if ( geometryAttribute === undefined ) {
  43645. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43646. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43647. }
  43648. if ( cachedAttribute === undefined ) return true;
  43649. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43650. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43651. attributesNum ++;
  43652. }
  43653. }
  43654. if ( currentState.attributesNum !== attributesNum ) return true;
  43655. if ( currentState.index !== index ) return true;
  43656. return false;
  43657. }
  43658. function saveCache( object, geometry, program, index ) {
  43659. const cache = {};
  43660. const attributes = geometry.attributes;
  43661. let attributesNum = 0;
  43662. const programAttributes = program.getAttributes();
  43663. for ( const name in programAttributes ) {
  43664. const programAttribute = programAttributes[ name ];
  43665. if ( programAttribute.location >= 0 ) {
  43666. let attribute = attributes[ name ];
  43667. if ( attribute === undefined ) {
  43668. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43669. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43670. }
  43671. const data = {};
  43672. data.attribute = attribute;
  43673. if ( attribute && attribute.data ) {
  43674. data.data = attribute.data;
  43675. }
  43676. cache[ name ] = data;
  43677. attributesNum ++;
  43678. }
  43679. }
  43680. currentState.attributes = cache;
  43681. currentState.attributesNum = attributesNum;
  43682. currentState.index = index;
  43683. }
  43684. function initAttributes() {
  43685. const newAttributes = currentState.newAttributes;
  43686. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43687. newAttributes[ i ] = 0;
  43688. }
  43689. }
  43690. function enableAttribute( attribute ) {
  43691. enableAttributeAndDivisor( attribute, 0 );
  43692. }
  43693. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43694. const newAttributes = currentState.newAttributes;
  43695. const enabledAttributes = currentState.enabledAttributes;
  43696. const attributeDivisors = currentState.attributeDivisors;
  43697. newAttributes[ attribute ] = 1;
  43698. if ( enabledAttributes[ attribute ] === 0 ) {
  43699. gl.enableVertexAttribArray( attribute );
  43700. enabledAttributes[ attribute ] = 1;
  43701. }
  43702. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43703. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43704. attributeDivisors[ attribute ] = meshPerAttribute;
  43705. }
  43706. }
  43707. function disableUnusedAttributes() {
  43708. const newAttributes = currentState.newAttributes;
  43709. const enabledAttributes = currentState.enabledAttributes;
  43710. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43711. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43712. gl.disableVertexAttribArray( i );
  43713. enabledAttributes[ i ] = 0;
  43714. }
  43715. }
  43716. }
  43717. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43718. if ( integer === true ) {
  43719. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43720. } else {
  43721. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43722. }
  43723. }
  43724. function setupVertexAttributes( object, material, program, geometry ) {
  43725. initAttributes();
  43726. const geometryAttributes = geometry.attributes;
  43727. const programAttributes = program.getAttributes();
  43728. const materialDefaultAttributeValues = material.defaultAttributeValues;
  43729. for ( const name in programAttributes ) {
  43730. const programAttribute = programAttributes[ name ];
  43731. if ( programAttribute.location >= 0 ) {
  43732. let geometryAttribute = geometryAttributes[ name ];
  43733. if ( geometryAttribute === undefined ) {
  43734. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43735. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43736. }
  43737. if ( geometryAttribute !== undefined ) {
  43738. const normalized = geometryAttribute.normalized;
  43739. const size = geometryAttribute.itemSize;
  43740. const attribute = attributes.get( geometryAttribute );
  43741. // TODO Attribute may not be available on context restore
  43742. if ( attribute === undefined ) continue;
  43743. const buffer = attribute.buffer;
  43744. const type = attribute.type;
  43745. const bytesPerElement = attribute.bytesPerElement;
  43746. // check for integer attributes
  43747. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  43748. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  43749. const data = geometryAttribute.data;
  43750. const stride = data.stride;
  43751. const offset = geometryAttribute.offset;
  43752. if ( data.isInstancedInterleavedBuffer ) {
  43753. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43754. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  43755. }
  43756. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43757. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  43758. }
  43759. } else {
  43760. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43761. enableAttribute( programAttribute.location + i );
  43762. }
  43763. }
  43764. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43765. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43766. vertexAttribPointer(
  43767. programAttribute.location + i,
  43768. size / programAttribute.locationSize,
  43769. type,
  43770. normalized,
  43771. stride * bytesPerElement,
  43772. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  43773. integer
  43774. );
  43775. }
  43776. } else {
  43777. if ( geometryAttribute.isInstancedBufferAttribute ) {
  43778. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43779. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  43780. }
  43781. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43782. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  43783. }
  43784. } else {
  43785. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43786. enableAttribute( programAttribute.location + i );
  43787. }
  43788. }
  43789. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43790. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43791. vertexAttribPointer(
  43792. programAttribute.location + i,
  43793. size / programAttribute.locationSize,
  43794. type,
  43795. normalized,
  43796. size * bytesPerElement,
  43797. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  43798. integer
  43799. );
  43800. }
  43801. }
  43802. } else if ( materialDefaultAttributeValues !== undefined ) {
  43803. const value = materialDefaultAttributeValues[ name ];
  43804. if ( value !== undefined ) {
  43805. switch ( value.length ) {
  43806. case 2:
  43807. gl.vertexAttrib2fv( programAttribute.location, value );
  43808. break;
  43809. case 3:
  43810. gl.vertexAttrib3fv( programAttribute.location, value );
  43811. break;
  43812. case 4:
  43813. gl.vertexAttrib4fv( programAttribute.location, value );
  43814. break;
  43815. default:
  43816. gl.vertexAttrib1fv( programAttribute.location, value );
  43817. }
  43818. }
  43819. }
  43820. }
  43821. }
  43822. disableUnusedAttributes();
  43823. }
  43824. function dispose() {
  43825. reset();
  43826. for ( const geometryId in bindingStates ) {
  43827. const programMap = bindingStates[ geometryId ];
  43828. for ( const programId in programMap ) {
  43829. const stateMap = programMap[ programId ];
  43830. for ( const wireframe in stateMap ) {
  43831. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43832. delete stateMap[ wireframe ];
  43833. }
  43834. delete programMap[ programId ];
  43835. }
  43836. delete bindingStates[ geometryId ];
  43837. }
  43838. }
  43839. function releaseStatesOfGeometry( geometry ) {
  43840. if ( bindingStates[ geometry.id ] === undefined ) return;
  43841. const programMap = bindingStates[ geometry.id ];
  43842. for ( const programId in programMap ) {
  43843. const stateMap = programMap[ programId ];
  43844. for ( const wireframe in stateMap ) {
  43845. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43846. delete stateMap[ wireframe ];
  43847. }
  43848. delete programMap[ programId ];
  43849. }
  43850. delete bindingStates[ geometry.id ];
  43851. }
  43852. function releaseStatesOfProgram( program ) {
  43853. for ( const geometryId in bindingStates ) {
  43854. const programMap = bindingStates[ geometryId ];
  43855. if ( programMap[ program.id ] === undefined ) continue;
  43856. const stateMap = programMap[ program.id ];
  43857. for ( const wireframe in stateMap ) {
  43858. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43859. delete stateMap[ wireframe ];
  43860. }
  43861. delete programMap[ program.id ];
  43862. }
  43863. }
  43864. function reset() {
  43865. resetDefaultState();
  43866. forceUpdate = true;
  43867. if ( currentState === defaultState ) return;
  43868. currentState = defaultState;
  43869. bindVertexArrayObject( currentState.object );
  43870. }
  43871. // for backward-compatibility
  43872. function resetDefaultState() {
  43873. defaultState.geometry = null;
  43874. defaultState.program = null;
  43875. defaultState.wireframe = false;
  43876. }
  43877. return {
  43878. setup: setup,
  43879. reset: reset,
  43880. resetDefaultState: resetDefaultState,
  43881. dispose: dispose,
  43882. releaseStatesOfGeometry: releaseStatesOfGeometry,
  43883. releaseStatesOfProgram: releaseStatesOfProgram,
  43884. initAttributes: initAttributes,
  43885. enableAttribute: enableAttribute,
  43886. disableUnusedAttributes: disableUnusedAttributes
  43887. };
  43888. }
  43889. function WebGLBufferRenderer( gl, extensions, info ) {
  43890. let mode;
  43891. function setMode( value ) {
  43892. mode = value;
  43893. }
  43894. function render( start, count ) {
  43895. gl.drawArrays( mode, start, count );
  43896. info.update( count, mode, 1 );
  43897. }
  43898. function renderInstances( start, count, primcount ) {
  43899. if ( primcount === 0 ) return;
  43900. gl.drawArraysInstanced( mode, start, count, primcount );
  43901. info.update( count, mode, primcount );
  43902. }
  43903. function renderMultiDraw( starts, counts, drawCount ) {
  43904. if ( drawCount === 0 ) return;
  43905. const extension = extensions.get( 'WEBGL_multi_draw' );
  43906. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43907. let elementCount = 0;
  43908. for ( let i = 0; i < drawCount; i ++ ) {
  43909. elementCount += counts[ i ];
  43910. }
  43911. info.update( elementCount, mode, 1 );
  43912. }
  43913. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43914. if ( drawCount === 0 ) return;
  43915. const extension = extensions.get( 'WEBGL_multi_draw' );
  43916. if ( extension === null ) {
  43917. for ( let i = 0; i < starts.length; i ++ ) {
  43918. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43919. }
  43920. } else {
  43921. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43922. let elementCount = 0;
  43923. for ( let i = 0; i < drawCount; i ++ ) {
  43924. elementCount += counts[ i ] * primcount[ i ];
  43925. }
  43926. info.update( elementCount, mode, 1 );
  43927. }
  43928. }
  43929. //
  43930. this.setMode = setMode;
  43931. this.render = render;
  43932. this.renderInstances = renderInstances;
  43933. this.renderMultiDraw = renderMultiDraw;
  43934. this.renderMultiDrawInstances = renderMultiDrawInstances;
  43935. }
  43936. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  43937. let maxAnisotropy;
  43938. function getMaxAnisotropy() {
  43939. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  43940. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43941. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43942. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43943. } else {
  43944. maxAnisotropy = 0;
  43945. }
  43946. return maxAnisotropy;
  43947. }
  43948. function textureFormatReadable( textureFormat ) {
  43949. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  43950. return false;
  43951. }
  43952. return true;
  43953. }
  43954. function textureTypeReadable( textureType ) {
  43955. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  43956. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  43957. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  43958. return false;
  43959. }
  43960. return true;
  43961. }
  43962. function getMaxPrecision( precision ) {
  43963. if ( precision === 'highp' ) {
  43964. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  43965. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  43966. return 'highp';
  43967. }
  43968. precision = 'mediump';
  43969. }
  43970. if ( precision === 'mediump' ) {
  43971. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  43972. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  43973. return 'mediump';
  43974. }
  43975. }
  43976. return 'lowp';
  43977. }
  43978. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  43979. const maxPrecision = getMaxPrecision( precision );
  43980. if ( maxPrecision !== precision ) {
  43981. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  43982. precision = maxPrecision;
  43983. }
  43984. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  43985. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  43986. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  43987. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  43988. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  43989. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  43990. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43991. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  43992. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  43993. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  43994. const vertexTextures = maxVertexTextures > 0;
  43995. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  43996. return {
  43997. isWebGL2: true, // keeping this for backwards compatibility
  43998. getMaxAnisotropy: getMaxAnisotropy,
  43999. getMaxPrecision: getMaxPrecision,
  44000. textureFormatReadable: textureFormatReadable,
  44001. textureTypeReadable: textureTypeReadable,
  44002. precision: precision,
  44003. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44004. reversedDepthBuffer: reversedDepthBuffer,
  44005. maxTextures: maxTextures,
  44006. maxVertexTextures: maxVertexTextures,
  44007. maxTextureSize: maxTextureSize,
  44008. maxCubemapSize: maxCubemapSize,
  44009. maxAttributes: maxAttributes,
  44010. maxVertexUniforms: maxVertexUniforms,
  44011. maxVaryings: maxVaryings,
  44012. maxFragmentUniforms: maxFragmentUniforms,
  44013. vertexTextures: vertexTextures,
  44014. maxSamples: maxSamples
  44015. };
  44016. }
  44017. function WebGLClipping( properties ) {
  44018. const scope = this;
  44019. let globalState = null,
  44020. numGlobalPlanes = 0,
  44021. localClippingEnabled = false,
  44022. renderingShadows = false;
  44023. const plane = new Plane(),
  44024. viewNormalMatrix = new Matrix3(),
  44025. uniform = { value: null, needsUpdate: false };
  44026. this.uniform = uniform;
  44027. this.numPlanes = 0;
  44028. this.numIntersection = 0;
  44029. this.init = function ( planes, enableLocalClipping ) {
  44030. const enabled =
  44031. planes.length !== 0 ||
  44032. enableLocalClipping ||
  44033. // enable state of previous frame - the clipping code has to
  44034. // run another frame in order to reset the state:
  44035. numGlobalPlanes !== 0 ||
  44036. localClippingEnabled;
  44037. localClippingEnabled = enableLocalClipping;
  44038. numGlobalPlanes = planes.length;
  44039. return enabled;
  44040. };
  44041. this.beginShadows = function () {
  44042. renderingShadows = true;
  44043. projectPlanes( null );
  44044. };
  44045. this.endShadows = function () {
  44046. renderingShadows = false;
  44047. };
  44048. this.setGlobalState = function ( planes, camera ) {
  44049. globalState = projectPlanes( planes, camera, 0 );
  44050. };
  44051. this.setState = function ( material, camera, useCache ) {
  44052. const planes = material.clippingPlanes,
  44053. clipIntersection = material.clipIntersection,
  44054. clipShadows = material.clipShadows;
  44055. const materialProperties = properties.get( material );
  44056. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44057. // there's no local clipping
  44058. if ( renderingShadows ) {
  44059. // there's no global clipping
  44060. projectPlanes( null );
  44061. } else {
  44062. resetGlobalState();
  44063. }
  44064. } else {
  44065. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44066. lGlobal = nGlobal * 4;
  44067. let dstArray = materialProperties.clippingState || null;
  44068. uniform.value = dstArray; // ensure unique state
  44069. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44070. for ( let i = 0; i !== lGlobal; ++ i ) {
  44071. dstArray[ i ] = globalState[ i ];
  44072. }
  44073. materialProperties.clippingState = dstArray;
  44074. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44075. this.numPlanes += nGlobal;
  44076. }
  44077. };
  44078. function resetGlobalState() {
  44079. if ( uniform.value !== globalState ) {
  44080. uniform.value = globalState;
  44081. uniform.needsUpdate = numGlobalPlanes > 0;
  44082. }
  44083. scope.numPlanes = numGlobalPlanes;
  44084. scope.numIntersection = 0;
  44085. }
  44086. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44087. const nPlanes = planes !== null ? planes.length : 0;
  44088. let dstArray = null;
  44089. if ( nPlanes !== 0 ) {
  44090. dstArray = uniform.value;
  44091. if ( skipTransform !== true || dstArray === null ) {
  44092. const flatSize = dstOffset + nPlanes * 4,
  44093. viewMatrix = camera.matrixWorldInverse;
  44094. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44095. if ( dstArray === null || dstArray.length < flatSize ) {
  44096. dstArray = new Float32Array( flatSize );
  44097. }
  44098. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44099. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44100. plane.normal.toArray( dstArray, i4 );
  44101. dstArray[ i4 + 3 ] = plane.constant;
  44102. }
  44103. }
  44104. uniform.value = dstArray;
  44105. uniform.needsUpdate = true;
  44106. }
  44107. scope.numPlanes = nPlanes;
  44108. scope.numIntersection = 0;
  44109. return dstArray;
  44110. }
  44111. }
  44112. function WebGLCubeMaps( renderer ) {
  44113. let cubemaps = new WeakMap();
  44114. function mapTextureMapping( texture, mapping ) {
  44115. if ( mapping === EquirectangularReflectionMapping ) {
  44116. texture.mapping = CubeReflectionMapping;
  44117. } else if ( mapping === EquirectangularRefractionMapping ) {
  44118. texture.mapping = CubeRefractionMapping;
  44119. }
  44120. return texture;
  44121. }
  44122. function get( texture ) {
  44123. if ( texture && texture.isTexture ) {
  44124. const mapping = texture.mapping;
  44125. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44126. if ( cubemaps.has( texture ) ) {
  44127. const cubemap = cubemaps.get( texture ).texture;
  44128. return mapTextureMapping( cubemap, texture.mapping );
  44129. } else {
  44130. const image = texture.image;
  44131. if ( image && image.height > 0 ) {
  44132. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44133. renderTarget.fromEquirectangularTexture( renderer, texture );
  44134. cubemaps.set( texture, renderTarget );
  44135. texture.addEventListener( 'dispose', onTextureDispose );
  44136. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44137. } else {
  44138. // image not yet ready. try the conversion next frame
  44139. return null;
  44140. }
  44141. }
  44142. }
  44143. }
  44144. return texture;
  44145. }
  44146. function onTextureDispose( event ) {
  44147. const texture = event.target;
  44148. texture.removeEventListener( 'dispose', onTextureDispose );
  44149. const cubemap = cubemaps.get( texture );
  44150. if ( cubemap !== undefined ) {
  44151. cubemaps.delete( texture );
  44152. cubemap.dispose();
  44153. }
  44154. }
  44155. function dispose() {
  44156. cubemaps = new WeakMap();
  44157. }
  44158. return {
  44159. get: get,
  44160. dispose: dispose
  44161. };
  44162. }
  44163. const LOD_MIN = 4;
  44164. // The standard deviations (radians) associated with the extra mips. These are
  44165. // chosen to approximate a Trowbridge-Reitz distribution function times the
  44166. // geometric shadowing function. These sigma values squared must match the
  44167. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  44168. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44169. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44170. // samples and exit early, but not recompile the shader.
  44171. const MAX_SAMPLES = 20;
  44172. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44173. const _clearColor = /*@__PURE__*/ new Color();
  44174. let _oldTarget = null;
  44175. let _oldActiveCubeFace = 0;
  44176. let _oldActiveMipmapLevel = 0;
  44177. let _oldXrEnabled = false;
  44178. // Golden Ratio
  44179. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  44180. const INV_PHI = 1 / PHI;
  44181. // Vertices of a dodecahedron (except the opposites, which represent the
  44182. // same axis), used as axis directions evenly spread on a sphere.
  44183. const _axisDirections = [
  44184. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  44185. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  44186. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  44187. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  44188. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  44189. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  44190. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  44191. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  44192. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  44193. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  44194. const _origin = /*@__PURE__*/ new Vector3();
  44195. /**
  44196. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44197. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44198. * blur to be quickly accessed based on material roughness. It is packed into a
  44199. * special CubeUV format that allows us to perform custom interpolation so that
  44200. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44201. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44202. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44203. * higher roughness levels. In this way we maintain resolution to smoothly
  44204. * interpolate diffuse lighting while limiting sampling computation.
  44205. *
  44206. * Paper: Fast, Accurate Image-Based Lighting:
  44207. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  44208. */
  44209. class PMREMGenerator {
  44210. /**
  44211. * Constructs a new PMREM generator.
  44212. *
  44213. * @param {WebGLRenderer} renderer - The renderer.
  44214. */
  44215. constructor( renderer ) {
  44216. this._renderer = renderer;
  44217. this._pingPongRenderTarget = null;
  44218. this._lodMax = 0;
  44219. this._cubeSize = 0;
  44220. this._lodPlanes = [];
  44221. this._sizeLods = [];
  44222. this._sigmas = [];
  44223. this._blurMaterial = null;
  44224. this._cubemapMaterial = null;
  44225. this._equirectMaterial = null;
  44226. this._compileMaterial( this._blurMaterial );
  44227. }
  44228. /**
  44229. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44230. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44231. * in radians to be applied to the scene before PMREM generation. Optional near
  44232. * and far planes ensure the scene is rendered in its entirety.
  44233. *
  44234. * @param {Scene} scene - The scene to be captured.
  44235. * @param {number} [sigma=0] - The blur radius in radians.
  44236. * @param {number} [near=0.1] - The near plane distance.
  44237. * @param {number} [far=100] - The far plane distance.
  44238. * @param {Object} [options={}] - The configuration options.
  44239. * @param {number} [options.size=256] - The texture size of the PMREM.
  44240. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  44241. * @return {WebGLRenderTarget} The resulting PMREM.
  44242. */
  44243. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44244. const {
  44245. size = 256,
  44246. position = _origin,
  44247. } = options;
  44248. _oldTarget = this._renderer.getRenderTarget();
  44249. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44250. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44251. _oldXrEnabled = this._renderer.xr.enabled;
  44252. this._renderer.xr.enabled = false;
  44253. this._setSize( size );
  44254. const cubeUVRenderTarget = this._allocateTargets();
  44255. cubeUVRenderTarget.depthBuffer = true;
  44256. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44257. if ( sigma > 0 ) {
  44258. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44259. }
  44260. this._applyPMREM( cubeUVRenderTarget );
  44261. this._cleanup( cubeUVRenderTarget );
  44262. return cubeUVRenderTarget;
  44263. }
  44264. /**
  44265. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44266. * or HDR. The ideal input image size is 1k (1024 x 512),
  44267. * as this matches best with the 256 x 256 cubemap output.
  44268. *
  44269. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44270. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44271. * @return {WebGLRenderTarget} The resulting PMREM.
  44272. */
  44273. fromEquirectangular( equirectangular, renderTarget = null ) {
  44274. return this._fromTexture( equirectangular, renderTarget );
  44275. }
  44276. /**
  44277. * Generates a PMREM from an cubemap texture, which can be either LDR
  44278. * or HDR. The ideal input cube size is 256 x 256,
  44279. * as this matches best with the 256 x 256 cubemap output.
  44280. *
  44281. * @param {Texture} cubemap - The cubemap texture to be converted.
  44282. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44283. * @return {WebGLRenderTarget} The resulting PMREM.
  44284. */
  44285. fromCubemap( cubemap, renderTarget = null ) {
  44286. return this._fromTexture( cubemap, renderTarget );
  44287. }
  44288. /**
  44289. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44290. * your texture's network fetch for increased concurrency.
  44291. */
  44292. compileCubemapShader() {
  44293. if ( this._cubemapMaterial === null ) {
  44294. this._cubemapMaterial = _getCubemapMaterial();
  44295. this._compileMaterial( this._cubemapMaterial );
  44296. }
  44297. }
  44298. /**
  44299. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44300. * your texture's network fetch for increased concurrency.
  44301. */
  44302. compileEquirectangularShader() {
  44303. if ( this._equirectMaterial === null ) {
  44304. this._equirectMaterial = _getEquirectMaterial();
  44305. this._compileMaterial( this._equirectMaterial );
  44306. }
  44307. }
  44308. /**
  44309. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44310. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44311. * one of them will cause any others to also become unusable.
  44312. */
  44313. dispose() {
  44314. this._dispose();
  44315. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44316. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44317. }
  44318. // private interface
  44319. _setSize( cubeSize ) {
  44320. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44321. this._cubeSize = Math.pow( 2, this._lodMax );
  44322. }
  44323. _dispose() {
  44324. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44325. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44326. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  44327. this._lodPlanes[ i ].dispose();
  44328. }
  44329. }
  44330. _cleanup( outputTarget ) {
  44331. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44332. this._renderer.xr.enabled = _oldXrEnabled;
  44333. outputTarget.scissorTest = false;
  44334. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44335. }
  44336. _fromTexture( texture, renderTarget ) {
  44337. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44338. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44339. } else { // Equirectangular
  44340. this._setSize( texture.image.width / 4 );
  44341. }
  44342. _oldTarget = this._renderer.getRenderTarget();
  44343. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44344. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44345. _oldXrEnabled = this._renderer.xr.enabled;
  44346. this._renderer.xr.enabled = false;
  44347. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44348. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44349. this._applyPMREM( cubeUVRenderTarget );
  44350. this._cleanup( cubeUVRenderTarget );
  44351. return cubeUVRenderTarget;
  44352. }
  44353. _allocateTargets() {
  44354. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44355. const height = 4 * this._cubeSize;
  44356. const params = {
  44357. magFilter: LinearFilter,
  44358. minFilter: LinearFilter,
  44359. generateMipmaps: false,
  44360. type: HalfFloatType,
  44361. format: RGBAFormat,
  44362. colorSpace: LinearSRGBColorSpace,
  44363. depthBuffer: false
  44364. };
  44365. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44366. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44367. if ( this._pingPongRenderTarget !== null ) {
  44368. this._dispose();
  44369. }
  44370. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44371. const { _lodMax } = this;
  44372. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44373. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44374. }
  44375. return cubeUVRenderTarget;
  44376. }
  44377. _compileMaterial( material ) {
  44378. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  44379. this._renderer.compile( tmpMesh, _flatCamera );
  44380. }
  44381. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44382. const fov = 90;
  44383. const aspect = 1;
  44384. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44385. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44386. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44387. const renderer = this._renderer;
  44388. const originalAutoClear = renderer.autoClear;
  44389. const toneMapping = renderer.toneMapping;
  44390. renderer.getClearColor( _clearColor );
  44391. renderer.toneMapping = NoToneMapping;
  44392. renderer.autoClear = false;
  44393. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44394. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44395. if ( reversedDepthBuffer ) {
  44396. renderer.setRenderTarget( cubeUVRenderTarget );
  44397. renderer.clearDepth();
  44398. renderer.setRenderTarget( null );
  44399. }
  44400. const backgroundMaterial = new MeshBasicMaterial( {
  44401. name: 'PMREM.Background',
  44402. side: BackSide,
  44403. depthWrite: false,
  44404. depthTest: false,
  44405. } );
  44406. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  44407. let useSolidColor = false;
  44408. const background = scene.background;
  44409. if ( background ) {
  44410. if ( background.isColor ) {
  44411. backgroundMaterial.color.copy( background );
  44412. scene.background = null;
  44413. useSolidColor = true;
  44414. }
  44415. } else {
  44416. backgroundMaterial.color.copy( _clearColor );
  44417. useSolidColor = true;
  44418. }
  44419. for ( let i = 0; i < 6; i ++ ) {
  44420. const col = i % 3;
  44421. if ( col === 0 ) {
  44422. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44423. cubeCamera.position.set( position.x, position.y, position.z );
  44424. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44425. } else if ( col === 1 ) {
  44426. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44427. cubeCamera.position.set( position.x, position.y, position.z );
  44428. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44429. } else {
  44430. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44431. cubeCamera.position.set( position.x, position.y, position.z );
  44432. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44433. }
  44434. const size = this._cubeSize;
  44435. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44436. renderer.setRenderTarget( cubeUVRenderTarget );
  44437. if ( useSolidColor ) {
  44438. renderer.render( backgroundBox, cubeCamera );
  44439. }
  44440. renderer.render( scene, cubeCamera );
  44441. }
  44442. backgroundBox.geometry.dispose();
  44443. backgroundBox.material.dispose();
  44444. renderer.toneMapping = toneMapping;
  44445. renderer.autoClear = originalAutoClear;
  44446. scene.background = background;
  44447. }
  44448. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44449. const renderer = this._renderer;
  44450. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44451. if ( isCubeTexture ) {
  44452. if ( this._cubemapMaterial === null ) {
  44453. this._cubemapMaterial = _getCubemapMaterial();
  44454. }
  44455. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44456. } else {
  44457. if ( this._equirectMaterial === null ) {
  44458. this._equirectMaterial = _getEquirectMaterial();
  44459. }
  44460. }
  44461. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44462. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  44463. const uniforms = material.uniforms;
  44464. uniforms[ 'envMap' ].value = texture;
  44465. const size = this._cubeSize;
  44466. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44467. renderer.setRenderTarget( cubeUVRenderTarget );
  44468. renderer.render( mesh, _flatCamera );
  44469. }
  44470. _applyPMREM( cubeUVRenderTarget ) {
  44471. const renderer = this._renderer;
  44472. const autoClear = renderer.autoClear;
  44473. renderer.autoClear = false;
  44474. const n = this._lodPlanes.length;
  44475. for ( let i = 1; i < n; i ++ ) {
  44476. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  44477. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  44478. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  44479. }
  44480. renderer.autoClear = autoClear;
  44481. }
  44482. /**
  44483. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44484. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44485. * the blur latitudinally (around the poles), and then longitudinally (towards
  44486. * the poles) to approximate the orthogonally-separable blur. It is least
  44487. * accurate at the poles, but still does a decent job.
  44488. *
  44489. * @private
  44490. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44491. * @param {number} lodIn
  44492. * @param {number} lodOut
  44493. * @param {number} sigma
  44494. * @param {Vector3} [poleAxis]
  44495. */
  44496. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44497. const pingPongRenderTarget = this._pingPongRenderTarget;
  44498. this._halfBlur(
  44499. cubeUVRenderTarget,
  44500. pingPongRenderTarget,
  44501. lodIn,
  44502. lodOut,
  44503. sigma,
  44504. 'latitudinal',
  44505. poleAxis );
  44506. this._halfBlur(
  44507. pingPongRenderTarget,
  44508. cubeUVRenderTarget,
  44509. lodOut,
  44510. lodOut,
  44511. sigma,
  44512. 'longitudinal',
  44513. poleAxis );
  44514. }
  44515. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44516. const renderer = this._renderer;
  44517. const blurMaterial = this._blurMaterial;
  44518. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44519. console.error(
  44520. 'blur direction must be either latitudinal or longitudinal!' );
  44521. }
  44522. // Number of standard deviations at which to cut off the discrete approximation.
  44523. const STANDARD_DEVIATIONS = 3;
  44524. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  44525. const blurUniforms = blurMaterial.uniforms;
  44526. const pixels = this._sizeLods[ lodIn ] - 1;
  44527. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44528. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44529. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44530. if ( samples > MAX_SAMPLES ) {
  44531. console.warn( `sigmaRadians, ${
  44532. sigmaRadians}, is too large and will clip, as it requested ${
  44533. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44534. }
  44535. const weights = [];
  44536. let sum = 0;
  44537. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44538. const x = i / sigmaPixels;
  44539. const weight = Math.exp( - x * x / 2 );
  44540. weights.push( weight );
  44541. if ( i === 0 ) {
  44542. sum += weight;
  44543. } else if ( i < samples ) {
  44544. sum += 2 * weight;
  44545. }
  44546. }
  44547. for ( let i = 0; i < weights.length; i ++ ) {
  44548. weights[ i ] = weights[ i ] / sum;
  44549. }
  44550. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44551. blurUniforms[ 'samples' ].value = samples;
  44552. blurUniforms[ 'weights' ].value = weights;
  44553. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44554. if ( poleAxis ) {
  44555. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44556. }
  44557. const { _lodMax } = this;
  44558. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44559. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44560. const outputSize = this._sizeLods[ lodOut ];
  44561. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44562. const y = 4 * ( this._cubeSize - outputSize );
  44563. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44564. renderer.setRenderTarget( targetOut );
  44565. renderer.render( blurMesh, _flatCamera );
  44566. }
  44567. }
  44568. function _createPlanes( lodMax ) {
  44569. const lodPlanes = [];
  44570. const sizeLods = [];
  44571. const sigmas = [];
  44572. let lod = lodMax;
  44573. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44574. for ( let i = 0; i < totalLods; i ++ ) {
  44575. const sizeLod = Math.pow( 2, lod );
  44576. sizeLods.push( sizeLod );
  44577. let sigma = 1.0 / sizeLod;
  44578. if ( i > lodMax - LOD_MIN ) {
  44579. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44580. } else if ( i === 0 ) {
  44581. sigma = 0;
  44582. }
  44583. sigmas.push( sigma );
  44584. const texelSize = 1.0 / ( sizeLod - 2 );
  44585. const min = - texelSize;
  44586. const max = 1 + texelSize;
  44587. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44588. const cubeFaces = 6;
  44589. const vertices = 6;
  44590. const positionSize = 3;
  44591. const uvSize = 2;
  44592. const faceIndexSize = 1;
  44593. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44594. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44595. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44596. for ( let face = 0; face < cubeFaces; face ++ ) {
  44597. const x = ( face % 3 ) * 2 / 3 - 1;
  44598. const y = face > 2 ? 0 : -1;
  44599. const coordinates = [
  44600. x, y, 0,
  44601. x + 2 / 3, y, 0,
  44602. x + 2 / 3, y + 1, 0,
  44603. x, y, 0,
  44604. x + 2 / 3, y + 1, 0,
  44605. x, y + 1, 0
  44606. ];
  44607. position.set( coordinates, positionSize * vertices * face );
  44608. uv.set( uv1, uvSize * vertices * face );
  44609. const fill = [ face, face, face, face, face, face ];
  44610. faceIndex.set( fill, faceIndexSize * vertices * face );
  44611. }
  44612. const planes = new BufferGeometry();
  44613. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44614. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44615. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44616. lodPlanes.push( planes );
  44617. if ( lod > LOD_MIN ) {
  44618. lod --;
  44619. }
  44620. }
  44621. return { lodPlanes, sizeLods, sigmas };
  44622. }
  44623. function _createRenderTarget( width, height, params ) {
  44624. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44625. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44626. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44627. cubeUVRenderTarget.scissorTest = true;
  44628. return cubeUVRenderTarget;
  44629. }
  44630. function _setViewport( target, x, y, width, height ) {
  44631. target.viewport.set( x, y, width, height );
  44632. target.scissor.set( x, y, width, height );
  44633. }
  44634. function _getBlurShader( lodMax, width, height ) {
  44635. const weights = new Float32Array( MAX_SAMPLES );
  44636. const poleAxis = new Vector3( 0, 1, 0 );
  44637. const shaderMaterial = new ShaderMaterial( {
  44638. name: 'SphericalGaussianBlur',
  44639. defines: {
  44640. 'n': MAX_SAMPLES,
  44641. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44642. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44643. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44644. },
  44645. uniforms: {
  44646. 'envMap': { value: null },
  44647. 'samples': { value: 1 },
  44648. 'weights': { value: weights },
  44649. 'latitudinal': { value: false },
  44650. 'dTheta': { value: 0 },
  44651. 'mipInt': { value: 0 },
  44652. 'poleAxis': { value: poleAxis }
  44653. },
  44654. vertexShader: _getCommonVertexShader(),
  44655. fragmentShader: /* glsl */`
  44656. precision mediump float;
  44657. precision mediump int;
  44658. varying vec3 vOutputDirection;
  44659. uniform sampler2D envMap;
  44660. uniform int samples;
  44661. uniform float weights[ n ];
  44662. uniform bool latitudinal;
  44663. uniform float dTheta;
  44664. uniform float mipInt;
  44665. uniform vec3 poleAxis;
  44666. #define ENVMAP_TYPE_CUBE_UV
  44667. #include <cube_uv_reflection_fragment>
  44668. vec3 getSample( float theta, vec3 axis ) {
  44669. float cosTheta = cos( theta );
  44670. // Rodrigues' axis-angle rotation
  44671. vec3 sampleDirection = vOutputDirection * cosTheta
  44672. + cross( axis, vOutputDirection ) * sin( theta )
  44673. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  44674. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  44675. }
  44676. void main() {
  44677. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  44678. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  44679. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  44680. }
  44681. axis = normalize( axis );
  44682. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  44683. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  44684. for ( int i = 1; i < n; i++ ) {
  44685. if ( i >= samples ) {
  44686. break;
  44687. }
  44688. float theta = dTheta * float( i );
  44689. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  44690. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  44691. }
  44692. }
  44693. `,
  44694. blending: NoBlending,
  44695. depthTest: false,
  44696. depthWrite: false
  44697. } );
  44698. return shaderMaterial;
  44699. }
  44700. function _getEquirectMaterial() {
  44701. return new ShaderMaterial( {
  44702. name: 'EquirectangularToCubeUV',
  44703. uniforms: {
  44704. 'envMap': { value: null }
  44705. },
  44706. vertexShader: _getCommonVertexShader(),
  44707. fragmentShader: /* glsl */`
  44708. precision mediump float;
  44709. precision mediump int;
  44710. varying vec3 vOutputDirection;
  44711. uniform sampler2D envMap;
  44712. #include <common>
  44713. void main() {
  44714. vec3 outputDirection = normalize( vOutputDirection );
  44715. vec2 uv = equirectUv( outputDirection );
  44716. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  44717. }
  44718. `,
  44719. blending: NoBlending,
  44720. depthTest: false,
  44721. depthWrite: false
  44722. } );
  44723. }
  44724. function _getCubemapMaterial() {
  44725. return new ShaderMaterial( {
  44726. name: 'CubemapToCubeUV',
  44727. uniforms: {
  44728. 'envMap': { value: null },
  44729. 'flipEnvMap': { value: -1 }
  44730. },
  44731. vertexShader: _getCommonVertexShader(),
  44732. fragmentShader: /* glsl */`
  44733. precision mediump float;
  44734. precision mediump int;
  44735. uniform float flipEnvMap;
  44736. varying vec3 vOutputDirection;
  44737. uniform samplerCube envMap;
  44738. void main() {
  44739. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  44740. }
  44741. `,
  44742. blending: NoBlending,
  44743. depthTest: false,
  44744. depthWrite: false
  44745. } );
  44746. }
  44747. function _getCommonVertexShader() {
  44748. return /* glsl */`
  44749. precision mediump float;
  44750. precision mediump int;
  44751. attribute float faceIndex;
  44752. varying vec3 vOutputDirection;
  44753. // RH coordinate system; PMREM face-indexing convention
  44754. vec3 getDirection( vec2 uv, float face ) {
  44755. uv = 2.0 * uv - 1.0;
  44756. vec3 direction = vec3( uv, 1.0 );
  44757. if ( face == 0.0 ) {
  44758. direction = direction.zyx; // ( 1, v, u ) pos x
  44759. } else if ( face == 1.0 ) {
  44760. direction = direction.xzy;
  44761. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  44762. } else if ( face == 2.0 ) {
  44763. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  44764. } else if ( face == 3.0 ) {
  44765. direction = direction.zyx;
  44766. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  44767. } else if ( face == 4.0 ) {
  44768. direction = direction.xzy;
  44769. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  44770. } else if ( face == 5.0 ) {
  44771. direction.z *= -1.0; // ( u, v, -1 ) neg z
  44772. }
  44773. return direction;
  44774. }
  44775. void main() {
  44776. vOutputDirection = getDirection( uv, faceIndex );
  44777. gl_Position = vec4( position, 1.0 );
  44778. }
  44779. `;
  44780. }
  44781. function WebGLCubeUVMaps( renderer ) {
  44782. let cubeUVmaps = new WeakMap();
  44783. let pmremGenerator = null;
  44784. function get( texture ) {
  44785. if ( texture && texture.isTexture ) {
  44786. const mapping = texture.mapping;
  44787. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  44788. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44789. // equirect/cube map to cubeUV conversion
  44790. if ( isEquirectMap || isCubeMap ) {
  44791. let renderTarget = cubeUVmaps.get( texture );
  44792. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  44793. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  44794. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44795. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  44796. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44797. cubeUVmaps.set( texture, renderTarget );
  44798. return renderTarget.texture;
  44799. } else {
  44800. if ( renderTarget !== undefined ) {
  44801. return renderTarget.texture;
  44802. } else {
  44803. const image = texture.image;
  44804. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  44805. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44806. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  44807. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44808. cubeUVmaps.set( texture, renderTarget );
  44809. texture.addEventListener( 'dispose', onTextureDispose );
  44810. return renderTarget.texture;
  44811. } else {
  44812. // image not yet ready. try the conversion next frame
  44813. return null;
  44814. }
  44815. }
  44816. }
  44817. }
  44818. }
  44819. return texture;
  44820. }
  44821. function isCubeTextureComplete( image ) {
  44822. let count = 0;
  44823. const length = 6;
  44824. for ( let i = 0; i < length; i ++ ) {
  44825. if ( image[ i ] !== undefined ) count ++;
  44826. }
  44827. return count === length;
  44828. }
  44829. function onTextureDispose( event ) {
  44830. const texture = event.target;
  44831. texture.removeEventListener( 'dispose', onTextureDispose );
  44832. const cubemapUV = cubeUVmaps.get( texture );
  44833. if ( cubemapUV !== undefined ) {
  44834. cubeUVmaps.delete( texture );
  44835. cubemapUV.dispose();
  44836. }
  44837. }
  44838. function dispose() {
  44839. cubeUVmaps = new WeakMap();
  44840. if ( pmremGenerator !== null ) {
  44841. pmremGenerator.dispose();
  44842. pmremGenerator = null;
  44843. }
  44844. }
  44845. return {
  44846. get: get,
  44847. dispose: dispose
  44848. };
  44849. }
  44850. function WebGLExtensions( gl ) {
  44851. const extensions = {};
  44852. function getExtension( name ) {
  44853. if ( extensions[ name ] !== undefined ) {
  44854. return extensions[ name ];
  44855. }
  44856. let extension;
  44857. switch ( name ) {
  44858. case 'WEBGL_depth_texture':
  44859. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  44860. break;
  44861. case 'EXT_texture_filter_anisotropic':
  44862. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  44863. break;
  44864. case 'WEBGL_compressed_texture_s3tc':
  44865. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  44866. break;
  44867. case 'WEBGL_compressed_texture_pvrtc':
  44868. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  44869. break;
  44870. default:
  44871. extension = gl.getExtension( name );
  44872. }
  44873. extensions[ name ] = extension;
  44874. return extension;
  44875. }
  44876. return {
  44877. has: function ( name ) {
  44878. return getExtension( name ) !== null;
  44879. },
  44880. init: function () {
  44881. getExtension( 'EXT_color_buffer_float' );
  44882. getExtension( 'WEBGL_clip_cull_distance' );
  44883. getExtension( 'OES_texture_float_linear' );
  44884. getExtension( 'EXT_color_buffer_half_float' );
  44885. getExtension( 'WEBGL_multisampled_render_to_texture' );
  44886. getExtension( 'WEBGL_render_shared_exponent' );
  44887. },
  44888. get: function ( name ) {
  44889. const extension = getExtension( name );
  44890. if ( extension === null ) {
  44891. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  44892. }
  44893. return extension;
  44894. }
  44895. };
  44896. }
  44897. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  44898. const geometries = {};
  44899. const wireframeAttributes = new WeakMap();
  44900. function onGeometryDispose( event ) {
  44901. const geometry = event.target;
  44902. if ( geometry.index !== null ) {
  44903. attributes.remove( geometry.index );
  44904. }
  44905. for ( const name in geometry.attributes ) {
  44906. attributes.remove( geometry.attributes[ name ] );
  44907. }
  44908. geometry.removeEventListener( 'dispose', onGeometryDispose );
  44909. delete geometries[ geometry.id ];
  44910. const attribute = wireframeAttributes.get( geometry );
  44911. if ( attribute ) {
  44912. attributes.remove( attribute );
  44913. wireframeAttributes.delete( geometry );
  44914. }
  44915. bindingStates.releaseStatesOfGeometry( geometry );
  44916. if ( geometry.isInstancedBufferGeometry === true ) {
  44917. delete geometry._maxInstanceCount;
  44918. }
  44919. //
  44920. info.memory.geometries --;
  44921. }
  44922. function get( object, geometry ) {
  44923. if ( geometries[ geometry.id ] === true ) return geometry;
  44924. geometry.addEventListener( 'dispose', onGeometryDispose );
  44925. geometries[ geometry.id ] = true;
  44926. info.memory.geometries ++;
  44927. return geometry;
  44928. }
  44929. function update( geometry ) {
  44930. const geometryAttributes = geometry.attributes;
  44931. // Updating index buffer in VAO now. See WebGLBindingStates.
  44932. for ( const name in geometryAttributes ) {
  44933. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  44934. }
  44935. }
  44936. function updateWireframeAttribute( geometry ) {
  44937. const indices = [];
  44938. const geometryIndex = geometry.index;
  44939. const geometryPosition = geometry.attributes.position;
  44940. let version = 0;
  44941. if ( geometryIndex !== null ) {
  44942. const array = geometryIndex.array;
  44943. version = geometryIndex.version;
  44944. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  44945. const a = array[ i + 0 ];
  44946. const b = array[ i + 1 ];
  44947. const c = array[ i + 2 ];
  44948. indices.push( a, b, b, c, c, a );
  44949. }
  44950. } else if ( geometryPosition !== undefined ) {
  44951. const array = geometryPosition.array;
  44952. version = geometryPosition.version;
  44953. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  44954. const a = i + 0;
  44955. const b = i + 1;
  44956. const c = i + 2;
  44957. indices.push( a, b, b, c, c, a );
  44958. }
  44959. } else {
  44960. return;
  44961. }
  44962. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  44963. attribute.version = version;
  44964. // Updating index buffer in VAO now. See WebGLBindingStates
  44965. //
  44966. const previousAttribute = wireframeAttributes.get( geometry );
  44967. if ( previousAttribute ) attributes.remove( previousAttribute );
  44968. //
  44969. wireframeAttributes.set( geometry, attribute );
  44970. }
  44971. function getWireframeAttribute( geometry ) {
  44972. const currentAttribute = wireframeAttributes.get( geometry );
  44973. if ( currentAttribute ) {
  44974. const geometryIndex = geometry.index;
  44975. if ( geometryIndex !== null ) {
  44976. // if the attribute is obsolete, create a new one
  44977. if ( currentAttribute.version < geometryIndex.version ) {
  44978. updateWireframeAttribute( geometry );
  44979. }
  44980. }
  44981. } else {
  44982. updateWireframeAttribute( geometry );
  44983. }
  44984. return wireframeAttributes.get( geometry );
  44985. }
  44986. return {
  44987. get: get,
  44988. update: update,
  44989. getWireframeAttribute: getWireframeAttribute
  44990. };
  44991. }
  44992. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  44993. let mode;
  44994. function setMode( value ) {
  44995. mode = value;
  44996. }
  44997. let type, bytesPerElement;
  44998. function setIndex( value ) {
  44999. type = value.type;
  45000. bytesPerElement = value.bytesPerElement;
  45001. }
  45002. function render( start, count ) {
  45003. gl.drawElements( mode, count, type, start * bytesPerElement );
  45004. info.update( count, mode, 1 );
  45005. }
  45006. function renderInstances( start, count, primcount ) {
  45007. if ( primcount === 0 ) return;
  45008. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45009. info.update( count, mode, primcount );
  45010. }
  45011. function renderMultiDraw( starts, counts, drawCount ) {
  45012. if ( drawCount === 0 ) return;
  45013. const extension = extensions.get( 'WEBGL_multi_draw' );
  45014. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45015. let elementCount = 0;
  45016. for ( let i = 0; i < drawCount; i ++ ) {
  45017. elementCount += counts[ i ];
  45018. }
  45019. info.update( elementCount, mode, 1 );
  45020. }
  45021. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45022. if ( drawCount === 0 ) return;
  45023. const extension = extensions.get( 'WEBGL_multi_draw' );
  45024. if ( extension === null ) {
  45025. for ( let i = 0; i < starts.length; i ++ ) {
  45026. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45027. }
  45028. } else {
  45029. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45030. let elementCount = 0;
  45031. for ( let i = 0; i < drawCount; i ++ ) {
  45032. elementCount += counts[ i ] * primcount[ i ];
  45033. }
  45034. info.update( elementCount, mode, 1 );
  45035. }
  45036. }
  45037. //
  45038. this.setMode = setMode;
  45039. this.setIndex = setIndex;
  45040. this.render = render;
  45041. this.renderInstances = renderInstances;
  45042. this.renderMultiDraw = renderMultiDraw;
  45043. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45044. }
  45045. function WebGLInfo( gl ) {
  45046. const memory = {
  45047. geometries: 0,
  45048. textures: 0
  45049. };
  45050. const render = {
  45051. frame: 0,
  45052. calls: 0,
  45053. triangles: 0,
  45054. points: 0,
  45055. lines: 0
  45056. };
  45057. function update( count, mode, instanceCount ) {
  45058. render.calls ++;
  45059. switch ( mode ) {
  45060. case gl.TRIANGLES:
  45061. render.triangles += instanceCount * ( count / 3 );
  45062. break;
  45063. case gl.LINES:
  45064. render.lines += instanceCount * ( count / 2 );
  45065. break;
  45066. case gl.LINE_STRIP:
  45067. render.lines += instanceCount * ( count - 1 );
  45068. break;
  45069. case gl.LINE_LOOP:
  45070. render.lines += instanceCount * count;
  45071. break;
  45072. case gl.POINTS:
  45073. render.points += instanceCount * count;
  45074. break;
  45075. default:
  45076. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  45077. break;
  45078. }
  45079. }
  45080. function reset() {
  45081. render.calls = 0;
  45082. render.triangles = 0;
  45083. render.points = 0;
  45084. render.lines = 0;
  45085. }
  45086. return {
  45087. memory: memory,
  45088. render: render,
  45089. programs: null,
  45090. autoReset: true,
  45091. reset: reset,
  45092. update: update
  45093. };
  45094. }
  45095. function WebGLMorphtargets( gl, capabilities, textures ) {
  45096. const morphTextures = new WeakMap();
  45097. const morph = new Vector4();
  45098. function update( object, geometry, program ) {
  45099. const objectInfluences = object.morphTargetInfluences;
  45100. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45101. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45102. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45103. let entry = morphTextures.get( geometry );
  45104. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45105. if ( entry !== undefined ) entry.texture.dispose();
  45106. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45107. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45108. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45109. const morphTargets = geometry.morphAttributes.position || [];
  45110. const morphNormals = geometry.morphAttributes.normal || [];
  45111. const morphColors = geometry.morphAttributes.color || [];
  45112. let vertexDataCount = 0;
  45113. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45114. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45115. if ( hasMorphColors === true ) vertexDataCount = 3;
  45116. let width = geometry.attributes.position.count * vertexDataCount;
  45117. let height = 1;
  45118. if ( width > capabilities.maxTextureSize ) {
  45119. height = Math.ceil( width / capabilities.maxTextureSize );
  45120. width = capabilities.maxTextureSize;
  45121. }
  45122. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45123. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45124. texture.type = FloatType;
  45125. texture.needsUpdate = true;
  45126. // fill buffer
  45127. const vertexDataStride = vertexDataCount * 4;
  45128. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45129. const morphTarget = morphTargets[ i ];
  45130. const morphNormal = morphNormals[ i ];
  45131. const morphColor = morphColors[ i ];
  45132. const offset = width * height * 4 * i;
  45133. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45134. const stride = j * vertexDataStride;
  45135. if ( hasMorphPosition === true ) {
  45136. morph.fromBufferAttribute( morphTarget, j );
  45137. buffer[ offset + stride + 0 ] = morph.x;
  45138. buffer[ offset + stride + 1 ] = morph.y;
  45139. buffer[ offset + stride + 2 ] = morph.z;
  45140. buffer[ offset + stride + 3 ] = 0;
  45141. }
  45142. if ( hasMorphNormals === true ) {
  45143. morph.fromBufferAttribute( morphNormal, j );
  45144. buffer[ offset + stride + 4 ] = morph.x;
  45145. buffer[ offset + stride + 5 ] = morph.y;
  45146. buffer[ offset + stride + 6 ] = morph.z;
  45147. buffer[ offset + stride + 7 ] = 0;
  45148. }
  45149. if ( hasMorphColors === true ) {
  45150. morph.fromBufferAttribute( morphColor, j );
  45151. buffer[ offset + stride + 8 ] = morph.x;
  45152. buffer[ offset + stride + 9 ] = morph.y;
  45153. buffer[ offset + stride + 10 ] = morph.z;
  45154. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45155. }
  45156. }
  45157. }
  45158. entry = {
  45159. count: morphTargetsCount,
  45160. texture: texture,
  45161. size: new Vector2( width, height )
  45162. };
  45163. morphTextures.set( geometry, entry );
  45164. function disposeTexture() {
  45165. texture.dispose();
  45166. morphTextures.delete( geometry );
  45167. geometry.removeEventListener( 'dispose', disposeTexture );
  45168. }
  45169. geometry.addEventListener( 'dispose', disposeTexture );
  45170. }
  45171. //
  45172. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45173. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45174. } else {
  45175. let morphInfluencesSum = 0;
  45176. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45177. morphInfluencesSum += objectInfluences[ i ];
  45178. }
  45179. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45180. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45181. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45182. }
  45183. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45184. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45185. }
  45186. return {
  45187. update: update
  45188. };
  45189. }
  45190. function WebGLObjects( gl, geometries, attributes, info ) {
  45191. let updateMap = new WeakMap();
  45192. function update( object ) {
  45193. const frame = info.render.frame;
  45194. const geometry = object.geometry;
  45195. const buffergeometry = geometries.get( object, geometry );
  45196. // Update once per frame
  45197. if ( updateMap.get( buffergeometry ) !== frame ) {
  45198. geometries.update( buffergeometry );
  45199. updateMap.set( buffergeometry, frame );
  45200. }
  45201. if ( object.isInstancedMesh ) {
  45202. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45203. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45204. }
  45205. if ( updateMap.get( object ) !== frame ) {
  45206. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45207. if ( object.instanceColor !== null ) {
  45208. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45209. }
  45210. updateMap.set( object, frame );
  45211. }
  45212. }
  45213. if ( object.isSkinnedMesh ) {
  45214. const skeleton = object.skeleton;
  45215. if ( updateMap.get( skeleton ) !== frame ) {
  45216. skeleton.update();
  45217. updateMap.set( skeleton, frame );
  45218. }
  45219. }
  45220. return buffergeometry;
  45221. }
  45222. function dispose() {
  45223. updateMap = new WeakMap();
  45224. }
  45225. function onInstancedMeshDispose( event ) {
  45226. const instancedMesh = event.target;
  45227. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45228. attributes.remove( instancedMesh.instanceMatrix );
  45229. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45230. }
  45231. return {
  45232. update: update,
  45233. dispose: dispose
  45234. };
  45235. }
  45236. /**
  45237. * Uniforms of a program.
  45238. * Those form a tree structure with a special top-level container for the root,
  45239. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45240. *
  45241. *
  45242. * Properties of inner nodes including the top-level container:
  45243. *
  45244. * .seq - array of nested uniforms
  45245. * .map - nested uniforms by name
  45246. *
  45247. *
  45248. * Methods of all nodes except the top-level container:
  45249. *
  45250. * .setValue( gl, value, [textures] )
  45251. *
  45252. * uploads a uniform value(s)
  45253. * the 'textures' parameter is needed for sampler uniforms
  45254. *
  45255. *
  45256. * Static methods of the top-level container (textures factorizations):
  45257. *
  45258. * .upload( gl, seq, values, textures )
  45259. *
  45260. * sets uniforms in 'seq' to 'values[id].value'
  45261. *
  45262. * .seqWithValue( seq, values ) : filteredSeq
  45263. *
  45264. * filters 'seq' entries with corresponding entry in values
  45265. *
  45266. *
  45267. * Methods of the top-level container (textures factorizations):
  45268. *
  45269. * .setValue( gl, name, value, textures )
  45270. *
  45271. * sets uniform with name 'name' to 'value'
  45272. *
  45273. * .setOptional( gl, obj, prop )
  45274. *
  45275. * like .set for an optional property of the object
  45276. *
  45277. */
  45278. const emptyTexture = /*@__PURE__*/ new Texture();
  45279. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45280. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45281. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45282. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45283. // --- Utilities ---
  45284. // Array Caches (provide typed arrays for temporary by size)
  45285. const arrayCacheF32 = [];
  45286. const arrayCacheI32 = [];
  45287. // Float32Array caches used for uploading Matrix uniforms
  45288. const mat4array = new Float32Array( 16 );
  45289. const mat3array = new Float32Array( 9 );
  45290. const mat2array = new Float32Array( 4 );
  45291. // Flattening for arrays of vectors and matrices
  45292. function flatten( array, nBlocks, blockSize ) {
  45293. const firstElem = array[ 0 ];
  45294. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45295. // unoptimized: ! isNaN( firstElem )
  45296. // see http://jacksondunstan.com/articles/983
  45297. const n = nBlocks * blockSize;
  45298. let r = arrayCacheF32[ n ];
  45299. if ( r === undefined ) {
  45300. r = new Float32Array( n );
  45301. arrayCacheF32[ n ] = r;
  45302. }
  45303. if ( nBlocks !== 0 ) {
  45304. firstElem.toArray( r, 0 );
  45305. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45306. offset += blockSize;
  45307. array[ i ].toArray( r, offset );
  45308. }
  45309. }
  45310. return r;
  45311. }
  45312. function arraysEqual( a, b ) {
  45313. if ( a.length !== b.length ) return false;
  45314. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45315. if ( a[ i ] !== b[ i ] ) return false;
  45316. }
  45317. return true;
  45318. }
  45319. function copyArray( a, b ) {
  45320. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45321. a[ i ] = b[ i ];
  45322. }
  45323. }
  45324. // Texture unit allocation
  45325. function allocTexUnits( textures, n ) {
  45326. let r = arrayCacheI32[ n ];
  45327. if ( r === undefined ) {
  45328. r = new Int32Array( n );
  45329. arrayCacheI32[ n ] = r;
  45330. }
  45331. for ( let i = 0; i !== n; ++ i ) {
  45332. r[ i ] = textures.allocateTextureUnit();
  45333. }
  45334. return r;
  45335. }
  45336. // --- Setters ---
  45337. // Note: Defining these methods externally, because they come in a bunch
  45338. // and this way their names minify.
  45339. // Single scalar
  45340. function setValueV1f( gl, v ) {
  45341. const cache = this.cache;
  45342. if ( cache[ 0 ] === v ) return;
  45343. gl.uniform1f( this.addr, v );
  45344. cache[ 0 ] = v;
  45345. }
  45346. // Single float vector (from flat array or THREE.VectorN)
  45347. function setValueV2f( gl, v ) {
  45348. const cache = this.cache;
  45349. if ( v.x !== undefined ) {
  45350. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45351. gl.uniform2f( this.addr, v.x, v.y );
  45352. cache[ 0 ] = v.x;
  45353. cache[ 1 ] = v.y;
  45354. }
  45355. } else {
  45356. if ( arraysEqual( cache, v ) ) return;
  45357. gl.uniform2fv( this.addr, v );
  45358. copyArray( cache, v );
  45359. }
  45360. }
  45361. function setValueV3f( gl, v ) {
  45362. const cache = this.cache;
  45363. if ( v.x !== undefined ) {
  45364. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45365. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45366. cache[ 0 ] = v.x;
  45367. cache[ 1 ] = v.y;
  45368. cache[ 2 ] = v.z;
  45369. }
  45370. } else if ( v.r !== undefined ) {
  45371. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  45372. gl.uniform3f( this.addr, v.r, v.g, v.b );
  45373. cache[ 0 ] = v.r;
  45374. cache[ 1 ] = v.g;
  45375. cache[ 2 ] = v.b;
  45376. }
  45377. } else {
  45378. if ( arraysEqual( cache, v ) ) return;
  45379. gl.uniform3fv( this.addr, v );
  45380. copyArray( cache, v );
  45381. }
  45382. }
  45383. function setValueV4f( gl, v ) {
  45384. const cache = this.cache;
  45385. if ( v.x !== undefined ) {
  45386. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45387. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  45388. cache[ 0 ] = v.x;
  45389. cache[ 1 ] = v.y;
  45390. cache[ 2 ] = v.z;
  45391. cache[ 3 ] = v.w;
  45392. }
  45393. } else {
  45394. if ( arraysEqual( cache, v ) ) return;
  45395. gl.uniform4fv( this.addr, v );
  45396. copyArray( cache, v );
  45397. }
  45398. }
  45399. // Single matrix (from flat array or THREE.MatrixN)
  45400. function setValueM2( gl, v ) {
  45401. const cache = this.cache;
  45402. const elements = v.elements;
  45403. if ( elements === undefined ) {
  45404. if ( arraysEqual( cache, v ) ) return;
  45405. gl.uniformMatrix2fv( this.addr, false, v );
  45406. copyArray( cache, v );
  45407. } else {
  45408. if ( arraysEqual( cache, elements ) ) return;
  45409. mat2array.set( elements );
  45410. gl.uniformMatrix2fv( this.addr, false, mat2array );
  45411. copyArray( cache, elements );
  45412. }
  45413. }
  45414. function setValueM3( gl, v ) {
  45415. const cache = this.cache;
  45416. const elements = v.elements;
  45417. if ( elements === undefined ) {
  45418. if ( arraysEqual( cache, v ) ) return;
  45419. gl.uniformMatrix3fv( this.addr, false, v );
  45420. copyArray( cache, v );
  45421. } else {
  45422. if ( arraysEqual( cache, elements ) ) return;
  45423. mat3array.set( elements );
  45424. gl.uniformMatrix3fv( this.addr, false, mat3array );
  45425. copyArray( cache, elements );
  45426. }
  45427. }
  45428. function setValueM4( gl, v ) {
  45429. const cache = this.cache;
  45430. const elements = v.elements;
  45431. if ( elements === undefined ) {
  45432. if ( arraysEqual( cache, v ) ) return;
  45433. gl.uniformMatrix4fv( this.addr, false, v );
  45434. copyArray( cache, v );
  45435. } else {
  45436. if ( arraysEqual( cache, elements ) ) return;
  45437. mat4array.set( elements );
  45438. gl.uniformMatrix4fv( this.addr, false, mat4array );
  45439. copyArray( cache, elements );
  45440. }
  45441. }
  45442. // Single integer / boolean
  45443. function setValueV1i( gl, v ) {
  45444. const cache = this.cache;
  45445. if ( cache[ 0 ] === v ) return;
  45446. gl.uniform1i( this.addr, v );
  45447. cache[ 0 ] = v;
  45448. }
  45449. // Single integer / boolean vector (from flat array or THREE.VectorN)
  45450. function setValueV2i( gl, v ) {
  45451. const cache = this.cache;
  45452. if ( v.x !== undefined ) {
  45453. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45454. gl.uniform2i( this.addr, v.x, v.y );
  45455. cache[ 0 ] = v.x;
  45456. cache[ 1 ] = v.y;
  45457. }
  45458. } else {
  45459. if ( arraysEqual( cache, v ) ) return;
  45460. gl.uniform2iv( this.addr, v );
  45461. copyArray( cache, v );
  45462. }
  45463. }
  45464. function setValueV3i( gl, v ) {
  45465. const cache = this.cache;
  45466. if ( v.x !== undefined ) {
  45467. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45468. gl.uniform3i( this.addr, v.x, v.y, v.z );
  45469. cache[ 0 ] = v.x;
  45470. cache[ 1 ] = v.y;
  45471. cache[ 2 ] = v.z;
  45472. }
  45473. } else {
  45474. if ( arraysEqual( cache, v ) ) return;
  45475. gl.uniform3iv( this.addr, v );
  45476. copyArray( cache, v );
  45477. }
  45478. }
  45479. function setValueV4i( gl, v ) {
  45480. const cache = this.cache;
  45481. if ( v.x !== undefined ) {
  45482. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45483. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  45484. cache[ 0 ] = v.x;
  45485. cache[ 1 ] = v.y;
  45486. cache[ 2 ] = v.z;
  45487. cache[ 3 ] = v.w;
  45488. }
  45489. } else {
  45490. if ( arraysEqual( cache, v ) ) return;
  45491. gl.uniform4iv( this.addr, v );
  45492. copyArray( cache, v );
  45493. }
  45494. }
  45495. // Single unsigned integer
  45496. function setValueV1ui( gl, v ) {
  45497. const cache = this.cache;
  45498. if ( cache[ 0 ] === v ) return;
  45499. gl.uniform1ui( this.addr, v );
  45500. cache[ 0 ] = v;
  45501. }
  45502. // Single unsigned integer vector (from flat array or THREE.VectorN)
  45503. function setValueV2ui( gl, v ) {
  45504. const cache = this.cache;
  45505. if ( v.x !== undefined ) {
  45506. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45507. gl.uniform2ui( this.addr, v.x, v.y );
  45508. cache[ 0 ] = v.x;
  45509. cache[ 1 ] = v.y;
  45510. }
  45511. } else {
  45512. if ( arraysEqual( cache, v ) ) return;
  45513. gl.uniform2uiv( this.addr, v );
  45514. copyArray( cache, v );
  45515. }
  45516. }
  45517. function setValueV3ui( gl, v ) {
  45518. const cache = this.cache;
  45519. if ( v.x !== undefined ) {
  45520. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45521. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  45522. cache[ 0 ] = v.x;
  45523. cache[ 1 ] = v.y;
  45524. cache[ 2 ] = v.z;
  45525. }
  45526. } else {
  45527. if ( arraysEqual( cache, v ) ) return;
  45528. gl.uniform3uiv( this.addr, v );
  45529. copyArray( cache, v );
  45530. }
  45531. }
  45532. function setValueV4ui( gl, v ) {
  45533. const cache = this.cache;
  45534. if ( v.x !== undefined ) {
  45535. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45536. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  45537. cache[ 0 ] = v.x;
  45538. cache[ 1 ] = v.y;
  45539. cache[ 2 ] = v.z;
  45540. cache[ 3 ] = v.w;
  45541. }
  45542. } else {
  45543. if ( arraysEqual( cache, v ) ) return;
  45544. gl.uniform4uiv( this.addr, v );
  45545. copyArray( cache, v );
  45546. }
  45547. }
  45548. // Single texture (2D / Cube)
  45549. function setValueT1( gl, v, textures ) {
  45550. const cache = this.cache;
  45551. const unit = textures.allocateTextureUnit();
  45552. if ( cache[ 0 ] !== unit ) {
  45553. gl.uniform1i( this.addr, unit );
  45554. cache[ 0 ] = unit;
  45555. }
  45556. let emptyTexture2D;
  45557. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  45558. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  45559. emptyTexture2D = emptyShadowTexture;
  45560. } else {
  45561. emptyTexture2D = emptyTexture;
  45562. }
  45563. textures.setTexture2D( v || emptyTexture2D, unit );
  45564. }
  45565. function setValueT3D1( gl, v, textures ) {
  45566. const cache = this.cache;
  45567. const unit = textures.allocateTextureUnit();
  45568. if ( cache[ 0 ] !== unit ) {
  45569. gl.uniform1i( this.addr, unit );
  45570. cache[ 0 ] = unit;
  45571. }
  45572. textures.setTexture3D( v || empty3dTexture, unit );
  45573. }
  45574. function setValueT6( gl, v, textures ) {
  45575. const cache = this.cache;
  45576. const unit = textures.allocateTextureUnit();
  45577. if ( cache[ 0 ] !== unit ) {
  45578. gl.uniform1i( this.addr, unit );
  45579. cache[ 0 ] = unit;
  45580. }
  45581. textures.setTextureCube( v || emptyCubeTexture, unit );
  45582. }
  45583. function setValueT2DArray1( gl, v, textures ) {
  45584. const cache = this.cache;
  45585. const unit = textures.allocateTextureUnit();
  45586. if ( cache[ 0 ] !== unit ) {
  45587. gl.uniform1i( this.addr, unit );
  45588. cache[ 0 ] = unit;
  45589. }
  45590. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  45591. }
  45592. // Helper to pick the right setter for the singular case
  45593. function getSingularSetter( type ) {
  45594. switch ( type ) {
  45595. case 0x1406: return setValueV1f; // FLOAT
  45596. case 0x8b50: return setValueV2f; // _VEC2
  45597. case 0x8b51: return setValueV3f; // _VEC3
  45598. case 0x8b52: return setValueV4f; // _VEC4
  45599. case 0x8b5a: return setValueM2; // _MAT2
  45600. case 0x8b5b: return setValueM3; // _MAT3
  45601. case 0x8b5c: return setValueM4; // _MAT4
  45602. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  45603. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  45604. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  45605. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  45606. case 0x1405: return setValueV1ui; // UINT
  45607. case 0x8dc6: return setValueV2ui; // _VEC2
  45608. case 0x8dc7: return setValueV3ui; // _VEC3
  45609. case 0x8dc8: return setValueV4ui; // _VEC4
  45610. case 0x8b5e: // SAMPLER_2D
  45611. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45612. case 0x8dca: // INT_SAMPLER_2D
  45613. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45614. case 0x8b62: // SAMPLER_2D_SHADOW
  45615. return setValueT1;
  45616. case 0x8b5f: // SAMPLER_3D
  45617. case 0x8dcb: // INT_SAMPLER_3D
  45618. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45619. return setValueT3D1;
  45620. case 0x8b60: // SAMPLER_CUBE
  45621. case 0x8dcc: // INT_SAMPLER_CUBE
  45622. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45623. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45624. return setValueT6;
  45625. case 0x8dc1: // SAMPLER_2D_ARRAY
  45626. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45627. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45628. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45629. return setValueT2DArray1;
  45630. }
  45631. }
  45632. // Array of scalars
  45633. function setValueV1fArray( gl, v ) {
  45634. gl.uniform1fv( this.addr, v );
  45635. }
  45636. // Array of vectors (from flat array or array of THREE.VectorN)
  45637. function setValueV2fArray( gl, v ) {
  45638. const data = flatten( v, this.size, 2 );
  45639. gl.uniform2fv( this.addr, data );
  45640. }
  45641. function setValueV3fArray( gl, v ) {
  45642. const data = flatten( v, this.size, 3 );
  45643. gl.uniform3fv( this.addr, data );
  45644. }
  45645. function setValueV4fArray( gl, v ) {
  45646. const data = flatten( v, this.size, 4 );
  45647. gl.uniform4fv( this.addr, data );
  45648. }
  45649. // Array of matrices (from flat array or array of THREE.MatrixN)
  45650. function setValueM2Array( gl, v ) {
  45651. const data = flatten( v, this.size, 4 );
  45652. gl.uniformMatrix2fv( this.addr, false, data );
  45653. }
  45654. function setValueM3Array( gl, v ) {
  45655. const data = flatten( v, this.size, 9 );
  45656. gl.uniformMatrix3fv( this.addr, false, data );
  45657. }
  45658. function setValueM4Array( gl, v ) {
  45659. const data = flatten( v, this.size, 16 );
  45660. gl.uniformMatrix4fv( this.addr, false, data );
  45661. }
  45662. // Array of integer / boolean
  45663. function setValueV1iArray( gl, v ) {
  45664. gl.uniform1iv( this.addr, v );
  45665. }
  45666. // Array of integer / boolean vectors (from flat array)
  45667. function setValueV2iArray( gl, v ) {
  45668. gl.uniform2iv( this.addr, v );
  45669. }
  45670. function setValueV3iArray( gl, v ) {
  45671. gl.uniform3iv( this.addr, v );
  45672. }
  45673. function setValueV4iArray( gl, v ) {
  45674. gl.uniform4iv( this.addr, v );
  45675. }
  45676. // Array of unsigned integer
  45677. function setValueV1uiArray( gl, v ) {
  45678. gl.uniform1uiv( this.addr, v );
  45679. }
  45680. // Array of unsigned integer vectors (from flat array)
  45681. function setValueV2uiArray( gl, v ) {
  45682. gl.uniform2uiv( this.addr, v );
  45683. }
  45684. function setValueV3uiArray( gl, v ) {
  45685. gl.uniform3uiv( this.addr, v );
  45686. }
  45687. function setValueV4uiArray( gl, v ) {
  45688. gl.uniform4uiv( this.addr, v );
  45689. }
  45690. // Array of textures (2D / 3D / Cube / 2DArray)
  45691. function setValueT1Array( gl, v, textures ) {
  45692. const cache = this.cache;
  45693. const n = v.length;
  45694. const units = allocTexUnits( textures, n );
  45695. if ( ! arraysEqual( cache, units ) ) {
  45696. gl.uniform1iv( this.addr, units );
  45697. copyArray( cache, units );
  45698. }
  45699. for ( let i = 0; i !== n; ++ i ) {
  45700. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  45701. }
  45702. }
  45703. function setValueT3DArray( gl, v, textures ) {
  45704. const cache = this.cache;
  45705. const n = v.length;
  45706. const units = allocTexUnits( textures, n );
  45707. if ( ! arraysEqual( cache, units ) ) {
  45708. gl.uniform1iv( this.addr, units );
  45709. copyArray( cache, units );
  45710. }
  45711. for ( let i = 0; i !== n; ++ i ) {
  45712. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  45713. }
  45714. }
  45715. function setValueT6Array( gl, v, textures ) {
  45716. const cache = this.cache;
  45717. const n = v.length;
  45718. const units = allocTexUnits( textures, n );
  45719. if ( ! arraysEqual( cache, units ) ) {
  45720. gl.uniform1iv( this.addr, units );
  45721. copyArray( cache, units );
  45722. }
  45723. for ( let i = 0; i !== n; ++ i ) {
  45724. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  45725. }
  45726. }
  45727. function setValueT2DArrayArray( gl, v, textures ) {
  45728. const cache = this.cache;
  45729. const n = v.length;
  45730. const units = allocTexUnits( textures, n );
  45731. if ( ! arraysEqual( cache, units ) ) {
  45732. gl.uniform1iv( this.addr, units );
  45733. copyArray( cache, units );
  45734. }
  45735. for ( let i = 0; i !== n; ++ i ) {
  45736. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  45737. }
  45738. }
  45739. // Helper to pick the right setter for a pure (bottom-level) array
  45740. function getPureArraySetter( type ) {
  45741. switch ( type ) {
  45742. case 0x1406: return setValueV1fArray; // FLOAT
  45743. case 0x8b50: return setValueV2fArray; // _VEC2
  45744. case 0x8b51: return setValueV3fArray; // _VEC3
  45745. case 0x8b52: return setValueV4fArray; // _VEC4
  45746. case 0x8b5a: return setValueM2Array; // _MAT2
  45747. case 0x8b5b: return setValueM3Array; // _MAT3
  45748. case 0x8b5c: return setValueM4Array; // _MAT4
  45749. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  45750. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  45751. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  45752. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  45753. case 0x1405: return setValueV1uiArray; // UINT
  45754. case 0x8dc6: return setValueV2uiArray; // _VEC2
  45755. case 0x8dc7: return setValueV3uiArray; // _VEC3
  45756. case 0x8dc8: return setValueV4uiArray; // _VEC4
  45757. case 0x8b5e: // SAMPLER_2D
  45758. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45759. case 0x8dca: // INT_SAMPLER_2D
  45760. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45761. case 0x8b62: // SAMPLER_2D_SHADOW
  45762. return setValueT1Array;
  45763. case 0x8b5f: // SAMPLER_3D
  45764. case 0x8dcb: // INT_SAMPLER_3D
  45765. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45766. return setValueT3DArray;
  45767. case 0x8b60: // SAMPLER_CUBE
  45768. case 0x8dcc: // INT_SAMPLER_CUBE
  45769. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45770. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45771. return setValueT6Array;
  45772. case 0x8dc1: // SAMPLER_2D_ARRAY
  45773. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45774. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45775. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45776. return setValueT2DArrayArray;
  45777. }
  45778. }
  45779. // --- Uniform Classes ---
  45780. class SingleUniform {
  45781. constructor( id, activeInfo, addr ) {
  45782. this.id = id;
  45783. this.addr = addr;
  45784. this.cache = [];
  45785. this.type = activeInfo.type;
  45786. this.setValue = getSingularSetter( activeInfo.type );
  45787. // this.path = activeInfo.name; // DEBUG
  45788. }
  45789. }
  45790. class PureArrayUniform {
  45791. constructor( id, activeInfo, addr ) {
  45792. this.id = id;
  45793. this.addr = addr;
  45794. this.cache = [];
  45795. this.type = activeInfo.type;
  45796. this.size = activeInfo.size;
  45797. this.setValue = getPureArraySetter( activeInfo.type );
  45798. // this.path = activeInfo.name; // DEBUG
  45799. }
  45800. }
  45801. class StructuredUniform {
  45802. constructor( id ) {
  45803. this.id = id;
  45804. this.seq = [];
  45805. this.map = {};
  45806. }
  45807. setValue( gl, value, textures ) {
  45808. const seq = this.seq;
  45809. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45810. const u = seq[ i ];
  45811. u.setValue( gl, value[ u.id ], textures );
  45812. }
  45813. }
  45814. }
  45815. // --- Top-level ---
  45816. // Parser - builds up the property tree from the path strings
  45817. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  45818. // extracts
  45819. // - the identifier (member name or array index)
  45820. // - followed by an optional right bracket (found when array index)
  45821. // - followed by an optional left bracket or dot (type of subscript)
  45822. //
  45823. // Note: These portions can be read in a non-overlapping fashion and
  45824. // allow straightforward parsing of the hierarchy that WebGL encodes
  45825. // in the uniform names.
  45826. function addUniform( container, uniformObject ) {
  45827. container.seq.push( uniformObject );
  45828. container.map[ uniformObject.id ] = uniformObject;
  45829. }
  45830. function parseUniform( activeInfo, addr, container ) {
  45831. const path = activeInfo.name,
  45832. pathLength = path.length;
  45833. // reset RegExp object, because of the early exit of a previous run
  45834. RePathPart.lastIndex = 0;
  45835. while ( true ) {
  45836. const match = RePathPart.exec( path ),
  45837. matchEnd = RePathPart.lastIndex;
  45838. let id = match[ 1 ];
  45839. const idIsIndex = match[ 2 ] === ']',
  45840. subscript = match[ 3 ];
  45841. if ( idIsIndex ) id = id | 0; // convert to integer
  45842. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  45843. // bare name or "pure" bottom-level array "[0]" suffix
  45844. addUniform( container, subscript === undefined ?
  45845. new SingleUniform( id, activeInfo, addr ) :
  45846. new PureArrayUniform( id, activeInfo, addr ) );
  45847. break;
  45848. } else {
  45849. // step into inner node / create it in case it doesn't exist
  45850. const map = container.map;
  45851. let next = map[ id ];
  45852. if ( next === undefined ) {
  45853. next = new StructuredUniform( id );
  45854. addUniform( container, next );
  45855. }
  45856. container = next;
  45857. }
  45858. }
  45859. }
  45860. // Root Container
  45861. class WebGLUniforms {
  45862. constructor( gl, program ) {
  45863. this.seq = [];
  45864. this.map = {};
  45865. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  45866. for ( let i = 0; i < n; ++ i ) {
  45867. const info = gl.getActiveUniform( program, i ),
  45868. addr = gl.getUniformLocation( program, info.name );
  45869. parseUniform( info, addr, this );
  45870. }
  45871. }
  45872. setValue( gl, name, value, textures ) {
  45873. const u = this.map[ name ];
  45874. if ( u !== undefined ) u.setValue( gl, value, textures );
  45875. }
  45876. setOptional( gl, object, name ) {
  45877. const v = object[ name ];
  45878. if ( v !== undefined ) this.setValue( gl, name, v );
  45879. }
  45880. static upload( gl, seq, values, textures ) {
  45881. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45882. const u = seq[ i ],
  45883. v = values[ u.id ];
  45884. if ( v.needsUpdate !== false ) {
  45885. // note: always updating when .needsUpdate is undefined
  45886. u.setValue( gl, v.value, textures );
  45887. }
  45888. }
  45889. }
  45890. static seqWithValue( seq, values ) {
  45891. const r = [];
  45892. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45893. const u = seq[ i ];
  45894. if ( u.id in values ) r.push( u );
  45895. }
  45896. return r;
  45897. }
  45898. }
  45899. function WebGLShader( gl, type, string ) {
  45900. const shader = gl.createShader( type );
  45901. gl.shaderSource( shader, string );
  45902. gl.compileShader( shader );
  45903. return shader;
  45904. }
  45905. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  45906. const COMPLETION_STATUS_KHR = 0x91B1;
  45907. let programIdCount = 0;
  45908. function handleSource( string, errorLine ) {
  45909. const lines = string.split( '\n' );
  45910. const lines2 = [];
  45911. const from = Math.max( errorLine - 6, 0 );
  45912. const to = Math.min( errorLine + 6, lines.length );
  45913. for ( let i = from; i < to; i ++ ) {
  45914. const line = i + 1;
  45915. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  45916. }
  45917. return lines2.join( '\n' );
  45918. }
  45919. const _m0 = /*@__PURE__*/ new Matrix3();
  45920. function getEncodingComponents( colorSpace ) {
  45921. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  45922. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  45923. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  45924. case LinearTransfer:
  45925. return [ encodingMatrix, 'LinearTransferOETF' ];
  45926. case SRGBTransfer:
  45927. return [ encodingMatrix, 'sRGBTransferOETF' ];
  45928. default:
  45929. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  45930. return [ encodingMatrix, 'LinearTransferOETF' ];
  45931. }
  45932. }
  45933. function getShaderErrors( gl, shader, type ) {
  45934. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  45935. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  45936. const errors = shaderInfoLog.trim();
  45937. if ( status && errors === '' ) return '';
  45938. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  45939. if ( errorMatches ) {
  45940. // --enable-privileged-webgl-extension
  45941. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  45942. const errorLine = parseInt( errorMatches[ 1 ] );
  45943. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  45944. } else {
  45945. return errors;
  45946. }
  45947. }
  45948. function getTexelEncodingFunction( functionName, colorSpace ) {
  45949. const components = getEncodingComponents( colorSpace );
  45950. return [
  45951. `vec4 ${functionName}( vec4 value ) {`,
  45952. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  45953. '}',
  45954. ].join( '\n' );
  45955. }
  45956. function getToneMappingFunction( functionName, toneMapping ) {
  45957. let toneMappingName;
  45958. switch ( toneMapping ) {
  45959. case LinearToneMapping:
  45960. toneMappingName = 'Linear';
  45961. break;
  45962. case ReinhardToneMapping:
  45963. toneMappingName = 'Reinhard';
  45964. break;
  45965. case CineonToneMapping:
  45966. toneMappingName = 'Cineon';
  45967. break;
  45968. case ACESFilmicToneMapping:
  45969. toneMappingName = 'ACESFilmic';
  45970. break;
  45971. case AgXToneMapping:
  45972. toneMappingName = 'AgX';
  45973. break;
  45974. case NeutralToneMapping:
  45975. toneMappingName = 'Neutral';
  45976. break;
  45977. case CustomToneMapping:
  45978. toneMappingName = 'Custom';
  45979. break;
  45980. default:
  45981. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  45982. toneMappingName = 'Linear';
  45983. }
  45984. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  45985. }
  45986. const _v0 = /*@__PURE__*/ new Vector3();
  45987. function getLuminanceFunction() {
  45988. ColorManagement.getLuminanceCoefficients( _v0 );
  45989. const r = _v0.x.toFixed( 4 );
  45990. const g = _v0.y.toFixed( 4 );
  45991. const b = _v0.z.toFixed( 4 );
  45992. return [
  45993. 'float luminance( const in vec3 rgb ) {',
  45994. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  45995. ' return dot( weights, rgb );',
  45996. '}'
  45997. ].join( '\n' );
  45998. }
  45999. function generateVertexExtensions( parameters ) {
  46000. const chunks = [
  46001. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46002. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46003. ];
  46004. return chunks.filter( filterEmptyLine ).join( '\n' );
  46005. }
  46006. function generateDefines( defines ) {
  46007. const chunks = [];
  46008. for ( const name in defines ) {
  46009. const value = defines[ name ];
  46010. if ( value === false ) continue;
  46011. chunks.push( '#define ' + name + ' ' + value );
  46012. }
  46013. return chunks.join( '\n' );
  46014. }
  46015. function fetchAttributeLocations( gl, program ) {
  46016. const attributes = {};
  46017. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46018. for ( let i = 0; i < n; i ++ ) {
  46019. const info = gl.getActiveAttrib( program, i );
  46020. const name = info.name;
  46021. let locationSize = 1;
  46022. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46023. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46024. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46025. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46026. attributes[ name ] = {
  46027. type: info.type,
  46028. location: gl.getAttribLocation( program, name ),
  46029. locationSize: locationSize
  46030. };
  46031. }
  46032. return attributes;
  46033. }
  46034. function filterEmptyLine( string ) {
  46035. return string !== '';
  46036. }
  46037. function replaceLightNums( string, parameters ) {
  46038. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46039. return string
  46040. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46041. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46042. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46043. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46044. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46045. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46046. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46047. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46048. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46049. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46050. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46051. }
  46052. function replaceClippingPlaneNums( string, parameters ) {
  46053. return string
  46054. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46055. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46056. }
  46057. // Resolve Includes
  46058. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46059. function resolveIncludes( string ) {
  46060. return string.replace( includePattern, includeReplacer );
  46061. }
  46062. const shaderChunkMap = new Map();
  46063. function includeReplacer( match, include ) {
  46064. let string = ShaderChunk[ include ];
  46065. if ( string === undefined ) {
  46066. const newInclude = shaderChunkMap.get( include );
  46067. if ( newInclude !== undefined ) {
  46068. string = ShaderChunk[ newInclude ];
  46069. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46070. } else {
  46071. throw new Error( 'Can not resolve #include <' + include + '>' );
  46072. }
  46073. }
  46074. return resolveIncludes( string );
  46075. }
  46076. // Unroll Loops
  46077. 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;
  46078. function unrollLoops( string ) {
  46079. return string.replace( unrollLoopPattern, loopReplacer );
  46080. }
  46081. function loopReplacer( match, start, end, snippet ) {
  46082. let string = '';
  46083. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46084. string += snippet
  46085. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46086. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46087. }
  46088. return string;
  46089. }
  46090. //
  46091. function generatePrecision( parameters ) {
  46092. let precisionstring = `precision ${parameters.precision} float;
  46093. precision ${parameters.precision} int;
  46094. precision ${parameters.precision} sampler2D;
  46095. precision ${parameters.precision} samplerCube;
  46096. precision ${parameters.precision} sampler3D;
  46097. precision ${parameters.precision} sampler2DArray;
  46098. precision ${parameters.precision} sampler2DShadow;
  46099. precision ${parameters.precision} samplerCubeShadow;
  46100. precision ${parameters.precision} sampler2DArrayShadow;
  46101. precision ${parameters.precision} isampler2D;
  46102. precision ${parameters.precision} isampler3D;
  46103. precision ${parameters.precision} isamplerCube;
  46104. precision ${parameters.precision} isampler2DArray;
  46105. precision ${parameters.precision} usampler2D;
  46106. precision ${parameters.precision} usampler3D;
  46107. precision ${parameters.precision} usamplerCube;
  46108. precision ${parameters.precision} usampler2DArray;
  46109. `;
  46110. if ( parameters.precision === 'highp' ) {
  46111. precisionstring += '\n#define HIGH_PRECISION';
  46112. } else if ( parameters.precision === 'mediump' ) {
  46113. precisionstring += '\n#define MEDIUM_PRECISION';
  46114. } else if ( parameters.precision === 'lowp' ) {
  46115. precisionstring += '\n#define LOW_PRECISION';
  46116. }
  46117. return precisionstring;
  46118. }
  46119. function generateShadowMapTypeDefine( parameters ) {
  46120. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  46121. if ( parameters.shadowMapType === PCFShadowMap ) {
  46122. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  46123. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  46124. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  46125. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  46126. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  46127. }
  46128. return shadowMapTypeDefine;
  46129. }
  46130. function generateEnvMapTypeDefine( parameters ) {
  46131. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46132. if ( parameters.envMap ) {
  46133. switch ( parameters.envMapMode ) {
  46134. case CubeReflectionMapping:
  46135. case CubeRefractionMapping:
  46136. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46137. break;
  46138. case CubeUVReflectionMapping:
  46139. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  46140. break;
  46141. }
  46142. }
  46143. return envMapTypeDefine;
  46144. }
  46145. function generateEnvMapModeDefine( parameters ) {
  46146. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  46147. if ( parameters.envMap ) {
  46148. switch ( parameters.envMapMode ) {
  46149. case CubeRefractionMapping:
  46150. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  46151. break;
  46152. }
  46153. }
  46154. return envMapModeDefine;
  46155. }
  46156. function generateEnvMapBlendingDefine( parameters ) {
  46157. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  46158. if ( parameters.envMap ) {
  46159. switch ( parameters.combine ) {
  46160. case MultiplyOperation:
  46161. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  46162. break;
  46163. case MixOperation:
  46164. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  46165. break;
  46166. case AddOperation:
  46167. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  46168. break;
  46169. }
  46170. }
  46171. return envMapBlendingDefine;
  46172. }
  46173. function generateCubeUVSize( parameters ) {
  46174. const imageHeight = parameters.envMapCubeUVHeight;
  46175. if ( imageHeight === null ) return null;
  46176. const maxMip = Math.log2( imageHeight ) - 2;
  46177. const texelHeight = 1.0 / imageHeight;
  46178. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46179. return { texelWidth, texelHeight, maxMip };
  46180. }
  46181. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46182. // TODO Send this event to Three.js DevTools
  46183. // console.log( 'WebGLProgram', cacheKey );
  46184. const gl = renderer.getContext();
  46185. const defines = parameters.defines;
  46186. let vertexShader = parameters.vertexShader;
  46187. let fragmentShader = parameters.fragmentShader;
  46188. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46189. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46190. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46191. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46192. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46193. const customVertexExtensions = generateVertexExtensions( parameters );
  46194. const customDefines = generateDefines( defines );
  46195. const program = gl.createProgram();
  46196. let prefixVertex, prefixFragment;
  46197. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46198. if ( parameters.isRawShaderMaterial ) {
  46199. prefixVertex = [
  46200. '#define SHADER_TYPE ' + parameters.shaderType,
  46201. '#define SHADER_NAME ' + parameters.shaderName,
  46202. customDefines
  46203. ].filter( filterEmptyLine ).join( '\n' );
  46204. if ( prefixVertex.length > 0 ) {
  46205. prefixVertex += '\n';
  46206. }
  46207. prefixFragment = [
  46208. '#define SHADER_TYPE ' + parameters.shaderType,
  46209. '#define SHADER_NAME ' + parameters.shaderName,
  46210. customDefines
  46211. ].filter( filterEmptyLine ).join( '\n' );
  46212. if ( prefixFragment.length > 0 ) {
  46213. prefixFragment += '\n';
  46214. }
  46215. } else {
  46216. prefixVertex = [
  46217. generatePrecision( parameters ),
  46218. '#define SHADER_TYPE ' + parameters.shaderType,
  46219. '#define SHADER_NAME ' + parameters.shaderName,
  46220. customDefines,
  46221. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46222. parameters.batching ? '#define USE_BATCHING' : '',
  46223. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46224. parameters.instancing ? '#define USE_INSTANCING' : '',
  46225. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46226. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46227. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46228. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46229. parameters.map ? '#define USE_MAP' : '',
  46230. parameters.envMap ? '#define USE_ENVMAP' : '',
  46231. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46232. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46233. parameters.aoMap ? '#define USE_AOMAP' : '',
  46234. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46235. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46236. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46237. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46238. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46239. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46240. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46241. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46242. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46243. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46244. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46245. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46246. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46247. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46248. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46249. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46250. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46251. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46252. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46253. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46254. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46255. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46256. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46257. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46258. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46259. //
  46260. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46261. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46262. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46263. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46264. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46265. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46266. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46267. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46268. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46269. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46270. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46271. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46272. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46273. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46274. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46275. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46276. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46277. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46278. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46279. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46280. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46281. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46282. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46283. //
  46284. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46285. parameters.vertexColors ? '#define USE_COLOR' : '',
  46286. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46287. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46288. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46289. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46290. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46291. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46292. parameters.skinning ? '#define USE_SKINNING' : '',
  46293. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46294. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46295. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46296. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46297. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46298. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46299. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46300. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46301. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46302. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46303. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46304. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  46305. parameters.reversedDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  46306. 'uniform mat4 modelMatrix;',
  46307. 'uniform mat4 modelViewMatrix;',
  46308. 'uniform mat4 projectionMatrix;',
  46309. 'uniform mat4 viewMatrix;',
  46310. 'uniform mat3 normalMatrix;',
  46311. 'uniform vec3 cameraPosition;',
  46312. 'uniform bool isOrthographic;',
  46313. '#ifdef USE_INSTANCING',
  46314. ' attribute mat4 instanceMatrix;',
  46315. '#endif',
  46316. '#ifdef USE_INSTANCING_COLOR',
  46317. ' attribute vec3 instanceColor;',
  46318. '#endif',
  46319. '#ifdef USE_INSTANCING_MORPH',
  46320. ' uniform sampler2D morphTexture;',
  46321. '#endif',
  46322. 'attribute vec3 position;',
  46323. 'attribute vec3 normal;',
  46324. 'attribute vec2 uv;',
  46325. '#ifdef USE_UV1',
  46326. ' attribute vec2 uv1;',
  46327. '#endif',
  46328. '#ifdef USE_UV2',
  46329. ' attribute vec2 uv2;',
  46330. '#endif',
  46331. '#ifdef USE_UV3',
  46332. ' attribute vec2 uv3;',
  46333. '#endif',
  46334. '#ifdef USE_TANGENT',
  46335. ' attribute vec4 tangent;',
  46336. '#endif',
  46337. '#if defined( USE_COLOR_ALPHA )',
  46338. ' attribute vec4 color;',
  46339. '#elif defined( USE_COLOR )',
  46340. ' attribute vec3 color;',
  46341. '#endif',
  46342. '#ifdef USE_SKINNING',
  46343. ' attribute vec4 skinIndex;',
  46344. ' attribute vec4 skinWeight;',
  46345. '#endif',
  46346. '\n'
  46347. ].filter( filterEmptyLine ).join( '\n' );
  46348. prefixFragment = [
  46349. generatePrecision( parameters ),
  46350. '#define SHADER_TYPE ' + parameters.shaderType,
  46351. '#define SHADER_NAME ' + parameters.shaderName,
  46352. customDefines,
  46353. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46354. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46355. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46356. parameters.map ? '#define USE_MAP' : '',
  46357. parameters.matcap ? '#define USE_MATCAP' : '',
  46358. parameters.envMap ? '#define USE_ENVMAP' : '',
  46359. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46360. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46361. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46362. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46363. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46364. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46365. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46366. parameters.aoMap ? '#define USE_AOMAP' : '',
  46367. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46368. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46369. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46370. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46371. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46372. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46373. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46374. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46375. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46376. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46377. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46378. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46379. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46380. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46381. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46382. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46383. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46384. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46385. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46386. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46387. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46388. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  46389. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46390. parameters.sheen ? '#define USE_SHEEN' : '',
  46391. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46392. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46393. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46394. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46395. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46396. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46397. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  46398. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46399. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46400. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46401. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46402. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46403. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  46404. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46405. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46406. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46407. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46408. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46409. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  46410. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46411. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  46412. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  46413. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  46414. parameters.reversedDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  46415. 'uniform mat4 viewMatrix;',
  46416. 'uniform vec3 cameraPosition;',
  46417. 'uniform bool isOrthographic;',
  46418. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  46419. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  46420. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  46421. parameters.dithering ? '#define DITHERING' : '',
  46422. parameters.opaque ? '#define OPAQUE' : '',
  46423. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  46424. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  46425. getLuminanceFunction(),
  46426. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  46427. '\n'
  46428. ].filter( filterEmptyLine ).join( '\n' );
  46429. }
  46430. vertexShader = resolveIncludes( vertexShader );
  46431. vertexShader = replaceLightNums( vertexShader, parameters );
  46432. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  46433. fragmentShader = resolveIncludes( fragmentShader );
  46434. fragmentShader = replaceLightNums( fragmentShader, parameters );
  46435. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  46436. vertexShader = unrollLoops( vertexShader );
  46437. fragmentShader = unrollLoops( fragmentShader );
  46438. if ( parameters.isRawShaderMaterial !== true ) {
  46439. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  46440. versionString = '#version 300 es\n';
  46441. prefixVertex = [
  46442. customVertexExtensions,
  46443. '#define attribute in',
  46444. '#define varying out',
  46445. '#define texture2D texture'
  46446. ].join( '\n' ) + '\n' + prefixVertex;
  46447. prefixFragment = [
  46448. '#define varying in',
  46449. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  46450. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  46451. '#define gl_FragDepthEXT gl_FragDepth',
  46452. '#define texture2D texture',
  46453. '#define textureCube texture',
  46454. '#define texture2DProj textureProj',
  46455. '#define texture2DLodEXT textureLod',
  46456. '#define texture2DProjLodEXT textureProjLod',
  46457. '#define textureCubeLodEXT textureLod',
  46458. '#define texture2DGradEXT textureGrad',
  46459. '#define texture2DProjGradEXT textureProjGrad',
  46460. '#define textureCubeGradEXT textureGrad'
  46461. ].join( '\n' ) + '\n' + prefixFragment;
  46462. }
  46463. const vertexGlsl = versionString + prefixVertex + vertexShader;
  46464. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  46465. // console.log( '*VERTEX*', vertexGlsl );
  46466. // console.log( '*FRAGMENT*', fragmentGlsl );
  46467. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  46468. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  46469. gl.attachShader( program, glVertexShader );
  46470. gl.attachShader( program, glFragmentShader );
  46471. // Force a particular attribute to index 0.
  46472. if ( parameters.index0AttributeName !== undefined ) {
  46473. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  46474. } else if ( parameters.morphTargets === true ) {
  46475. // programs with morphTargets displace position out of attribute 0
  46476. gl.bindAttribLocation( program, 0, 'position' );
  46477. }
  46478. gl.linkProgram( program );
  46479. function onFirstUse( self ) {
  46480. // check for link errors
  46481. if ( renderer.debug.checkShaderErrors ) {
  46482. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  46483. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  46484. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  46485. const programLog = programInfoLog.trim();
  46486. const vertexLog = vertexShaderInfoLog.trim();
  46487. const fragmentLog = fragmentShaderInfoLog.trim();
  46488. let runnable = true;
  46489. let haveDiagnostics = true;
  46490. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  46491. runnable = false;
  46492. if ( typeof renderer.debug.onShaderError === 'function' ) {
  46493. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  46494. } else {
  46495. // default error reporting
  46496. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  46497. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  46498. console.error(
  46499. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46500. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  46501. 'Material Name: ' + self.name + '\n' +
  46502. 'Material Type: ' + self.type + '\n\n' +
  46503. 'Program Info Log: ' + programLog + '\n' +
  46504. vertexErrors + '\n' +
  46505. fragmentErrors
  46506. );
  46507. }
  46508. } else if ( programLog !== '' ) {
  46509. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46510. } else if ( vertexLog === '' || fragmentLog === '' ) {
  46511. haveDiagnostics = false;
  46512. }
  46513. if ( haveDiagnostics ) {
  46514. self.diagnostics = {
  46515. runnable: runnable,
  46516. programLog: programLog,
  46517. vertexShader: {
  46518. log: vertexLog,
  46519. prefix: prefixVertex
  46520. },
  46521. fragmentShader: {
  46522. log: fragmentLog,
  46523. prefix: prefixFragment
  46524. }
  46525. };
  46526. }
  46527. }
  46528. // Clean up
  46529. // Crashes in iOS9 and iOS10. #18402
  46530. // gl.detachShader( program, glVertexShader );
  46531. // gl.detachShader( program, glFragmentShader );
  46532. gl.deleteShader( glVertexShader );
  46533. gl.deleteShader( glFragmentShader );
  46534. cachedUniforms = new WebGLUniforms( gl, program );
  46535. cachedAttributes = fetchAttributeLocations( gl, program );
  46536. }
  46537. // set up caching for uniform locations
  46538. let cachedUniforms;
  46539. this.getUniforms = function () {
  46540. if ( cachedUniforms === undefined ) {
  46541. // Populates cachedUniforms and cachedAttributes
  46542. onFirstUse( this );
  46543. }
  46544. return cachedUniforms;
  46545. };
  46546. // set up caching for attribute locations
  46547. let cachedAttributes;
  46548. this.getAttributes = function () {
  46549. if ( cachedAttributes === undefined ) {
  46550. // Populates cachedAttributes and cachedUniforms
  46551. onFirstUse( this );
  46552. }
  46553. return cachedAttributes;
  46554. };
  46555. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  46556. // flag the program as ready immediately. It may cause a stall when it's first used.
  46557. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  46558. this.isReady = function () {
  46559. if ( programReady === false ) {
  46560. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  46561. }
  46562. return programReady;
  46563. };
  46564. // free resource
  46565. this.destroy = function () {
  46566. bindingStates.releaseStatesOfProgram( this );
  46567. gl.deleteProgram( program );
  46568. this.program = undefined;
  46569. };
  46570. //
  46571. this.type = parameters.shaderType;
  46572. this.name = parameters.shaderName;
  46573. this.id = programIdCount ++;
  46574. this.cacheKey = cacheKey;
  46575. this.usedTimes = 1;
  46576. this.program = program;
  46577. this.vertexShader = glVertexShader;
  46578. this.fragmentShader = glFragmentShader;
  46579. return this;
  46580. }
  46581. let _id = 0;
  46582. class WebGLShaderCache {
  46583. constructor() {
  46584. this.shaderCache = new Map();
  46585. this.materialCache = new Map();
  46586. }
  46587. update( material ) {
  46588. const vertexShader = material.vertexShader;
  46589. const fragmentShader = material.fragmentShader;
  46590. const vertexShaderStage = this._getShaderStage( vertexShader );
  46591. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  46592. const materialShaders = this._getShaderCacheForMaterial( material );
  46593. if ( materialShaders.has( vertexShaderStage ) === false ) {
  46594. materialShaders.add( vertexShaderStage );
  46595. vertexShaderStage.usedTimes ++;
  46596. }
  46597. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  46598. materialShaders.add( fragmentShaderStage );
  46599. fragmentShaderStage.usedTimes ++;
  46600. }
  46601. return this;
  46602. }
  46603. remove( material ) {
  46604. const materialShaders = this.materialCache.get( material );
  46605. for ( const shaderStage of materialShaders ) {
  46606. shaderStage.usedTimes --;
  46607. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  46608. }
  46609. this.materialCache.delete( material );
  46610. return this;
  46611. }
  46612. getVertexShaderID( material ) {
  46613. return this._getShaderStage( material.vertexShader ).id;
  46614. }
  46615. getFragmentShaderID( material ) {
  46616. return this._getShaderStage( material.fragmentShader ).id;
  46617. }
  46618. dispose() {
  46619. this.shaderCache.clear();
  46620. this.materialCache.clear();
  46621. }
  46622. _getShaderCacheForMaterial( material ) {
  46623. const cache = this.materialCache;
  46624. let set = cache.get( material );
  46625. if ( set === undefined ) {
  46626. set = new Set();
  46627. cache.set( material, set );
  46628. }
  46629. return set;
  46630. }
  46631. _getShaderStage( code ) {
  46632. const cache = this.shaderCache;
  46633. let stage = cache.get( code );
  46634. if ( stage === undefined ) {
  46635. stage = new WebGLShaderStage( code );
  46636. cache.set( code, stage );
  46637. }
  46638. return stage;
  46639. }
  46640. }
  46641. class WebGLShaderStage {
  46642. constructor( code ) {
  46643. this.id = _id ++;
  46644. this.code = code;
  46645. this.usedTimes = 0;
  46646. }
  46647. }
  46648. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  46649. const _programLayers = new Layers();
  46650. const _customShaders = new WebGLShaderCache();
  46651. const _activeChannels = new Set();
  46652. const programs = [];
  46653. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  46654. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  46655. let precision = capabilities.precision;
  46656. const shaderIDs = {
  46657. MeshDepthMaterial: 'depth',
  46658. MeshDistanceMaterial: 'distanceRGBA',
  46659. MeshNormalMaterial: 'normal',
  46660. MeshBasicMaterial: 'basic',
  46661. MeshLambertMaterial: 'lambert',
  46662. MeshPhongMaterial: 'phong',
  46663. MeshToonMaterial: 'toon',
  46664. MeshStandardMaterial: 'physical',
  46665. MeshPhysicalMaterial: 'physical',
  46666. MeshMatcapMaterial: 'matcap',
  46667. LineBasicMaterial: 'basic',
  46668. LineDashedMaterial: 'dashed',
  46669. PointsMaterial: 'points',
  46670. ShadowMaterial: 'shadow',
  46671. SpriteMaterial: 'sprite'
  46672. };
  46673. function getChannel( value ) {
  46674. _activeChannels.add( value );
  46675. if ( value === 0 ) return 'uv';
  46676. return `uv${ value }`;
  46677. }
  46678. function getParameters( material, lights, shadows, scene, object ) {
  46679. const fog = scene.fog;
  46680. const geometry = object.geometry;
  46681. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  46682. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  46683. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  46684. const shaderID = shaderIDs[ material.type ];
  46685. // heuristics to create shader parameters according to lights in the scene
  46686. // (not to blow over maxLights budget)
  46687. if ( material.precision !== null ) {
  46688. precision = capabilities.getMaxPrecision( material.precision );
  46689. if ( precision !== material.precision ) {
  46690. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  46691. }
  46692. }
  46693. //
  46694. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  46695. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  46696. let morphTextureStride = 0;
  46697. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  46698. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  46699. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  46700. //
  46701. let vertexShader, fragmentShader;
  46702. let customVertexShaderID, customFragmentShaderID;
  46703. if ( shaderID ) {
  46704. const shader = ShaderLib[ shaderID ];
  46705. vertexShader = shader.vertexShader;
  46706. fragmentShader = shader.fragmentShader;
  46707. } else {
  46708. vertexShader = material.vertexShader;
  46709. fragmentShader = material.fragmentShader;
  46710. _customShaders.update( material );
  46711. customVertexShaderID = _customShaders.getVertexShaderID( material );
  46712. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  46713. }
  46714. const currentRenderTarget = renderer.getRenderTarget();
  46715. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  46716. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  46717. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  46718. const HAS_MAP = !! material.map;
  46719. const HAS_MATCAP = !! material.matcap;
  46720. const HAS_ENVMAP = !! envMap;
  46721. const HAS_AOMAP = !! material.aoMap;
  46722. const HAS_LIGHTMAP = !! material.lightMap;
  46723. const HAS_BUMPMAP = !! material.bumpMap;
  46724. const HAS_NORMALMAP = !! material.normalMap;
  46725. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  46726. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  46727. const HAS_METALNESSMAP = !! material.metalnessMap;
  46728. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  46729. const HAS_ANISOTROPY = material.anisotropy > 0;
  46730. const HAS_CLEARCOAT = material.clearcoat > 0;
  46731. const HAS_DISPERSION = material.dispersion > 0;
  46732. const HAS_IRIDESCENCE = material.iridescence > 0;
  46733. const HAS_SHEEN = material.sheen > 0;
  46734. const HAS_TRANSMISSION = material.transmission > 0;
  46735. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  46736. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  46737. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  46738. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  46739. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  46740. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  46741. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  46742. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  46743. const HAS_SPECULARMAP = !! material.specularMap;
  46744. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  46745. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  46746. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  46747. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  46748. const HAS_GRADIENTMAP = !! material.gradientMap;
  46749. const HAS_ALPHAMAP = !! material.alphaMap;
  46750. const HAS_ALPHATEST = material.alphaTest > 0;
  46751. const HAS_ALPHAHASH = !! material.alphaHash;
  46752. const HAS_EXTENSIONS = !! material.extensions;
  46753. let toneMapping = NoToneMapping;
  46754. if ( material.toneMapped ) {
  46755. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  46756. toneMapping = renderer.toneMapping;
  46757. }
  46758. }
  46759. const parameters = {
  46760. shaderID: shaderID,
  46761. shaderType: material.type,
  46762. shaderName: material.name,
  46763. vertexShader: vertexShader,
  46764. fragmentShader: fragmentShader,
  46765. defines: material.defines,
  46766. customVertexShaderID: customVertexShaderID,
  46767. customFragmentShaderID: customFragmentShaderID,
  46768. isRawShaderMaterial: material.isRawShaderMaterial === true,
  46769. glslVersion: material.glslVersion,
  46770. precision: precision,
  46771. batching: IS_BATCHEDMESH,
  46772. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  46773. instancing: IS_INSTANCEDMESH,
  46774. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  46775. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  46776. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  46777. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  46778. alphaToCoverage: !! material.alphaToCoverage,
  46779. map: HAS_MAP,
  46780. matcap: HAS_MATCAP,
  46781. envMap: HAS_ENVMAP,
  46782. envMapMode: HAS_ENVMAP && envMap.mapping,
  46783. envMapCubeUVHeight: envMapCubeUVHeight,
  46784. aoMap: HAS_AOMAP,
  46785. lightMap: HAS_LIGHTMAP,
  46786. bumpMap: HAS_BUMPMAP,
  46787. normalMap: HAS_NORMALMAP,
  46788. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  46789. emissiveMap: HAS_EMISSIVEMAP,
  46790. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  46791. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  46792. metalnessMap: HAS_METALNESSMAP,
  46793. roughnessMap: HAS_ROUGHNESSMAP,
  46794. anisotropy: HAS_ANISOTROPY,
  46795. anisotropyMap: HAS_ANISOTROPYMAP,
  46796. clearcoat: HAS_CLEARCOAT,
  46797. clearcoatMap: HAS_CLEARCOATMAP,
  46798. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  46799. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  46800. dispersion: HAS_DISPERSION,
  46801. iridescence: HAS_IRIDESCENCE,
  46802. iridescenceMap: HAS_IRIDESCENCEMAP,
  46803. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  46804. sheen: HAS_SHEEN,
  46805. sheenColorMap: HAS_SHEEN_COLORMAP,
  46806. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  46807. specularMap: HAS_SPECULARMAP,
  46808. specularColorMap: HAS_SPECULAR_COLORMAP,
  46809. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  46810. transmission: HAS_TRANSMISSION,
  46811. transmissionMap: HAS_TRANSMISSIONMAP,
  46812. thicknessMap: HAS_THICKNESSMAP,
  46813. gradientMap: HAS_GRADIENTMAP,
  46814. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  46815. alphaMap: HAS_ALPHAMAP,
  46816. alphaTest: HAS_ALPHATEST,
  46817. alphaHash: HAS_ALPHAHASH,
  46818. combine: material.combine,
  46819. //
  46820. mapUv: HAS_MAP && getChannel( material.map.channel ),
  46821. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  46822. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  46823. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  46824. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  46825. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  46826. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  46827. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  46828. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  46829. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  46830. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  46831. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  46832. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  46833. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  46834. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  46835. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  46836. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  46837. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  46838. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  46839. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  46840. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  46841. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  46842. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  46843. //
  46844. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  46845. vertexColors: material.vertexColors,
  46846. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  46847. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  46848. fog: !! fog,
  46849. useFog: material.fog === true,
  46850. fogExp2: ( !! fog && fog.isFogExp2 ),
  46851. flatShading: ( material.flatShading === true && material.wireframe === false ),
  46852. sizeAttenuation: material.sizeAttenuation === true,
  46853. logarithmicDepthBuffer: logarithmicDepthBuffer,
  46854. reversedDepthBuffer: reversedDepthBuffer,
  46855. skinning: object.isSkinnedMesh === true,
  46856. morphTargets: geometry.morphAttributes.position !== undefined,
  46857. morphNormals: geometry.morphAttributes.normal !== undefined,
  46858. morphColors: geometry.morphAttributes.color !== undefined,
  46859. morphTargetsCount: morphTargetsCount,
  46860. morphTextureStride: morphTextureStride,
  46861. numDirLights: lights.directional.length,
  46862. numPointLights: lights.point.length,
  46863. numSpotLights: lights.spot.length,
  46864. numSpotLightMaps: lights.spotLightMap.length,
  46865. numRectAreaLights: lights.rectArea.length,
  46866. numHemiLights: lights.hemi.length,
  46867. numDirLightShadows: lights.directionalShadowMap.length,
  46868. numPointLightShadows: lights.pointShadowMap.length,
  46869. numSpotLightShadows: lights.spotShadowMap.length,
  46870. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  46871. numLightProbes: lights.numLightProbes,
  46872. numClippingPlanes: clipping.numPlanes,
  46873. numClipIntersection: clipping.numIntersection,
  46874. dithering: material.dithering,
  46875. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  46876. shadowMapType: renderer.shadowMap.type,
  46877. toneMapping: toneMapping,
  46878. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  46879. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  46880. premultipliedAlpha: material.premultipliedAlpha,
  46881. doubleSided: material.side === DoubleSide,
  46882. flipSided: material.side === BackSide,
  46883. useDepthPacking: material.depthPacking >= 0,
  46884. depthPacking: material.depthPacking || 0,
  46885. index0AttributeName: material.index0AttributeName,
  46886. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  46887. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  46888. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  46889. customProgramCacheKey: material.customProgramCacheKey()
  46890. };
  46891. // the usage of getChannel() determines the active texture channels for this shader
  46892. parameters.vertexUv1s = _activeChannels.has( 1 );
  46893. parameters.vertexUv2s = _activeChannels.has( 2 );
  46894. parameters.vertexUv3s = _activeChannels.has( 3 );
  46895. _activeChannels.clear();
  46896. return parameters;
  46897. }
  46898. function getProgramCacheKey( parameters ) {
  46899. const array = [];
  46900. if ( parameters.shaderID ) {
  46901. array.push( parameters.shaderID );
  46902. } else {
  46903. array.push( parameters.customVertexShaderID );
  46904. array.push( parameters.customFragmentShaderID );
  46905. }
  46906. if ( parameters.defines !== undefined ) {
  46907. for ( const name in parameters.defines ) {
  46908. array.push( name );
  46909. array.push( parameters.defines[ name ] );
  46910. }
  46911. }
  46912. if ( parameters.isRawShaderMaterial === false ) {
  46913. getProgramCacheKeyParameters( array, parameters );
  46914. getProgramCacheKeyBooleans( array, parameters );
  46915. array.push( renderer.outputColorSpace );
  46916. }
  46917. array.push( parameters.customProgramCacheKey );
  46918. return array.join();
  46919. }
  46920. function getProgramCacheKeyParameters( array, parameters ) {
  46921. array.push( parameters.precision );
  46922. array.push( parameters.outputColorSpace );
  46923. array.push( parameters.envMapMode );
  46924. array.push( parameters.envMapCubeUVHeight );
  46925. array.push( parameters.mapUv );
  46926. array.push( parameters.alphaMapUv );
  46927. array.push( parameters.lightMapUv );
  46928. array.push( parameters.aoMapUv );
  46929. array.push( parameters.bumpMapUv );
  46930. array.push( parameters.normalMapUv );
  46931. array.push( parameters.displacementMapUv );
  46932. array.push( parameters.emissiveMapUv );
  46933. array.push( parameters.metalnessMapUv );
  46934. array.push( parameters.roughnessMapUv );
  46935. array.push( parameters.anisotropyMapUv );
  46936. array.push( parameters.clearcoatMapUv );
  46937. array.push( parameters.clearcoatNormalMapUv );
  46938. array.push( parameters.clearcoatRoughnessMapUv );
  46939. array.push( parameters.iridescenceMapUv );
  46940. array.push( parameters.iridescenceThicknessMapUv );
  46941. array.push( parameters.sheenColorMapUv );
  46942. array.push( parameters.sheenRoughnessMapUv );
  46943. array.push( parameters.specularMapUv );
  46944. array.push( parameters.specularColorMapUv );
  46945. array.push( parameters.specularIntensityMapUv );
  46946. array.push( parameters.transmissionMapUv );
  46947. array.push( parameters.thicknessMapUv );
  46948. array.push( parameters.combine );
  46949. array.push( parameters.fogExp2 );
  46950. array.push( parameters.sizeAttenuation );
  46951. array.push( parameters.morphTargetsCount );
  46952. array.push( parameters.morphAttributeCount );
  46953. array.push( parameters.numDirLights );
  46954. array.push( parameters.numPointLights );
  46955. array.push( parameters.numSpotLights );
  46956. array.push( parameters.numSpotLightMaps );
  46957. array.push( parameters.numHemiLights );
  46958. array.push( parameters.numRectAreaLights );
  46959. array.push( parameters.numDirLightShadows );
  46960. array.push( parameters.numPointLightShadows );
  46961. array.push( parameters.numSpotLightShadows );
  46962. array.push( parameters.numSpotLightShadowsWithMaps );
  46963. array.push( parameters.numLightProbes );
  46964. array.push( parameters.shadowMapType );
  46965. array.push( parameters.toneMapping );
  46966. array.push( parameters.numClippingPlanes );
  46967. array.push( parameters.numClipIntersection );
  46968. array.push( parameters.depthPacking );
  46969. }
  46970. function getProgramCacheKeyBooleans( array, parameters ) {
  46971. _programLayers.disableAll();
  46972. if ( parameters.supportsVertexTextures )
  46973. _programLayers.enable( 0 );
  46974. if ( parameters.instancing )
  46975. _programLayers.enable( 1 );
  46976. if ( parameters.instancingColor )
  46977. _programLayers.enable( 2 );
  46978. if ( parameters.instancingMorph )
  46979. _programLayers.enable( 3 );
  46980. if ( parameters.matcap )
  46981. _programLayers.enable( 4 );
  46982. if ( parameters.envMap )
  46983. _programLayers.enable( 5 );
  46984. if ( parameters.normalMapObjectSpace )
  46985. _programLayers.enable( 6 );
  46986. if ( parameters.normalMapTangentSpace )
  46987. _programLayers.enable( 7 );
  46988. if ( parameters.clearcoat )
  46989. _programLayers.enable( 8 );
  46990. if ( parameters.iridescence )
  46991. _programLayers.enable( 9 );
  46992. if ( parameters.alphaTest )
  46993. _programLayers.enable( 10 );
  46994. if ( parameters.vertexColors )
  46995. _programLayers.enable( 11 );
  46996. if ( parameters.vertexAlphas )
  46997. _programLayers.enable( 12 );
  46998. if ( parameters.vertexUv1s )
  46999. _programLayers.enable( 13 );
  47000. if ( parameters.vertexUv2s )
  47001. _programLayers.enable( 14 );
  47002. if ( parameters.vertexUv3s )
  47003. _programLayers.enable( 15 );
  47004. if ( parameters.vertexTangents )
  47005. _programLayers.enable( 16 );
  47006. if ( parameters.anisotropy )
  47007. _programLayers.enable( 17 );
  47008. if ( parameters.alphaHash )
  47009. _programLayers.enable( 18 );
  47010. if ( parameters.batching )
  47011. _programLayers.enable( 19 );
  47012. if ( parameters.dispersion )
  47013. _programLayers.enable( 20 );
  47014. if ( parameters.batchingColor )
  47015. _programLayers.enable( 21 );
  47016. if ( parameters.gradientMap )
  47017. _programLayers.enable( 22 );
  47018. array.push( _programLayers.mask );
  47019. _programLayers.disableAll();
  47020. if ( parameters.fog )
  47021. _programLayers.enable( 0 );
  47022. if ( parameters.useFog )
  47023. _programLayers.enable( 1 );
  47024. if ( parameters.flatShading )
  47025. _programLayers.enable( 2 );
  47026. if ( parameters.logarithmicDepthBuffer )
  47027. _programLayers.enable( 3 );
  47028. if ( parameters.reversedDepthBuffer )
  47029. _programLayers.enable( 4 );
  47030. if ( parameters.skinning )
  47031. _programLayers.enable( 5 );
  47032. if ( parameters.morphTargets )
  47033. _programLayers.enable( 6 );
  47034. if ( parameters.morphNormals )
  47035. _programLayers.enable( 7 );
  47036. if ( parameters.morphColors )
  47037. _programLayers.enable( 8 );
  47038. if ( parameters.premultipliedAlpha )
  47039. _programLayers.enable( 9 );
  47040. if ( parameters.shadowMapEnabled )
  47041. _programLayers.enable( 10 );
  47042. if ( parameters.doubleSided )
  47043. _programLayers.enable( 11 );
  47044. if ( parameters.flipSided )
  47045. _programLayers.enable( 12 );
  47046. if ( parameters.useDepthPacking )
  47047. _programLayers.enable( 13 );
  47048. if ( parameters.dithering )
  47049. _programLayers.enable( 14 );
  47050. if ( parameters.transmission )
  47051. _programLayers.enable( 15 );
  47052. if ( parameters.sheen )
  47053. _programLayers.enable( 16 );
  47054. if ( parameters.opaque )
  47055. _programLayers.enable( 17 );
  47056. if ( parameters.pointsUvs )
  47057. _programLayers.enable( 18 );
  47058. if ( parameters.decodeVideoTexture )
  47059. _programLayers.enable( 19 );
  47060. if ( parameters.decodeVideoTextureEmissive )
  47061. _programLayers.enable( 20 );
  47062. if ( parameters.alphaToCoverage )
  47063. _programLayers.enable( 21 );
  47064. array.push( _programLayers.mask );
  47065. }
  47066. function getUniforms( material ) {
  47067. const shaderID = shaderIDs[ material.type ];
  47068. let uniforms;
  47069. if ( shaderID ) {
  47070. const shader = ShaderLib[ shaderID ];
  47071. uniforms = UniformsUtils.clone( shader.uniforms );
  47072. } else {
  47073. uniforms = material.uniforms;
  47074. }
  47075. return uniforms;
  47076. }
  47077. function acquireProgram( parameters, cacheKey ) {
  47078. let program;
  47079. // Check if code has been already compiled
  47080. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  47081. const preexistingProgram = programs[ p ];
  47082. if ( preexistingProgram.cacheKey === cacheKey ) {
  47083. program = preexistingProgram;
  47084. ++ program.usedTimes;
  47085. break;
  47086. }
  47087. }
  47088. if ( program === undefined ) {
  47089. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47090. programs.push( program );
  47091. }
  47092. return program;
  47093. }
  47094. function releaseProgram( program ) {
  47095. if ( -- program.usedTimes === 0 ) {
  47096. // Remove from unordered set
  47097. const i = programs.indexOf( program );
  47098. programs[ i ] = programs[ programs.length - 1 ];
  47099. programs.pop();
  47100. // Free WebGL resources
  47101. program.destroy();
  47102. }
  47103. }
  47104. function releaseShaderCache( material ) {
  47105. _customShaders.remove( material );
  47106. }
  47107. function dispose() {
  47108. _customShaders.dispose();
  47109. }
  47110. return {
  47111. getParameters: getParameters,
  47112. getProgramCacheKey: getProgramCacheKey,
  47113. getUniforms: getUniforms,
  47114. acquireProgram: acquireProgram,
  47115. releaseProgram: releaseProgram,
  47116. releaseShaderCache: releaseShaderCache,
  47117. // Exposed for resource monitoring & error feedback via renderer.info:
  47118. programs: programs,
  47119. dispose: dispose
  47120. };
  47121. }
  47122. function WebGLProperties() {
  47123. let properties = new WeakMap();
  47124. function has( object ) {
  47125. return properties.has( object );
  47126. }
  47127. function get( object ) {
  47128. let map = properties.get( object );
  47129. if ( map === undefined ) {
  47130. map = {};
  47131. properties.set( object, map );
  47132. }
  47133. return map;
  47134. }
  47135. function remove( object ) {
  47136. properties.delete( object );
  47137. }
  47138. function update( object, key, value ) {
  47139. properties.get( object )[ key ] = value;
  47140. }
  47141. function dispose() {
  47142. properties = new WeakMap();
  47143. }
  47144. return {
  47145. has: has,
  47146. get: get,
  47147. remove: remove,
  47148. update: update,
  47149. dispose: dispose
  47150. };
  47151. }
  47152. function painterSortStable( a, b ) {
  47153. if ( a.groupOrder !== b.groupOrder ) {
  47154. return a.groupOrder - b.groupOrder;
  47155. } else if ( a.renderOrder !== b.renderOrder ) {
  47156. return a.renderOrder - b.renderOrder;
  47157. } else if ( a.material.id !== b.material.id ) {
  47158. return a.material.id - b.material.id;
  47159. } else if ( a.z !== b.z ) {
  47160. return a.z - b.z;
  47161. } else {
  47162. return a.id - b.id;
  47163. }
  47164. }
  47165. function reversePainterSortStable( a, b ) {
  47166. if ( a.groupOrder !== b.groupOrder ) {
  47167. return a.groupOrder - b.groupOrder;
  47168. } else if ( a.renderOrder !== b.renderOrder ) {
  47169. return a.renderOrder - b.renderOrder;
  47170. } else if ( a.z !== b.z ) {
  47171. return b.z - a.z;
  47172. } else {
  47173. return a.id - b.id;
  47174. }
  47175. }
  47176. function WebGLRenderList() {
  47177. const renderItems = [];
  47178. let renderItemsIndex = 0;
  47179. const opaque = [];
  47180. const transmissive = [];
  47181. const transparent = [];
  47182. function init() {
  47183. renderItemsIndex = 0;
  47184. opaque.length = 0;
  47185. transmissive.length = 0;
  47186. transparent.length = 0;
  47187. }
  47188. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47189. let renderItem = renderItems[ renderItemsIndex ];
  47190. if ( renderItem === undefined ) {
  47191. renderItem = {
  47192. id: object.id,
  47193. object: object,
  47194. geometry: geometry,
  47195. material: material,
  47196. groupOrder: groupOrder,
  47197. renderOrder: object.renderOrder,
  47198. z: z,
  47199. group: group
  47200. };
  47201. renderItems[ renderItemsIndex ] = renderItem;
  47202. } else {
  47203. renderItem.id = object.id;
  47204. renderItem.object = object;
  47205. renderItem.geometry = geometry;
  47206. renderItem.material = material;
  47207. renderItem.groupOrder = groupOrder;
  47208. renderItem.renderOrder = object.renderOrder;
  47209. renderItem.z = z;
  47210. renderItem.group = group;
  47211. }
  47212. renderItemsIndex ++;
  47213. return renderItem;
  47214. }
  47215. function push( object, geometry, material, groupOrder, z, group ) {
  47216. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47217. if ( material.transmission > 0.0 ) {
  47218. transmissive.push( renderItem );
  47219. } else if ( material.transparent === true ) {
  47220. transparent.push( renderItem );
  47221. } else {
  47222. opaque.push( renderItem );
  47223. }
  47224. }
  47225. function unshift( object, geometry, material, groupOrder, z, group ) {
  47226. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47227. if ( material.transmission > 0.0 ) {
  47228. transmissive.unshift( renderItem );
  47229. } else if ( material.transparent === true ) {
  47230. transparent.unshift( renderItem );
  47231. } else {
  47232. opaque.unshift( renderItem );
  47233. }
  47234. }
  47235. function sort( customOpaqueSort, customTransparentSort ) {
  47236. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47237. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47238. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47239. }
  47240. function finish() {
  47241. // Clear references from inactive renderItems in the list
  47242. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47243. const renderItem = renderItems[ i ];
  47244. if ( renderItem.id === null ) break;
  47245. renderItem.id = null;
  47246. renderItem.object = null;
  47247. renderItem.geometry = null;
  47248. renderItem.material = null;
  47249. renderItem.group = null;
  47250. }
  47251. }
  47252. return {
  47253. opaque: opaque,
  47254. transmissive: transmissive,
  47255. transparent: transparent,
  47256. init: init,
  47257. push: push,
  47258. unshift: unshift,
  47259. finish: finish,
  47260. sort: sort
  47261. };
  47262. }
  47263. function WebGLRenderLists() {
  47264. let lists = new WeakMap();
  47265. function get( scene, renderCallDepth ) {
  47266. const listArray = lists.get( scene );
  47267. let list;
  47268. if ( listArray === undefined ) {
  47269. list = new WebGLRenderList();
  47270. lists.set( scene, [ list ] );
  47271. } else {
  47272. if ( renderCallDepth >= listArray.length ) {
  47273. list = new WebGLRenderList();
  47274. listArray.push( list );
  47275. } else {
  47276. list = listArray[ renderCallDepth ];
  47277. }
  47278. }
  47279. return list;
  47280. }
  47281. function dispose() {
  47282. lists = new WeakMap();
  47283. }
  47284. return {
  47285. get: get,
  47286. dispose: dispose
  47287. };
  47288. }
  47289. function UniformsCache() {
  47290. const lights = {};
  47291. return {
  47292. get: function ( light ) {
  47293. if ( lights[ light.id ] !== undefined ) {
  47294. return lights[ light.id ];
  47295. }
  47296. let uniforms;
  47297. switch ( light.type ) {
  47298. case 'DirectionalLight':
  47299. uniforms = {
  47300. direction: new Vector3(),
  47301. color: new Color()
  47302. };
  47303. break;
  47304. case 'SpotLight':
  47305. uniforms = {
  47306. position: new Vector3(),
  47307. direction: new Vector3(),
  47308. color: new Color(),
  47309. distance: 0,
  47310. coneCos: 0,
  47311. penumbraCos: 0,
  47312. decay: 0
  47313. };
  47314. break;
  47315. case 'PointLight':
  47316. uniforms = {
  47317. position: new Vector3(),
  47318. color: new Color(),
  47319. distance: 0,
  47320. decay: 0
  47321. };
  47322. break;
  47323. case 'HemisphereLight':
  47324. uniforms = {
  47325. direction: new Vector3(),
  47326. skyColor: new Color(),
  47327. groundColor: new Color()
  47328. };
  47329. break;
  47330. case 'RectAreaLight':
  47331. uniforms = {
  47332. color: new Color(),
  47333. position: new Vector3(),
  47334. halfWidth: new Vector3(),
  47335. halfHeight: new Vector3()
  47336. };
  47337. break;
  47338. }
  47339. lights[ light.id ] = uniforms;
  47340. return uniforms;
  47341. }
  47342. };
  47343. }
  47344. function ShadowUniformsCache() {
  47345. const lights = {};
  47346. return {
  47347. get: function ( light ) {
  47348. if ( lights[ light.id ] !== undefined ) {
  47349. return lights[ light.id ];
  47350. }
  47351. let uniforms;
  47352. switch ( light.type ) {
  47353. case 'DirectionalLight':
  47354. uniforms = {
  47355. shadowIntensity: 1,
  47356. shadowBias: 0,
  47357. shadowNormalBias: 0,
  47358. shadowRadius: 1,
  47359. shadowMapSize: new Vector2()
  47360. };
  47361. break;
  47362. case 'SpotLight':
  47363. uniforms = {
  47364. shadowIntensity: 1,
  47365. shadowBias: 0,
  47366. shadowNormalBias: 0,
  47367. shadowRadius: 1,
  47368. shadowMapSize: new Vector2()
  47369. };
  47370. break;
  47371. case 'PointLight':
  47372. uniforms = {
  47373. shadowIntensity: 1,
  47374. shadowBias: 0,
  47375. shadowNormalBias: 0,
  47376. shadowRadius: 1,
  47377. shadowMapSize: new Vector2(),
  47378. shadowCameraNear: 1,
  47379. shadowCameraFar: 1000
  47380. };
  47381. break;
  47382. // TODO (abelnation): set RectAreaLight shadow uniforms
  47383. }
  47384. lights[ light.id ] = uniforms;
  47385. return uniforms;
  47386. }
  47387. };
  47388. }
  47389. let nextVersion = 0;
  47390. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  47391. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  47392. }
  47393. function WebGLLights( extensions ) {
  47394. const cache = new UniformsCache();
  47395. const shadowCache = ShadowUniformsCache();
  47396. const state = {
  47397. version: 0,
  47398. hash: {
  47399. directionalLength: -1,
  47400. pointLength: -1,
  47401. spotLength: -1,
  47402. rectAreaLength: -1,
  47403. hemiLength: -1,
  47404. numDirectionalShadows: -1,
  47405. numPointShadows: -1,
  47406. numSpotShadows: -1,
  47407. numSpotMaps: -1,
  47408. numLightProbes: -1
  47409. },
  47410. ambient: [ 0, 0, 0 ],
  47411. probe: [],
  47412. directional: [],
  47413. directionalShadow: [],
  47414. directionalShadowMap: [],
  47415. directionalShadowMatrix: [],
  47416. spot: [],
  47417. spotLightMap: [],
  47418. spotShadow: [],
  47419. spotShadowMap: [],
  47420. spotLightMatrix: [],
  47421. rectArea: [],
  47422. rectAreaLTC1: null,
  47423. rectAreaLTC2: null,
  47424. point: [],
  47425. pointShadow: [],
  47426. pointShadowMap: [],
  47427. pointShadowMatrix: [],
  47428. hemi: [],
  47429. numSpotLightShadowsWithMaps: 0,
  47430. numLightProbes: 0
  47431. };
  47432. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  47433. const vector3 = new Vector3();
  47434. const matrix4 = new Matrix4();
  47435. const matrix42 = new Matrix4();
  47436. function setup( lights ) {
  47437. let r = 0, g = 0, b = 0;
  47438. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  47439. let directionalLength = 0;
  47440. let pointLength = 0;
  47441. let spotLength = 0;
  47442. let rectAreaLength = 0;
  47443. let hemiLength = 0;
  47444. let numDirectionalShadows = 0;
  47445. let numPointShadows = 0;
  47446. let numSpotShadows = 0;
  47447. let numSpotMaps = 0;
  47448. let numSpotShadowsWithMaps = 0;
  47449. let numLightProbes = 0;
  47450. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  47451. lights.sort( shadowCastingAndTexturingLightsFirst );
  47452. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47453. const light = lights[ i ];
  47454. const color = light.color;
  47455. const intensity = light.intensity;
  47456. const distance = light.distance;
  47457. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  47458. if ( light.isAmbientLight ) {
  47459. r += color.r * intensity;
  47460. g += color.g * intensity;
  47461. b += color.b * intensity;
  47462. } else if ( light.isLightProbe ) {
  47463. for ( let j = 0; j < 9; j ++ ) {
  47464. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  47465. }
  47466. numLightProbes ++;
  47467. } else if ( light.isDirectionalLight ) {
  47468. const uniforms = cache.get( light );
  47469. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47470. if ( light.castShadow ) {
  47471. const shadow = light.shadow;
  47472. const shadowUniforms = shadowCache.get( light );
  47473. shadowUniforms.shadowIntensity = shadow.intensity;
  47474. shadowUniforms.shadowBias = shadow.bias;
  47475. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47476. shadowUniforms.shadowRadius = shadow.radius;
  47477. shadowUniforms.shadowMapSize = shadow.mapSize;
  47478. state.directionalShadow[ directionalLength ] = shadowUniforms;
  47479. state.directionalShadowMap[ directionalLength ] = shadowMap;
  47480. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  47481. numDirectionalShadows ++;
  47482. }
  47483. state.directional[ directionalLength ] = uniforms;
  47484. directionalLength ++;
  47485. } else if ( light.isSpotLight ) {
  47486. const uniforms = cache.get( light );
  47487. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47488. uniforms.color.copy( color ).multiplyScalar( intensity );
  47489. uniforms.distance = distance;
  47490. uniforms.coneCos = Math.cos( light.angle );
  47491. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  47492. uniforms.decay = light.decay;
  47493. state.spot[ spotLength ] = uniforms;
  47494. const shadow = light.shadow;
  47495. if ( light.map ) {
  47496. state.spotLightMap[ numSpotMaps ] = light.map;
  47497. numSpotMaps ++;
  47498. // make sure the lightMatrix is up to date
  47499. // TODO : do it if required only
  47500. shadow.updateMatrices( light );
  47501. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  47502. }
  47503. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  47504. if ( light.castShadow ) {
  47505. const shadowUniforms = shadowCache.get( light );
  47506. shadowUniforms.shadowIntensity = shadow.intensity;
  47507. shadowUniforms.shadowBias = shadow.bias;
  47508. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47509. shadowUniforms.shadowRadius = shadow.radius;
  47510. shadowUniforms.shadowMapSize = shadow.mapSize;
  47511. state.spotShadow[ spotLength ] = shadowUniforms;
  47512. state.spotShadowMap[ spotLength ] = shadowMap;
  47513. numSpotShadows ++;
  47514. }
  47515. spotLength ++;
  47516. } else if ( light.isRectAreaLight ) {
  47517. const uniforms = cache.get( light );
  47518. uniforms.color.copy( color ).multiplyScalar( intensity );
  47519. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47520. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47521. state.rectArea[ rectAreaLength ] = uniforms;
  47522. rectAreaLength ++;
  47523. } else if ( light.isPointLight ) {
  47524. const uniforms = cache.get( light );
  47525. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47526. uniforms.distance = light.distance;
  47527. uniforms.decay = light.decay;
  47528. if ( light.castShadow ) {
  47529. const shadow = light.shadow;
  47530. const shadowUniforms = shadowCache.get( light );
  47531. shadowUniforms.shadowIntensity = shadow.intensity;
  47532. shadowUniforms.shadowBias = shadow.bias;
  47533. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47534. shadowUniforms.shadowRadius = shadow.radius;
  47535. shadowUniforms.shadowMapSize = shadow.mapSize;
  47536. shadowUniforms.shadowCameraNear = shadow.camera.near;
  47537. shadowUniforms.shadowCameraFar = shadow.camera.far;
  47538. state.pointShadow[ pointLength ] = shadowUniforms;
  47539. state.pointShadowMap[ pointLength ] = shadowMap;
  47540. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  47541. numPointShadows ++;
  47542. }
  47543. state.point[ pointLength ] = uniforms;
  47544. pointLength ++;
  47545. } else if ( light.isHemisphereLight ) {
  47546. const uniforms = cache.get( light );
  47547. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  47548. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  47549. state.hemi[ hemiLength ] = uniforms;
  47550. hemiLength ++;
  47551. }
  47552. }
  47553. if ( rectAreaLength > 0 ) {
  47554. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  47555. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  47556. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  47557. } else {
  47558. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  47559. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  47560. }
  47561. }
  47562. state.ambient[ 0 ] = r;
  47563. state.ambient[ 1 ] = g;
  47564. state.ambient[ 2 ] = b;
  47565. const hash = state.hash;
  47566. if ( hash.directionalLength !== directionalLength ||
  47567. hash.pointLength !== pointLength ||
  47568. hash.spotLength !== spotLength ||
  47569. hash.rectAreaLength !== rectAreaLength ||
  47570. hash.hemiLength !== hemiLength ||
  47571. hash.numDirectionalShadows !== numDirectionalShadows ||
  47572. hash.numPointShadows !== numPointShadows ||
  47573. hash.numSpotShadows !== numSpotShadows ||
  47574. hash.numSpotMaps !== numSpotMaps ||
  47575. hash.numLightProbes !== numLightProbes ) {
  47576. state.directional.length = directionalLength;
  47577. state.spot.length = spotLength;
  47578. state.rectArea.length = rectAreaLength;
  47579. state.point.length = pointLength;
  47580. state.hemi.length = hemiLength;
  47581. state.directionalShadow.length = numDirectionalShadows;
  47582. state.directionalShadowMap.length = numDirectionalShadows;
  47583. state.pointShadow.length = numPointShadows;
  47584. state.pointShadowMap.length = numPointShadows;
  47585. state.spotShadow.length = numSpotShadows;
  47586. state.spotShadowMap.length = numSpotShadows;
  47587. state.directionalShadowMatrix.length = numDirectionalShadows;
  47588. state.pointShadowMatrix.length = numPointShadows;
  47589. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  47590. state.spotLightMap.length = numSpotMaps;
  47591. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  47592. state.numLightProbes = numLightProbes;
  47593. hash.directionalLength = directionalLength;
  47594. hash.pointLength = pointLength;
  47595. hash.spotLength = spotLength;
  47596. hash.rectAreaLength = rectAreaLength;
  47597. hash.hemiLength = hemiLength;
  47598. hash.numDirectionalShadows = numDirectionalShadows;
  47599. hash.numPointShadows = numPointShadows;
  47600. hash.numSpotShadows = numSpotShadows;
  47601. hash.numSpotMaps = numSpotMaps;
  47602. hash.numLightProbes = numLightProbes;
  47603. state.version = nextVersion ++;
  47604. }
  47605. }
  47606. function setupView( lights, camera ) {
  47607. let directionalLength = 0;
  47608. let pointLength = 0;
  47609. let spotLength = 0;
  47610. let rectAreaLength = 0;
  47611. let hemiLength = 0;
  47612. const viewMatrix = camera.matrixWorldInverse;
  47613. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47614. const light = lights[ i ];
  47615. if ( light.isDirectionalLight ) {
  47616. const uniforms = state.directional[ directionalLength ];
  47617. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47618. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47619. uniforms.direction.sub( vector3 );
  47620. uniforms.direction.transformDirection( viewMatrix );
  47621. directionalLength ++;
  47622. } else if ( light.isSpotLight ) {
  47623. const uniforms = state.spot[ spotLength ];
  47624. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47625. uniforms.position.applyMatrix4( viewMatrix );
  47626. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47627. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47628. uniforms.direction.sub( vector3 );
  47629. uniforms.direction.transformDirection( viewMatrix );
  47630. spotLength ++;
  47631. } else if ( light.isRectAreaLight ) {
  47632. const uniforms = state.rectArea[ rectAreaLength ];
  47633. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47634. uniforms.position.applyMatrix4( viewMatrix );
  47635. // extract local rotation of light to derive width/height half vectors
  47636. matrix42.identity();
  47637. matrix4.copy( light.matrixWorld );
  47638. matrix4.premultiply( viewMatrix );
  47639. matrix42.extractRotation( matrix4 );
  47640. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47641. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47642. uniforms.halfWidth.applyMatrix4( matrix42 );
  47643. uniforms.halfHeight.applyMatrix4( matrix42 );
  47644. rectAreaLength ++;
  47645. } else if ( light.isPointLight ) {
  47646. const uniforms = state.point[ pointLength ];
  47647. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47648. uniforms.position.applyMatrix4( viewMatrix );
  47649. pointLength ++;
  47650. } else if ( light.isHemisphereLight ) {
  47651. const uniforms = state.hemi[ hemiLength ];
  47652. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47653. uniforms.direction.transformDirection( viewMatrix );
  47654. hemiLength ++;
  47655. }
  47656. }
  47657. }
  47658. return {
  47659. setup: setup,
  47660. setupView: setupView,
  47661. state: state
  47662. };
  47663. }
  47664. function WebGLRenderState( extensions ) {
  47665. const lights = new WebGLLights( extensions );
  47666. const lightsArray = [];
  47667. const shadowsArray = [];
  47668. function init( camera ) {
  47669. state.camera = camera;
  47670. lightsArray.length = 0;
  47671. shadowsArray.length = 0;
  47672. }
  47673. function pushLight( light ) {
  47674. lightsArray.push( light );
  47675. }
  47676. function pushShadow( shadowLight ) {
  47677. shadowsArray.push( shadowLight );
  47678. }
  47679. function setupLights() {
  47680. lights.setup( lightsArray );
  47681. }
  47682. function setupLightsView( camera ) {
  47683. lights.setupView( lightsArray, camera );
  47684. }
  47685. const state = {
  47686. lightsArray: lightsArray,
  47687. shadowsArray: shadowsArray,
  47688. camera: null,
  47689. lights: lights,
  47690. transmissionRenderTarget: {}
  47691. };
  47692. return {
  47693. init: init,
  47694. state: state,
  47695. setupLights: setupLights,
  47696. setupLightsView: setupLightsView,
  47697. pushLight: pushLight,
  47698. pushShadow: pushShadow
  47699. };
  47700. }
  47701. function WebGLRenderStates( extensions ) {
  47702. let renderStates = new WeakMap();
  47703. function get( scene, renderCallDepth = 0 ) {
  47704. const renderStateArray = renderStates.get( scene );
  47705. let renderState;
  47706. if ( renderStateArray === undefined ) {
  47707. renderState = new WebGLRenderState( extensions );
  47708. renderStates.set( scene, [ renderState ] );
  47709. } else {
  47710. if ( renderCallDepth >= renderStateArray.length ) {
  47711. renderState = new WebGLRenderState( extensions );
  47712. renderStateArray.push( renderState );
  47713. } else {
  47714. renderState = renderStateArray[ renderCallDepth ];
  47715. }
  47716. }
  47717. return renderState;
  47718. }
  47719. function dispose() {
  47720. renderStates = new WeakMap();
  47721. }
  47722. return {
  47723. get: get,
  47724. dispose: dispose
  47725. };
  47726. }
  47727. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  47728. 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}";
  47729. function WebGLShadowMap( renderer, objects, capabilities ) {
  47730. let _frustum = new Frustum();
  47731. const _shadowMapSize = new Vector2(),
  47732. _viewportSize = new Vector2(),
  47733. _viewport = new Vector4(),
  47734. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  47735. _distanceMaterial = new MeshDistanceMaterial(),
  47736. _materialCache = {},
  47737. _maxTextureSize = capabilities.maxTextureSize;
  47738. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  47739. const shadowMaterialVertical = new ShaderMaterial( {
  47740. defines: {
  47741. VSM_SAMPLES: 8
  47742. },
  47743. uniforms: {
  47744. shadow_pass: { value: null },
  47745. resolution: { value: new Vector2() },
  47746. radius: { value: 4.0 }
  47747. },
  47748. vertexShader: vertex,
  47749. fragmentShader: fragment
  47750. } );
  47751. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  47752. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  47753. const fullScreenTri = new BufferGeometry();
  47754. fullScreenTri.setAttribute(
  47755. 'position',
  47756. new BufferAttribute(
  47757. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  47758. 3
  47759. )
  47760. );
  47761. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  47762. const scope = this;
  47763. this.enabled = false;
  47764. this.autoUpdate = true;
  47765. this.needsUpdate = false;
  47766. this.type = PCFShadowMap;
  47767. let _previousType = this.type;
  47768. this.render = function ( lights, scene, camera ) {
  47769. if ( scope.enabled === false ) return;
  47770. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  47771. if ( lights.length === 0 ) return;
  47772. const currentRenderTarget = renderer.getRenderTarget();
  47773. const activeCubeFace = renderer.getActiveCubeFace();
  47774. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  47775. const _state = renderer.state;
  47776. // Set GL state for depth map.
  47777. _state.setBlending( NoBlending );
  47778. if ( _state.buffers.depth.getReversed() ) {
  47779. _state.buffers.color.setClear( 0, 0, 0, 0 );
  47780. } else {
  47781. _state.buffers.color.setClear( 1, 1, 1, 1 );
  47782. }
  47783. _state.buffers.depth.setTest( true );
  47784. _state.setScissorTest( false );
  47785. // check for shadow map type changes
  47786. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  47787. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  47788. // render depth map
  47789. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  47790. const light = lights[ i ];
  47791. const shadow = light.shadow;
  47792. if ( shadow === undefined ) {
  47793. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  47794. continue;
  47795. }
  47796. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  47797. _shadowMapSize.copy( shadow.mapSize );
  47798. const shadowFrameExtents = shadow.getFrameExtents();
  47799. _shadowMapSize.multiply( shadowFrameExtents );
  47800. _viewportSize.copy( shadow.mapSize );
  47801. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  47802. if ( _shadowMapSize.x > _maxTextureSize ) {
  47803. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  47804. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  47805. shadow.mapSize.x = _viewportSize.x;
  47806. }
  47807. if ( _shadowMapSize.y > _maxTextureSize ) {
  47808. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  47809. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  47810. shadow.mapSize.y = _viewportSize.y;
  47811. }
  47812. }
  47813. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  47814. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  47815. if ( shadow.map !== null ) {
  47816. shadow.map.dispose();
  47817. }
  47818. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  47819. shadow.map.texture.name = light.name + '.shadowMap';
  47820. shadow.camera.updateProjectionMatrix();
  47821. }
  47822. renderer.setRenderTarget( shadow.map );
  47823. renderer.clear();
  47824. const viewportCount = shadow.getViewportCount();
  47825. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  47826. const viewport = shadow.getViewport( vp );
  47827. _viewport.set(
  47828. _viewportSize.x * viewport.x,
  47829. _viewportSize.y * viewport.y,
  47830. _viewportSize.x * viewport.z,
  47831. _viewportSize.y * viewport.w
  47832. );
  47833. _state.viewport( _viewport );
  47834. shadow.updateMatrices( light, vp );
  47835. _frustum = shadow.getFrustum();
  47836. renderObject( scene, camera, shadow.camera, light, this.type );
  47837. }
  47838. // do blur pass for VSM
  47839. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  47840. VSMPass( shadow, camera );
  47841. }
  47842. shadow.needsUpdate = false;
  47843. }
  47844. _previousType = this.type;
  47845. scope.needsUpdate = false;
  47846. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  47847. };
  47848. function VSMPass( shadow, camera ) {
  47849. const geometry = objects.update( fullScreenMesh );
  47850. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  47851. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  47852. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  47853. shadowMaterialVertical.needsUpdate = true;
  47854. shadowMaterialHorizontal.needsUpdate = true;
  47855. }
  47856. if ( shadow.mapPass === null ) {
  47857. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  47858. }
  47859. // vertical pass
  47860. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  47861. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  47862. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  47863. renderer.setRenderTarget( shadow.mapPass );
  47864. renderer.clear();
  47865. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  47866. // horizontal pass
  47867. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  47868. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  47869. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  47870. renderer.setRenderTarget( shadow.map );
  47871. renderer.clear();
  47872. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  47873. }
  47874. function getDepthMaterial( object, material, light, type ) {
  47875. let result = null;
  47876. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  47877. if ( customMaterial !== undefined ) {
  47878. result = customMaterial;
  47879. } else {
  47880. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  47881. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  47882. ( material.displacementMap && material.displacementScale !== 0 ) ||
  47883. ( material.alphaMap && material.alphaTest > 0 ) ||
  47884. ( material.map && material.alphaTest > 0 ) ||
  47885. ( material.alphaToCoverage === true ) ) {
  47886. // in this case we need a unique material instance reflecting the
  47887. // appropriate state
  47888. const keyA = result.uuid, keyB = material.uuid;
  47889. let materialsForVariant = _materialCache[ keyA ];
  47890. if ( materialsForVariant === undefined ) {
  47891. materialsForVariant = {};
  47892. _materialCache[ keyA ] = materialsForVariant;
  47893. }
  47894. let cachedMaterial = materialsForVariant[ keyB ];
  47895. if ( cachedMaterial === undefined ) {
  47896. cachedMaterial = result.clone();
  47897. materialsForVariant[ keyB ] = cachedMaterial;
  47898. material.addEventListener( 'dispose', onMaterialDispose );
  47899. }
  47900. result = cachedMaterial;
  47901. }
  47902. }
  47903. result.visible = material.visible;
  47904. result.wireframe = material.wireframe;
  47905. if ( type === VSMShadowMap ) {
  47906. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  47907. } else {
  47908. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  47909. }
  47910. result.alphaMap = material.alphaMap;
  47911. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  47912. result.map = material.map;
  47913. result.clipShadows = material.clipShadows;
  47914. result.clippingPlanes = material.clippingPlanes;
  47915. result.clipIntersection = material.clipIntersection;
  47916. result.displacementMap = material.displacementMap;
  47917. result.displacementScale = material.displacementScale;
  47918. result.displacementBias = material.displacementBias;
  47919. result.wireframeLinewidth = material.wireframeLinewidth;
  47920. result.linewidth = material.linewidth;
  47921. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  47922. const materialProperties = renderer.properties.get( result );
  47923. materialProperties.light = light;
  47924. }
  47925. return result;
  47926. }
  47927. function renderObject( object, camera, shadowCamera, light, type ) {
  47928. if ( object.visible === false ) return;
  47929. const visible = object.layers.test( camera.layers );
  47930. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  47931. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  47932. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  47933. const geometry = objects.update( object );
  47934. const material = object.material;
  47935. if ( Array.isArray( material ) ) {
  47936. const groups = geometry.groups;
  47937. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  47938. const group = groups[ k ];
  47939. const groupMaterial = material[ group.materialIndex ];
  47940. if ( groupMaterial && groupMaterial.visible ) {
  47941. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  47942. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  47943. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  47944. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  47945. }
  47946. }
  47947. } else if ( material.visible ) {
  47948. const depthMaterial = getDepthMaterial( object, material, light, type );
  47949. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  47950. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  47951. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  47952. }
  47953. }
  47954. }
  47955. const children = object.children;
  47956. for ( let i = 0, l = children.length; i < l; i ++ ) {
  47957. renderObject( children[ i ], camera, shadowCamera, light, type );
  47958. }
  47959. }
  47960. function onMaterialDispose( event ) {
  47961. const material = event.target;
  47962. material.removeEventListener( 'dispose', onMaterialDispose );
  47963. // make sure to remove the unique distance/depth materials used for shadow map rendering
  47964. for ( const id in _materialCache ) {
  47965. const cache = _materialCache[ id ];
  47966. const uuid = event.target.uuid;
  47967. if ( uuid in cache ) {
  47968. const shadowMaterial = cache[ uuid ];
  47969. shadowMaterial.dispose();
  47970. delete cache[ uuid ];
  47971. }
  47972. }
  47973. }
  47974. }
  47975. const reversedFuncs = {
  47976. [ NeverDepth ]: AlwaysDepth,
  47977. [ LessDepth ]: GreaterDepth,
  47978. [ EqualDepth ]: NotEqualDepth,
  47979. [ LessEqualDepth ]: GreaterEqualDepth,
  47980. [ AlwaysDepth ]: NeverDepth,
  47981. [ GreaterDepth ]: LessDepth,
  47982. [ NotEqualDepth ]: EqualDepth,
  47983. [ GreaterEqualDepth ]: LessEqualDepth,
  47984. };
  47985. function WebGLState( gl, extensions ) {
  47986. function ColorBuffer() {
  47987. let locked = false;
  47988. const color = new Vector4();
  47989. let currentColorMask = null;
  47990. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  47991. return {
  47992. setMask: function ( colorMask ) {
  47993. if ( currentColorMask !== colorMask && ! locked ) {
  47994. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  47995. currentColorMask = colorMask;
  47996. }
  47997. },
  47998. setLocked: function ( lock ) {
  47999. locked = lock;
  48000. },
  48001. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48002. if ( premultipliedAlpha === true ) {
  48003. r *= a; g *= a; b *= a;
  48004. }
  48005. color.set( r, g, b, a );
  48006. if ( currentColorClear.equals( color ) === false ) {
  48007. gl.clearColor( r, g, b, a );
  48008. currentColorClear.copy( color );
  48009. }
  48010. },
  48011. reset: function () {
  48012. locked = false;
  48013. currentColorMask = null;
  48014. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48015. }
  48016. };
  48017. }
  48018. function DepthBuffer() {
  48019. let locked = false;
  48020. let currentReversed = false;
  48021. let currentDepthMask = null;
  48022. let currentDepthFunc = null;
  48023. let currentDepthClear = null;
  48024. return {
  48025. setReversed: function ( reversed ) {
  48026. if ( currentReversed !== reversed ) {
  48027. const ext = extensions.get( 'EXT_clip_control' );
  48028. if ( reversed ) {
  48029. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48030. } else {
  48031. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48032. }
  48033. currentReversed = reversed;
  48034. const oldDepth = currentDepthClear;
  48035. currentDepthClear = null;
  48036. this.setClear( oldDepth );
  48037. }
  48038. },
  48039. getReversed: function () {
  48040. return currentReversed;
  48041. },
  48042. setTest: function ( depthTest ) {
  48043. if ( depthTest ) {
  48044. enable( gl.DEPTH_TEST );
  48045. } else {
  48046. disable( gl.DEPTH_TEST );
  48047. }
  48048. },
  48049. setMask: function ( depthMask ) {
  48050. if ( currentDepthMask !== depthMask && ! locked ) {
  48051. gl.depthMask( depthMask );
  48052. currentDepthMask = depthMask;
  48053. }
  48054. },
  48055. setFunc: function ( depthFunc ) {
  48056. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48057. if ( currentDepthFunc !== depthFunc ) {
  48058. switch ( depthFunc ) {
  48059. case NeverDepth:
  48060. gl.depthFunc( gl.NEVER );
  48061. break;
  48062. case AlwaysDepth:
  48063. gl.depthFunc( gl.ALWAYS );
  48064. break;
  48065. case LessDepth:
  48066. gl.depthFunc( gl.LESS );
  48067. break;
  48068. case LessEqualDepth:
  48069. gl.depthFunc( gl.LEQUAL );
  48070. break;
  48071. case EqualDepth:
  48072. gl.depthFunc( gl.EQUAL );
  48073. break;
  48074. case GreaterEqualDepth:
  48075. gl.depthFunc( gl.GEQUAL );
  48076. break;
  48077. case GreaterDepth:
  48078. gl.depthFunc( gl.GREATER );
  48079. break;
  48080. case NotEqualDepth:
  48081. gl.depthFunc( gl.NOTEQUAL );
  48082. break;
  48083. default:
  48084. gl.depthFunc( gl.LEQUAL );
  48085. }
  48086. currentDepthFunc = depthFunc;
  48087. }
  48088. },
  48089. setLocked: function ( lock ) {
  48090. locked = lock;
  48091. },
  48092. setClear: function ( depth ) {
  48093. if ( currentDepthClear !== depth ) {
  48094. if ( currentReversed ) {
  48095. depth = 1 - depth;
  48096. }
  48097. gl.clearDepth( depth );
  48098. currentDepthClear = depth;
  48099. }
  48100. },
  48101. reset: function () {
  48102. locked = false;
  48103. currentDepthMask = null;
  48104. currentDepthFunc = null;
  48105. currentDepthClear = null;
  48106. currentReversed = false;
  48107. }
  48108. };
  48109. }
  48110. function StencilBuffer() {
  48111. let locked = false;
  48112. let currentStencilMask = null;
  48113. let currentStencilFunc = null;
  48114. let currentStencilRef = null;
  48115. let currentStencilFuncMask = null;
  48116. let currentStencilFail = null;
  48117. let currentStencilZFail = null;
  48118. let currentStencilZPass = null;
  48119. let currentStencilClear = null;
  48120. return {
  48121. setTest: function ( stencilTest ) {
  48122. if ( ! locked ) {
  48123. if ( stencilTest ) {
  48124. enable( gl.STENCIL_TEST );
  48125. } else {
  48126. disable( gl.STENCIL_TEST );
  48127. }
  48128. }
  48129. },
  48130. setMask: function ( stencilMask ) {
  48131. if ( currentStencilMask !== stencilMask && ! locked ) {
  48132. gl.stencilMask( stencilMask );
  48133. currentStencilMask = stencilMask;
  48134. }
  48135. },
  48136. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48137. if ( currentStencilFunc !== stencilFunc ||
  48138. currentStencilRef !== stencilRef ||
  48139. currentStencilFuncMask !== stencilMask ) {
  48140. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48141. currentStencilFunc = stencilFunc;
  48142. currentStencilRef = stencilRef;
  48143. currentStencilFuncMask = stencilMask;
  48144. }
  48145. },
  48146. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48147. if ( currentStencilFail !== stencilFail ||
  48148. currentStencilZFail !== stencilZFail ||
  48149. currentStencilZPass !== stencilZPass ) {
  48150. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48151. currentStencilFail = stencilFail;
  48152. currentStencilZFail = stencilZFail;
  48153. currentStencilZPass = stencilZPass;
  48154. }
  48155. },
  48156. setLocked: function ( lock ) {
  48157. locked = lock;
  48158. },
  48159. setClear: function ( stencil ) {
  48160. if ( currentStencilClear !== stencil ) {
  48161. gl.clearStencil( stencil );
  48162. currentStencilClear = stencil;
  48163. }
  48164. },
  48165. reset: function () {
  48166. locked = false;
  48167. currentStencilMask = null;
  48168. currentStencilFunc = null;
  48169. currentStencilRef = null;
  48170. currentStencilFuncMask = null;
  48171. currentStencilFail = null;
  48172. currentStencilZFail = null;
  48173. currentStencilZPass = null;
  48174. currentStencilClear = null;
  48175. }
  48176. };
  48177. }
  48178. //
  48179. const colorBuffer = new ColorBuffer();
  48180. const depthBuffer = new DepthBuffer();
  48181. const stencilBuffer = new StencilBuffer();
  48182. const uboBindings = new WeakMap();
  48183. const uboProgramMap = new WeakMap();
  48184. let enabledCapabilities = {};
  48185. let currentBoundFramebuffers = {};
  48186. let currentDrawbuffers = new WeakMap();
  48187. let defaultDrawbuffers = [];
  48188. let currentProgram = null;
  48189. let currentBlendingEnabled = false;
  48190. let currentBlending = null;
  48191. let currentBlendEquation = null;
  48192. let currentBlendSrc = null;
  48193. let currentBlendDst = null;
  48194. let currentBlendEquationAlpha = null;
  48195. let currentBlendSrcAlpha = null;
  48196. let currentBlendDstAlpha = null;
  48197. let currentBlendColor = new Color( 0, 0, 0 );
  48198. let currentBlendAlpha = 0;
  48199. let currentPremultipledAlpha = false;
  48200. let currentFlipSided = null;
  48201. let currentCullFace = null;
  48202. let currentLineWidth = null;
  48203. let currentPolygonOffsetFactor = null;
  48204. let currentPolygonOffsetUnits = null;
  48205. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48206. let lineWidthAvailable = false;
  48207. let version = 0;
  48208. const glVersion = gl.getParameter( gl.VERSION );
  48209. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48210. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48211. lineWidthAvailable = ( version >= 1.0 );
  48212. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48213. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48214. lineWidthAvailable = ( version >= 2.0 );
  48215. }
  48216. let currentTextureSlot = null;
  48217. let currentBoundTextures = {};
  48218. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48219. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48220. const currentScissor = new Vector4().fromArray( scissorParam );
  48221. const currentViewport = new Vector4().fromArray( viewportParam );
  48222. function createTexture( type, target, count, dimensions ) {
  48223. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48224. const texture = gl.createTexture();
  48225. gl.bindTexture( type, texture );
  48226. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48227. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48228. for ( let i = 0; i < count; i ++ ) {
  48229. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48230. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48231. } else {
  48232. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48233. }
  48234. }
  48235. return texture;
  48236. }
  48237. const emptyTextures = {};
  48238. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48239. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48240. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48241. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48242. // init
  48243. colorBuffer.setClear( 0, 0, 0, 1 );
  48244. depthBuffer.setClear( 1 );
  48245. stencilBuffer.setClear( 0 );
  48246. enable( gl.DEPTH_TEST );
  48247. depthBuffer.setFunc( LessEqualDepth );
  48248. setFlipSided( false );
  48249. setCullFace( CullFaceBack );
  48250. enable( gl.CULL_FACE );
  48251. setBlending( NoBlending );
  48252. //
  48253. function enable( id ) {
  48254. if ( enabledCapabilities[ id ] !== true ) {
  48255. gl.enable( id );
  48256. enabledCapabilities[ id ] = true;
  48257. }
  48258. }
  48259. function disable( id ) {
  48260. if ( enabledCapabilities[ id ] !== false ) {
  48261. gl.disable( id );
  48262. enabledCapabilities[ id ] = false;
  48263. }
  48264. }
  48265. function bindFramebuffer( target, framebuffer ) {
  48266. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48267. gl.bindFramebuffer( target, framebuffer );
  48268. currentBoundFramebuffers[ target ] = framebuffer;
  48269. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48270. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48271. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48272. }
  48273. if ( target === gl.FRAMEBUFFER ) {
  48274. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48275. }
  48276. return true;
  48277. }
  48278. return false;
  48279. }
  48280. function drawBuffers( renderTarget, framebuffer ) {
  48281. let drawBuffers = defaultDrawbuffers;
  48282. let needsUpdate = false;
  48283. if ( renderTarget ) {
  48284. drawBuffers = currentDrawbuffers.get( framebuffer );
  48285. if ( drawBuffers === undefined ) {
  48286. drawBuffers = [];
  48287. currentDrawbuffers.set( framebuffer, drawBuffers );
  48288. }
  48289. const textures = renderTarget.textures;
  48290. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48291. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48292. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48293. }
  48294. drawBuffers.length = textures.length;
  48295. needsUpdate = true;
  48296. }
  48297. } else {
  48298. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48299. drawBuffers[ 0 ] = gl.BACK;
  48300. needsUpdate = true;
  48301. }
  48302. }
  48303. if ( needsUpdate ) {
  48304. gl.drawBuffers( drawBuffers );
  48305. }
  48306. }
  48307. function useProgram( program ) {
  48308. if ( currentProgram !== program ) {
  48309. gl.useProgram( program );
  48310. currentProgram = program;
  48311. return true;
  48312. }
  48313. return false;
  48314. }
  48315. const equationToGL = {
  48316. [ AddEquation ]: gl.FUNC_ADD,
  48317. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48318. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48319. };
  48320. equationToGL[ MinEquation ] = gl.MIN;
  48321. equationToGL[ MaxEquation ] = gl.MAX;
  48322. const factorToGL = {
  48323. [ ZeroFactor ]: gl.ZERO,
  48324. [ OneFactor ]: gl.ONE,
  48325. [ SrcColorFactor ]: gl.SRC_COLOR,
  48326. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48327. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48328. [ DstColorFactor ]: gl.DST_COLOR,
  48329. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48330. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48331. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48332. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48333. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  48334. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  48335. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  48336. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  48337. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  48338. };
  48339. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  48340. if ( blending === NoBlending ) {
  48341. if ( currentBlendingEnabled === true ) {
  48342. disable( gl.BLEND );
  48343. currentBlendingEnabled = false;
  48344. }
  48345. return;
  48346. }
  48347. if ( currentBlendingEnabled === false ) {
  48348. enable( gl.BLEND );
  48349. currentBlendingEnabled = true;
  48350. }
  48351. if ( blending !== CustomBlending ) {
  48352. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  48353. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  48354. gl.blendEquation( gl.FUNC_ADD );
  48355. currentBlendEquation = AddEquation;
  48356. currentBlendEquationAlpha = AddEquation;
  48357. }
  48358. if ( premultipliedAlpha ) {
  48359. switch ( blending ) {
  48360. case NormalBlending:
  48361. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48362. break;
  48363. case AdditiveBlending:
  48364. gl.blendFunc( gl.ONE, gl.ONE );
  48365. break;
  48366. case SubtractiveBlending:
  48367. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48368. break;
  48369. case MultiplyBlending:
  48370. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48371. break;
  48372. default:
  48373. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  48374. break;
  48375. }
  48376. } else {
  48377. switch ( blending ) {
  48378. case NormalBlending:
  48379. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48380. break;
  48381. case AdditiveBlending:
  48382. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48383. break;
  48384. case SubtractiveBlending:
  48385. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48386. break;
  48387. case MultiplyBlending:
  48388. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48389. break;
  48390. default:
  48391. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  48392. break;
  48393. }
  48394. }
  48395. currentBlendSrc = null;
  48396. currentBlendDst = null;
  48397. currentBlendSrcAlpha = null;
  48398. currentBlendDstAlpha = null;
  48399. currentBlendColor.set( 0, 0, 0 );
  48400. currentBlendAlpha = 0;
  48401. currentBlending = blending;
  48402. currentPremultipledAlpha = premultipliedAlpha;
  48403. }
  48404. return;
  48405. }
  48406. // custom blending
  48407. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48408. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48409. blendDstAlpha = blendDstAlpha || blendDst;
  48410. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  48411. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48412. currentBlendEquation = blendEquation;
  48413. currentBlendEquationAlpha = blendEquationAlpha;
  48414. }
  48415. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  48416. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48417. currentBlendSrc = blendSrc;
  48418. currentBlendDst = blendDst;
  48419. currentBlendSrcAlpha = blendSrcAlpha;
  48420. currentBlendDstAlpha = blendDstAlpha;
  48421. }
  48422. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  48423. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  48424. currentBlendColor.copy( blendColor );
  48425. currentBlendAlpha = blendAlpha;
  48426. }
  48427. currentBlending = blending;
  48428. currentPremultipledAlpha = false;
  48429. }
  48430. function setMaterial( material, frontFaceCW ) {
  48431. material.side === DoubleSide
  48432. ? disable( gl.CULL_FACE )
  48433. : enable( gl.CULL_FACE );
  48434. let flipSided = ( material.side === BackSide );
  48435. if ( frontFaceCW ) flipSided = ! flipSided;
  48436. setFlipSided( flipSided );
  48437. ( material.blending === NormalBlending && material.transparent === false )
  48438. ? setBlending( NoBlending )
  48439. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  48440. depthBuffer.setFunc( material.depthFunc );
  48441. depthBuffer.setTest( material.depthTest );
  48442. depthBuffer.setMask( material.depthWrite );
  48443. colorBuffer.setMask( material.colorWrite );
  48444. const stencilWrite = material.stencilWrite;
  48445. stencilBuffer.setTest( stencilWrite );
  48446. if ( stencilWrite ) {
  48447. stencilBuffer.setMask( material.stencilWriteMask );
  48448. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48449. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48450. }
  48451. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48452. material.alphaToCoverage === true
  48453. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48454. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48455. }
  48456. //
  48457. function setFlipSided( flipSided ) {
  48458. if ( currentFlipSided !== flipSided ) {
  48459. if ( flipSided ) {
  48460. gl.frontFace( gl.CW );
  48461. } else {
  48462. gl.frontFace( gl.CCW );
  48463. }
  48464. currentFlipSided = flipSided;
  48465. }
  48466. }
  48467. function setCullFace( cullFace ) {
  48468. if ( cullFace !== CullFaceNone ) {
  48469. enable( gl.CULL_FACE );
  48470. if ( cullFace !== currentCullFace ) {
  48471. if ( cullFace === CullFaceBack ) {
  48472. gl.cullFace( gl.BACK );
  48473. } else if ( cullFace === CullFaceFront ) {
  48474. gl.cullFace( gl.FRONT );
  48475. } else {
  48476. gl.cullFace( gl.FRONT_AND_BACK );
  48477. }
  48478. }
  48479. } else {
  48480. disable( gl.CULL_FACE );
  48481. }
  48482. currentCullFace = cullFace;
  48483. }
  48484. function setLineWidth( width ) {
  48485. if ( width !== currentLineWidth ) {
  48486. if ( lineWidthAvailable ) gl.lineWidth( width );
  48487. currentLineWidth = width;
  48488. }
  48489. }
  48490. function setPolygonOffset( polygonOffset, factor, units ) {
  48491. if ( polygonOffset ) {
  48492. enable( gl.POLYGON_OFFSET_FILL );
  48493. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  48494. gl.polygonOffset( factor, units );
  48495. currentPolygonOffsetFactor = factor;
  48496. currentPolygonOffsetUnits = units;
  48497. }
  48498. } else {
  48499. disable( gl.POLYGON_OFFSET_FILL );
  48500. }
  48501. }
  48502. function setScissorTest( scissorTest ) {
  48503. if ( scissorTest ) {
  48504. enable( gl.SCISSOR_TEST );
  48505. } else {
  48506. disable( gl.SCISSOR_TEST );
  48507. }
  48508. }
  48509. // texture
  48510. function activeTexture( webglSlot ) {
  48511. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48512. if ( currentTextureSlot !== webglSlot ) {
  48513. gl.activeTexture( webglSlot );
  48514. currentTextureSlot = webglSlot;
  48515. }
  48516. }
  48517. function bindTexture( webglType, webglTexture, webglSlot ) {
  48518. if ( webglSlot === undefined ) {
  48519. if ( currentTextureSlot === null ) {
  48520. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48521. } else {
  48522. webglSlot = currentTextureSlot;
  48523. }
  48524. }
  48525. let boundTexture = currentBoundTextures[ webglSlot ];
  48526. if ( boundTexture === undefined ) {
  48527. boundTexture = { type: undefined, texture: undefined };
  48528. currentBoundTextures[ webglSlot ] = boundTexture;
  48529. }
  48530. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48531. if ( currentTextureSlot !== webglSlot ) {
  48532. gl.activeTexture( webglSlot );
  48533. currentTextureSlot = webglSlot;
  48534. }
  48535. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  48536. boundTexture.type = webglType;
  48537. boundTexture.texture = webglTexture;
  48538. }
  48539. }
  48540. function unbindTexture() {
  48541. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48542. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48543. gl.bindTexture( boundTexture.type, null );
  48544. boundTexture.type = undefined;
  48545. boundTexture.texture = undefined;
  48546. }
  48547. }
  48548. function compressedTexImage2D() {
  48549. try {
  48550. gl.compressedTexImage2D( ...arguments );
  48551. } catch ( error ) {
  48552. console.error( 'THREE.WebGLState:', error );
  48553. }
  48554. }
  48555. function compressedTexImage3D() {
  48556. try {
  48557. gl.compressedTexImage3D( ...arguments );
  48558. } catch ( error ) {
  48559. console.error( 'THREE.WebGLState:', error );
  48560. }
  48561. }
  48562. function texSubImage2D() {
  48563. try {
  48564. gl.texSubImage2D( ...arguments );
  48565. } catch ( error ) {
  48566. console.error( 'THREE.WebGLState:', error );
  48567. }
  48568. }
  48569. function texSubImage3D() {
  48570. try {
  48571. gl.texSubImage3D( ...arguments );
  48572. } catch ( error ) {
  48573. console.error( 'THREE.WebGLState:', error );
  48574. }
  48575. }
  48576. function compressedTexSubImage2D() {
  48577. try {
  48578. gl.compressedTexSubImage2D( ...arguments );
  48579. } catch ( error ) {
  48580. console.error( 'THREE.WebGLState:', error );
  48581. }
  48582. }
  48583. function compressedTexSubImage3D() {
  48584. try {
  48585. gl.compressedTexSubImage3D( ...arguments );
  48586. } catch ( error ) {
  48587. console.error( 'THREE.WebGLState:', error );
  48588. }
  48589. }
  48590. function texStorage2D() {
  48591. try {
  48592. gl.texStorage2D( ...arguments );
  48593. } catch ( error ) {
  48594. console.error( 'THREE.WebGLState:', error );
  48595. }
  48596. }
  48597. function texStorage3D() {
  48598. try {
  48599. gl.texStorage3D( ...arguments );
  48600. } catch ( error ) {
  48601. console.error( 'THREE.WebGLState:', error );
  48602. }
  48603. }
  48604. function texImage2D() {
  48605. try {
  48606. gl.texImage2D( ...arguments );
  48607. } catch ( error ) {
  48608. console.error( 'THREE.WebGLState:', error );
  48609. }
  48610. }
  48611. function texImage3D() {
  48612. try {
  48613. gl.texImage3D( ...arguments );
  48614. } catch ( error ) {
  48615. console.error( 'THREE.WebGLState:', error );
  48616. }
  48617. }
  48618. //
  48619. function scissor( scissor ) {
  48620. if ( currentScissor.equals( scissor ) === false ) {
  48621. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48622. currentScissor.copy( scissor );
  48623. }
  48624. }
  48625. function viewport( viewport ) {
  48626. if ( currentViewport.equals( viewport ) === false ) {
  48627. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48628. currentViewport.copy( viewport );
  48629. }
  48630. }
  48631. function updateUBOMapping( uniformsGroup, program ) {
  48632. let mapping = uboProgramMap.get( program );
  48633. if ( mapping === undefined ) {
  48634. mapping = new WeakMap();
  48635. uboProgramMap.set( program, mapping );
  48636. }
  48637. let blockIndex = mapping.get( uniformsGroup );
  48638. if ( blockIndex === undefined ) {
  48639. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  48640. mapping.set( uniformsGroup, blockIndex );
  48641. }
  48642. }
  48643. function uniformBlockBinding( uniformsGroup, program ) {
  48644. const mapping = uboProgramMap.get( program );
  48645. const blockIndex = mapping.get( uniformsGroup );
  48646. if ( uboBindings.get( program ) !== blockIndex ) {
  48647. // bind shader specific block index to global block point
  48648. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  48649. uboBindings.set( program, blockIndex );
  48650. }
  48651. }
  48652. //
  48653. function reset() {
  48654. // reset state
  48655. gl.disable( gl.BLEND );
  48656. gl.disable( gl.CULL_FACE );
  48657. gl.disable( gl.DEPTH_TEST );
  48658. gl.disable( gl.POLYGON_OFFSET_FILL );
  48659. gl.disable( gl.SCISSOR_TEST );
  48660. gl.disable( gl.STENCIL_TEST );
  48661. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48662. gl.blendEquation( gl.FUNC_ADD );
  48663. gl.blendFunc( gl.ONE, gl.ZERO );
  48664. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48665. gl.blendColor( 0, 0, 0, 0 );
  48666. gl.colorMask( true, true, true, true );
  48667. gl.clearColor( 0, 0, 0, 0 );
  48668. gl.depthMask( true );
  48669. gl.depthFunc( gl.LESS );
  48670. depthBuffer.setReversed( false );
  48671. gl.clearDepth( 1 );
  48672. gl.stencilMask( 0xffffffff );
  48673. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  48674. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  48675. gl.clearStencil( 0 );
  48676. gl.cullFace( gl.BACK );
  48677. gl.frontFace( gl.CCW );
  48678. gl.polygonOffset( 0, 0 );
  48679. gl.activeTexture( gl.TEXTURE0 );
  48680. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  48681. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48682. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48683. gl.useProgram( null );
  48684. gl.lineWidth( 1 );
  48685. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  48686. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  48687. // reset internals
  48688. enabledCapabilities = {};
  48689. currentTextureSlot = null;
  48690. currentBoundTextures = {};
  48691. currentBoundFramebuffers = {};
  48692. currentDrawbuffers = new WeakMap();
  48693. defaultDrawbuffers = [];
  48694. currentProgram = null;
  48695. currentBlendingEnabled = false;
  48696. currentBlending = null;
  48697. currentBlendEquation = null;
  48698. currentBlendSrc = null;
  48699. currentBlendDst = null;
  48700. currentBlendEquationAlpha = null;
  48701. currentBlendSrcAlpha = null;
  48702. currentBlendDstAlpha = null;
  48703. currentBlendColor = new Color( 0, 0, 0 );
  48704. currentBlendAlpha = 0;
  48705. currentPremultipledAlpha = false;
  48706. currentFlipSided = null;
  48707. currentCullFace = null;
  48708. currentLineWidth = null;
  48709. currentPolygonOffsetFactor = null;
  48710. currentPolygonOffsetUnits = null;
  48711. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48712. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48713. colorBuffer.reset();
  48714. depthBuffer.reset();
  48715. stencilBuffer.reset();
  48716. }
  48717. return {
  48718. buffers: {
  48719. color: colorBuffer,
  48720. depth: depthBuffer,
  48721. stencil: stencilBuffer
  48722. },
  48723. enable: enable,
  48724. disable: disable,
  48725. bindFramebuffer: bindFramebuffer,
  48726. drawBuffers: drawBuffers,
  48727. useProgram: useProgram,
  48728. setBlending: setBlending,
  48729. setMaterial: setMaterial,
  48730. setFlipSided: setFlipSided,
  48731. setCullFace: setCullFace,
  48732. setLineWidth: setLineWidth,
  48733. setPolygonOffset: setPolygonOffset,
  48734. setScissorTest: setScissorTest,
  48735. activeTexture: activeTexture,
  48736. bindTexture: bindTexture,
  48737. unbindTexture: unbindTexture,
  48738. compressedTexImage2D: compressedTexImage2D,
  48739. compressedTexImage3D: compressedTexImage3D,
  48740. texImage2D: texImage2D,
  48741. texImage3D: texImage3D,
  48742. updateUBOMapping: updateUBOMapping,
  48743. uniformBlockBinding: uniformBlockBinding,
  48744. texStorage2D: texStorage2D,
  48745. texStorage3D: texStorage3D,
  48746. texSubImage2D: texSubImage2D,
  48747. texSubImage3D: texSubImage3D,
  48748. compressedTexSubImage2D: compressedTexSubImage2D,
  48749. compressedTexSubImage3D: compressedTexSubImage3D,
  48750. scissor: scissor,
  48751. viewport: viewport,
  48752. reset: reset
  48753. };
  48754. }
  48755. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  48756. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  48757. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48758. const _imageDimensions = new Vector2();
  48759. const _videoTextures = new WeakMap();
  48760. let _canvas;
  48761. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  48762. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  48763. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  48764. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  48765. let useOffscreenCanvas = false;
  48766. try {
  48767. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  48768. // eslint-disable-next-line compat/compat
  48769. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  48770. } catch ( err ) {
  48771. // Ignore any errors
  48772. }
  48773. function createCanvas( width, height ) {
  48774. // Use OffscreenCanvas when available. Specially needed in web workers
  48775. return useOffscreenCanvas ?
  48776. // eslint-disable-next-line compat/compat
  48777. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  48778. }
  48779. function resizeImage( image, needsNewCanvas, maxSize ) {
  48780. let scale = 1;
  48781. const dimensions = getDimensions( image );
  48782. // handle case if texture exceeds max size
  48783. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  48784. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  48785. }
  48786. // only perform resize if necessary
  48787. if ( scale < 1 ) {
  48788. // only perform resize for certain image types
  48789. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  48790. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  48791. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  48792. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  48793. const width = Math.floor( scale * dimensions.width );
  48794. const height = Math.floor( scale * dimensions.height );
  48795. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  48796. // cube textures can't reuse the same canvas
  48797. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  48798. canvas.width = width;
  48799. canvas.height = height;
  48800. const context = canvas.getContext( '2d' );
  48801. context.drawImage( image, 0, 0, width, height );
  48802. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  48803. return canvas;
  48804. } else {
  48805. if ( 'data' in image ) {
  48806. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  48807. }
  48808. return image;
  48809. }
  48810. }
  48811. return image;
  48812. }
  48813. function textureNeedsGenerateMipmaps( texture ) {
  48814. return texture.generateMipmaps;
  48815. }
  48816. function generateMipmap( target ) {
  48817. _gl.generateMipmap( target );
  48818. }
  48819. function getTargetType( texture ) {
  48820. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  48821. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  48822. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  48823. return _gl.TEXTURE_2D;
  48824. }
  48825. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  48826. if ( internalFormatName !== null ) {
  48827. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  48828. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  48829. }
  48830. let internalFormat = glFormat;
  48831. if ( glFormat === _gl.RED ) {
  48832. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  48833. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  48834. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  48835. }
  48836. if ( glFormat === _gl.RED_INTEGER ) {
  48837. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  48838. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  48839. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  48840. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  48841. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  48842. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  48843. }
  48844. if ( glFormat === _gl.RG ) {
  48845. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  48846. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  48847. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  48848. }
  48849. if ( glFormat === _gl.RG_INTEGER ) {
  48850. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  48851. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  48852. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  48853. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  48854. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  48855. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  48856. }
  48857. if ( glFormat === _gl.RGB_INTEGER ) {
  48858. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  48859. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  48860. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  48861. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  48862. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  48863. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  48864. }
  48865. if ( glFormat === _gl.RGBA_INTEGER ) {
  48866. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  48867. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  48868. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  48869. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  48870. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  48871. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  48872. }
  48873. if ( glFormat === _gl.RGB ) {
  48874. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  48875. }
  48876. if ( glFormat === _gl.RGBA ) {
  48877. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48878. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  48879. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  48880. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  48881. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  48882. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  48883. }
  48884. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  48885. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  48886. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  48887. extensions.get( 'EXT_color_buffer_float' );
  48888. }
  48889. return internalFormat;
  48890. }
  48891. function getInternalDepthFormat( useStencil, depthType ) {
  48892. let glInternalFormat;
  48893. if ( useStencil ) {
  48894. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48895. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48896. } else if ( depthType === FloatType ) {
  48897. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  48898. } else if ( depthType === UnsignedShortType ) {
  48899. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48900. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  48901. }
  48902. } else {
  48903. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48904. glInternalFormat = _gl.DEPTH_COMPONENT24;
  48905. } else if ( depthType === FloatType ) {
  48906. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  48907. } else if ( depthType === UnsignedShortType ) {
  48908. glInternalFormat = _gl.DEPTH_COMPONENT16;
  48909. }
  48910. }
  48911. return glInternalFormat;
  48912. }
  48913. function getMipLevels( texture, image ) {
  48914. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  48915. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  48916. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  48917. // user-defined mipmaps
  48918. return texture.mipmaps.length;
  48919. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  48920. return image.mipmaps.length;
  48921. } else {
  48922. // texture without mipmaps (only base level)
  48923. return 1;
  48924. }
  48925. }
  48926. //
  48927. function onTextureDispose( event ) {
  48928. const texture = event.target;
  48929. texture.removeEventListener( 'dispose', onTextureDispose );
  48930. deallocateTexture( texture );
  48931. if ( texture.isVideoTexture ) {
  48932. _videoTextures.delete( texture );
  48933. }
  48934. }
  48935. function onRenderTargetDispose( event ) {
  48936. const renderTarget = event.target;
  48937. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  48938. deallocateRenderTarget( renderTarget );
  48939. }
  48940. //
  48941. function deallocateTexture( texture ) {
  48942. const textureProperties = properties.get( texture );
  48943. if ( textureProperties.__webglInit === undefined ) return;
  48944. // check if it's necessary to remove the WebGLTexture object
  48945. const source = texture.source;
  48946. const webglTextures = _sources.get( source );
  48947. if ( webglTextures ) {
  48948. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  48949. webglTexture.usedTimes --;
  48950. // the WebGLTexture object is not used anymore, remove it
  48951. if ( webglTexture.usedTimes === 0 ) {
  48952. deleteTexture( texture );
  48953. }
  48954. // remove the weak map entry if no WebGLTexture uses the source anymore
  48955. if ( Object.keys( webglTextures ).length === 0 ) {
  48956. _sources.delete( source );
  48957. }
  48958. }
  48959. properties.remove( texture );
  48960. }
  48961. function deleteTexture( texture ) {
  48962. const textureProperties = properties.get( texture );
  48963. _gl.deleteTexture( textureProperties.__webglTexture );
  48964. const source = texture.source;
  48965. const webglTextures = _sources.get( source );
  48966. delete webglTextures[ textureProperties.__cacheKey ];
  48967. info.memory.textures --;
  48968. }
  48969. function deallocateRenderTarget( renderTarget ) {
  48970. const renderTargetProperties = properties.get( renderTarget );
  48971. if ( renderTarget.depthTexture ) {
  48972. renderTarget.depthTexture.dispose();
  48973. properties.remove( renderTarget.depthTexture );
  48974. }
  48975. if ( renderTarget.isWebGLCubeRenderTarget ) {
  48976. for ( let i = 0; i < 6; i ++ ) {
  48977. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  48978. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  48979. } else {
  48980. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  48981. }
  48982. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  48983. }
  48984. } else {
  48985. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  48986. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  48987. } else {
  48988. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  48989. }
  48990. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  48991. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  48992. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  48993. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  48994. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48995. }
  48996. }
  48997. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  48998. }
  48999. const textures = renderTarget.textures;
  49000. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49001. const attachmentProperties = properties.get( textures[ i ] );
  49002. if ( attachmentProperties.__webglTexture ) {
  49003. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49004. info.memory.textures --;
  49005. }
  49006. properties.remove( textures[ i ] );
  49007. }
  49008. properties.remove( renderTarget );
  49009. }
  49010. //
  49011. let textureUnits = 0;
  49012. function resetTextureUnits() {
  49013. textureUnits = 0;
  49014. }
  49015. function allocateTextureUnit() {
  49016. const textureUnit = textureUnits;
  49017. if ( textureUnit >= capabilities.maxTextures ) {
  49018. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49019. }
  49020. textureUnits += 1;
  49021. return textureUnit;
  49022. }
  49023. function getTextureCacheKey( texture ) {
  49024. const array = [];
  49025. array.push( texture.wrapS );
  49026. array.push( texture.wrapT );
  49027. array.push( texture.wrapR || 0 );
  49028. array.push( texture.magFilter );
  49029. array.push( texture.minFilter );
  49030. array.push( texture.anisotropy );
  49031. array.push( texture.internalFormat );
  49032. array.push( texture.format );
  49033. array.push( texture.type );
  49034. array.push( texture.generateMipmaps );
  49035. array.push( texture.premultiplyAlpha );
  49036. array.push( texture.flipY );
  49037. array.push( texture.unpackAlignment );
  49038. array.push( texture.colorSpace );
  49039. return array.join();
  49040. }
  49041. //
  49042. function setTexture2D( texture, slot ) {
  49043. const textureProperties = properties.get( texture );
  49044. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49045. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49046. const image = texture.image;
  49047. if ( image === null ) {
  49048. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  49049. } else if ( image.complete === false ) {
  49050. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  49051. } else {
  49052. uploadTexture( textureProperties, texture, slot );
  49053. return;
  49054. }
  49055. } else if ( texture.isExternalTexture ) {
  49056. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49057. }
  49058. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49059. }
  49060. function setTexture2DArray( texture, slot ) {
  49061. const textureProperties = properties.get( texture );
  49062. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49063. uploadTexture( textureProperties, texture, slot );
  49064. return;
  49065. }
  49066. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49067. }
  49068. function setTexture3D( texture, slot ) {
  49069. const textureProperties = properties.get( texture );
  49070. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49071. uploadTexture( textureProperties, texture, slot );
  49072. return;
  49073. }
  49074. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49075. }
  49076. function setTextureCube( texture, slot ) {
  49077. const textureProperties = properties.get( texture );
  49078. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  49079. uploadCubeTexture( textureProperties, texture, slot );
  49080. return;
  49081. }
  49082. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49083. }
  49084. const wrappingToGL = {
  49085. [ RepeatWrapping ]: _gl.REPEAT,
  49086. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49087. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49088. };
  49089. const filterToGL = {
  49090. [ NearestFilter ]: _gl.NEAREST,
  49091. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49092. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49093. [ LinearFilter ]: _gl.LINEAR,
  49094. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49095. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49096. };
  49097. const compareToGL = {
  49098. [ NeverCompare ]: _gl.NEVER,
  49099. [ AlwaysCompare ]: _gl.ALWAYS,
  49100. [ LessCompare ]: _gl.LESS,
  49101. [ LessEqualCompare ]: _gl.LEQUAL,
  49102. [ EqualCompare ]: _gl.EQUAL,
  49103. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49104. [ GreaterCompare ]: _gl.GREATER,
  49105. [ NotEqualCompare ]: _gl.NOTEQUAL
  49106. };
  49107. function setTextureParameters( textureType, texture ) {
  49108. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49109. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49110. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49111. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49112. }
  49113. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49114. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49115. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49116. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49117. }
  49118. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49119. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49120. if ( texture.compareFunction ) {
  49121. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49122. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49123. }
  49124. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49125. if ( texture.magFilter === NearestFilter ) return;
  49126. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49127. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49128. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49129. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49130. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49131. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49132. }
  49133. }
  49134. }
  49135. function initTexture( textureProperties, texture ) {
  49136. let forceUpload = false;
  49137. if ( textureProperties.__webglInit === undefined ) {
  49138. textureProperties.__webglInit = true;
  49139. texture.addEventListener( 'dispose', onTextureDispose );
  49140. }
  49141. // create Source <-> WebGLTextures mapping if necessary
  49142. const source = texture.source;
  49143. let webglTextures = _sources.get( source );
  49144. if ( webglTextures === undefined ) {
  49145. webglTextures = {};
  49146. _sources.set( source, webglTextures );
  49147. }
  49148. // check if there is already a WebGLTexture object for the given texture parameters
  49149. const textureCacheKey = getTextureCacheKey( texture );
  49150. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49151. // if not, create a new instance of WebGLTexture
  49152. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49153. // create new entry
  49154. webglTextures[ textureCacheKey ] = {
  49155. texture: _gl.createTexture(),
  49156. usedTimes: 0
  49157. };
  49158. info.memory.textures ++;
  49159. // when a new instance of WebGLTexture was created, a texture upload is required
  49160. // even if the image contents are identical
  49161. forceUpload = true;
  49162. }
  49163. webglTextures[ textureCacheKey ].usedTimes ++;
  49164. // every time the texture cache key changes, it's necessary to check if an instance of
  49165. // WebGLTexture can be deleted in order to avoid a memory leak.
  49166. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49167. if ( webglTexture !== undefined ) {
  49168. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49169. if ( webglTexture.usedTimes === 0 ) {
  49170. deleteTexture( texture );
  49171. }
  49172. }
  49173. // store references to cache key and WebGLTexture object
  49174. textureProperties.__cacheKey = textureCacheKey;
  49175. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49176. }
  49177. return forceUpload;
  49178. }
  49179. function getRow( index, rowLength, componentStride ) {
  49180. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49181. }
  49182. function updateTexture( texture, image, glFormat, glType ) {
  49183. const componentStride = 4; // only RGBA supported
  49184. const updateRanges = texture.updateRanges;
  49185. if ( updateRanges.length === 0 ) {
  49186. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49187. } else {
  49188. // Before applying update ranges, we merge any adjacent / overlapping
  49189. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49190. // to performance improvements for applications which make heavy use of
  49191. // update ranges. Likely due to GPU command overhead.
  49192. //
  49193. // Note that to reduce garbage collection between frames, we merge the
  49194. // update ranges in-place. This is safe because this method will clear the
  49195. // update ranges once updated.
  49196. updateRanges.sort( ( a, b ) => a.start - b.start );
  49197. // To merge the update ranges in-place, we work from left to right in the
  49198. // existing updateRanges array, merging ranges. This may result in a final
  49199. // array which is smaller than the original. This index tracks the last
  49200. // index representing a merged range, any data after this index can be
  49201. // trimmed once the merge algorithm is completed.
  49202. let mergeIndex = 0;
  49203. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49204. const previousRange = updateRanges[ mergeIndex ];
  49205. const range = updateRanges[ i ];
  49206. // Only merge if in the same row and overlapping/adjacent
  49207. const previousEnd = previousRange.start + previousRange.count;
  49208. const currentRow = getRow( range.start, image.width, componentStride );
  49209. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49210. // We add one here to merge adjacent ranges. This is safe because ranges
  49211. // operate over positive integers.
  49212. if (
  49213. range.start <= previousEnd + 1 &&
  49214. currentRow === previousRow &&
  49215. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49216. ) {
  49217. previousRange.count = Math.max(
  49218. previousRange.count,
  49219. range.start + range.count - previousRange.start
  49220. );
  49221. } else {
  49222. ++ mergeIndex;
  49223. updateRanges[ mergeIndex ] = range;
  49224. }
  49225. }
  49226. // Trim the array to only contain the merged ranges.
  49227. updateRanges.length = mergeIndex + 1;
  49228. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49229. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49230. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49231. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49232. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49233. const range = updateRanges[ i ];
  49234. const pixelStart = Math.floor( range.start / componentStride );
  49235. const pixelCount = Math.ceil( range.count / componentStride );
  49236. const x = pixelStart % image.width;
  49237. const y = Math.floor( pixelStart / image.width );
  49238. // Assumes update ranges refer to contiguous memory
  49239. const width = pixelCount;
  49240. const height = 1;
  49241. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49242. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49243. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49244. }
  49245. texture.clearUpdateRanges();
  49246. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49247. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49248. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49249. }
  49250. }
  49251. function uploadTexture( textureProperties, texture, slot ) {
  49252. let textureType = _gl.TEXTURE_2D;
  49253. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49254. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49255. const forceUpload = initTexture( textureProperties, texture );
  49256. const source = texture.source;
  49257. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49258. const sourceProperties = properties.get( source );
  49259. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49260. state.activeTexture( _gl.TEXTURE0 + slot );
  49261. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49262. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49263. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49264. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49265. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49266. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49267. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49268. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49269. image = verifyColorSpace( texture, image );
  49270. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49271. const glType = utils.convert( texture.type );
  49272. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  49273. setTextureParameters( textureType, texture );
  49274. let mipmap;
  49275. const mipmaps = texture.mipmaps;
  49276. const useTexStorage = ( texture.isVideoTexture !== true );
  49277. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49278. const dataReady = source.dataReady;
  49279. const levels = getMipLevels( texture, image );
  49280. if ( texture.isDepthTexture ) {
  49281. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  49282. //
  49283. if ( allocateMemory ) {
  49284. if ( useTexStorage ) {
  49285. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  49286. } else {
  49287. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  49288. }
  49289. }
  49290. } else if ( texture.isDataTexture ) {
  49291. // use manually created mipmaps if available
  49292. // if there are no manual mipmaps
  49293. // set 0 level mipmap and then use GL to generate other mipmap levels
  49294. if ( mipmaps.length > 0 ) {
  49295. if ( useTexStorage && allocateMemory ) {
  49296. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49297. }
  49298. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49299. mipmap = mipmaps[ i ];
  49300. if ( useTexStorage ) {
  49301. if ( dataReady ) {
  49302. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49303. }
  49304. } else {
  49305. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49306. }
  49307. }
  49308. texture.generateMipmaps = false;
  49309. } else {
  49310. if ( useTexStorage ) {
  49311. if ( allocateMemory ) {
  49312. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49313. }
  49314. if ( dataReady ) {
  49315. updateTexture( texture, image, glFormat, glType );
  49316. }
  49317. } else {
  49318. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  49319. }
  49320. }
  49321. } else if ( texture.isCompressedTexture ) {
  49322. if ( texture.isCompressedArrayTexture ) {
  49323. if ( useTexStorage && allocateMemory ) {
  49324. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  49325. }
  49326. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49327. mipmap = mipmaps[ i ];
  49328. if ( texture.format !== RGBAFormat ) {
  49329. if ( glFormat !== null ) {
  49330. if ( useTexStorage ) {
  49331. if ( dataReady ) {
  49332. if ( texture.layerUpdates.size > 0 ) {
  49333. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  49334. for ( const layerIndex of texture.layerUpdates ) {
  49335. const layerData = mipmap.data.subarray(
  49336. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  49337. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  49338. );
  49339. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  49340. }
  49341. texture.clearLayerUpdates();
  49342. } else {
  49343. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49344. }
  49345. }
  49346. } else {
  49347. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  49348. }
  49349. } else {
  49350. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49351. }
  49352. } else {
  49353. if ( useTexStorage ) {
  49354. if ( dataReady ) {
  49355. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49356. }
  49357. } else {
  49358. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  49359. }
  49360. }
  49361. }
  49362. } else {
  49363. if ( useTexStorage && allocateMemory ) {
  49364. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49365. }
  49366. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49367. mipmap = mipmaps[ i ];
  49368. if ( texture.format !== RGBAFormat ) {
  49369. if ( glFormat !== null ) {
  49370. if ( useTexStorage ) {
  49371. if ( dataReady ) {
  49372. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49373. }
  49374. } else {
  49375. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49376. }
  49377. } else {
  49378. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49379. }
  49380. } else {
  49381. if ( useTexStorage ) {
  49382. if ( dataReady ) {
  49383. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49384. }
  49385. } else {
  49386. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49387. }
  49388. }
  49389. }
  49390. }
  49391. } else if ( texture.isDataArrayTexture ) {
  49392. if ( useTexStorage ) {
  49393. if ( allocateMemory ) {
  49394. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  49395. }
  49396. if ( dataReady ) {
  49397. if ( texture.layerUpdates.size > 0 ) {
  49398. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49399. for ( const layerIndex of texture.layerUpdates ) {
  49400. const layerData = image.data.subarray(
  49401. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49402. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49403. );
  49404. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49405. }
  49406. texture.clearLayerUpdates();
  49407. } else {
  49408. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49409. }
  49410. }
  49411. } else {
  49412. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49413. }
  49414. } else if ( texture.isData3DTexture ) {
  49415. if ( useTexStorage ) {
  49416. if ( allocateMemory ) {
  49417. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  49418. }
  49419. if ( dataReady ) {
  49420. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49421. }
  49422. } else {
  49423. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49424. }
  49425. } else if ( texture.isFramebufferTexture ) {
  49426. if ( allocateMemory ) {
  49427. if ( useTexStorage ) {
  49428. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49429. } else {
  49430. let width = image.width, height = image.height;
  49431. for ( let i = 0; i < levels; i ++ ) {
  49432. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  49433. width >>= 1;
  49434. height >>= 1;
  49435. }
  49436. }
  49437. }
  49438. } else {
  49439. // regular Texture (image, video, canvas)
  49440. // use manually created mipmaps if available
  49441. // if there are no manual mipmaps
  49442. // set 0 level mipmap and then use GL to generate other mipmap levels
  49443. if ( mipmaps.length > 0 ) {
  49444. if ( useTexStorage && allocateMemory ) {
  49445. const dimensions = getDimensions( mipmaps[ 0 ] );
  49446. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49447. }
  49448. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49449. mipmap = mipmaps[ i ];
  49450. if ( useTexStorage ) {
  49451. if ( dataReady ) {
  49452. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  49453. }
  49454. } else {
  49455. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  49456. }
  49457. }
  49458. texture.generateMipmaps = false;
  49459. } else {
  49460. if ( useTexStorage ) {
  49461. if ( allocateMemory ) {
  49462. const dimensions = getDimensions( image );
  49463. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49464. }
  49465. if ( dataReady ) {
  49466. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  49467. }
  49468. } else {
  49469. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  49470. }
  49471. }
  49472. }
  49473. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49474. generateMipmap( textureType );
  49475. }
  49476. sourceProperties.__version = source.version;
  49477. if ( texture.onUpdate ) texture.onUpdate( texture );
  49478. }
  49479. textureProperties.__version = texture.version;
  49480. }
  49481. function uploadCubeTexture( textureProperties, texture, slot ) {
  49482. if ( texture.image.length !== 6 ) return;
  49483. const forceUpload = initTexture( textureProperties, texture );
  49484. const source = texture.source;
  49485. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49486. const sourceProperties = properties.get( source );
  49487. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49488. state.activeTexture( _gl.TEXTURE0 + slot );
  49489. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49490. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49491. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49492. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49493. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49494. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49495. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49496. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  49497. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  49498. const cubeImage = [];
  49499. for ( let i = 0; i < 6; i ++ ) {
  49500. if ( ! isCompressed && ! isDataTexture ) {
  49501. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  49502. } else {
  49503. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  49504. }
  49505. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  49506. }
  49507. const image = cubeImage[ 0 ],
  49508. glFormat = utils.convert( texture.format, texture.colorSpace ),
  49509. glType = utils.convert( texture.type ),
  49510. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49511. const useTexStorage = ( texture.isVideoTexture !== true );
  49512. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49513. const dataReady = source.dataReady;
  49514. let levels = getMipLevels( texture, image );
  49515. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49516. let mipmaps;
  49517. if ( isCompressed ) {
  49518. if ( useTexStorage && allocateMemory ) {
  49519. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  49520. }
  49521. for ( let i = 0; i < 6; i ++ ) {
  49522. mipmaps = cubeImage[ i ].mipmaps;
  49523. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49524. const mipmap = mipmaps[ j ];
  49525. if ( texture.format !== RGBAFormat ) {
  49526. if ( glFormat !== null ) {
  49527. if ( useTexStorage ) {
  49528. if ( dataReady ) {
  49529. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49530. }
  49531. } else {
  49532. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49533. }
  49534. } else {
  49535. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  49536. }
  49537. } else {
  49538. if ( useTexStorage ) {
  49539. if ( dataReady ) {
  49540. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49541. }
  49542. } else {
  49543. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49544. }
  49545. }
  49546. }
  49547. }
  49548. } else {
  49549. mipmaps = texture.mipmaps;
  49550. if ( useTexStorage && allocateMemory ) {
  49551. // TODO: Uniformly handle mipmap definitions
  49552. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  49553. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  49554. if ( mipmaps.length > 0 ) levels ++;
  49555. const dimensions = getDimensions( cubeImage[ 0 ] );
  49556. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  49557. }
  49558. for ( let i = 0; i < 6; i ++ ) {
  49559. if ( isDataTexture ) {
  49560. if ( useTexStorage ) {
  49561. if ( dataReady ) {
  49562. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  49563. }
  49564. } else {
  49565. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  49566. }
  49567. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49568. const mipmap = mipmaps[ j ];
  49569. const mipmapImage = mipmap.image[ i ].image;
  49570. if ( useTexStorage ) {
  49571. if ( dataReady ) {
  49572. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  49573. }
  49574. } else {
  49575. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  49576. }
  49577. }
  49578. } else {
  49579. if ( useTexStorage ) {
  49580. if ( dataReady ) {
  49581. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  49582. }
  49583. } else {
  49584. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  49585. }
  49586. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49587. const mipmap = mipmaps[ j ];
  49588. if ( useTexStorage ) {
  49589. if ( dataReady ) {
  49590. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  49591. }
  49592. } else {
  49593. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  49594. }
  49595. }
  49596. }
  49597. }
  49598. }
  49599. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49600. // We assume images for cube map have the same size.
  49601. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49602. }
  49603. sourceProperties.__version = source.version;
  49604. if ( texture.onUpdate ) texture.onUpdate( texture );
  49605. }
  49606. textureProperties.__version = texture.version;
  49607. }
  49608. // Render targets
  49609. // Setup storage for target texture and bind it to correct framebuffer
  49610. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  49611. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49612. const glType = utils.convert( texture.type );
  49613. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49614. const renderTargetProperties = properties.get( renderTarget );
  49615. const textureProperties = properties.get( texture );
  49616. textureProperties.__renderTarget = renderTarget;
  49617. if ( ! renderTargetProperties.__hasExternalTextures ) {
  49618. const width = Math.max( 1, renderTarget.width >> level );
  49619. const height = Math.max( 1, renderTarget.height >> level );
  49620. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  49621. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  49622. } else {
  49623. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  49624. }
  49625. }
  49626. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49627. if ( useMultisampledRTT( renderTarget ) ) {
  49628. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  49629. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  49630. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  49631. }
  49632. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49633. }
  49634. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  49635. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  49636. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49637. if ( renderTarget.depthBuffer ) {
  49638. // retrieve the depth attachment types
  49639. const depthTexture = renderTarget.depthTexture;
  49640. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  49641. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  49642. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49643. // set up the attachment
  49644. const samples = getRenderTargetSamples( renderTarget );
  49645. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  49646. if ( isUseMultisampledRTT ) {
  49647. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49648. } else if ( isMultisample ) {
  49649. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49650. } else {
  49651. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49652. }
  49653. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49654. } else {
  49655. const textures = renderTarget.textures;
  49656. for ( let i = 0; i < textures.length; i ++ ) {
  49657. const texture = textures[ i ];
  49658. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49659. const glType = utils.convert( texture.type );
  49660. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49661. const samples = getRenderTargetSamples( renderTarget );
  49662. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  49663. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49664. } else if ( useMultisampledRTT( renderTarget ) ) {
  49665. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49666. } else {
  49667. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49668. }
  49669. }
  49670. }
  49671. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49672. }
  49673. // Setup resources for a Depth Texture for a FBO (needs an extension)
  49674. function setupDepthTexture( framebuffer, renderTarget ) {
  49675. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  49676. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  49677. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49678. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  49679. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  49680. }
  49681. const textureProperties = properties.get( renderTarget.depthTexture );
  49682. textureProperties.__renderTarget = renderTarget;
  49683. // upload an empty depth texture with framebuffer size
  49684. if ( ! textureProperties.__webglTexture ||
  49685. renderTarget.depthTexture.image.width !== renderTarget.width ||
  49686. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  49687. renderTarget.depthTexture.image.width = renderTarget.width;
  49688. renderTarget.depthTexture.image.height = renderTarget.height;
  49689. renderTarget.depthTexture.needsUpdate = true;
  49690. }
  49691. setTexture2D( renderTarget.depthTexture, 0 );
  49692. const webglDepthTexture = textureProperties.__webglTexture;
  49693. const samples = getRenderTargetSamples( renderTarget );
  49694. if ( renderTarget.depthTexture.format === DepthFormat ) {
  49695. if ( useMultisampledRTT( renderTarget ) ) {
  49696. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49697. } else {
  49698. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49699. }
  49700. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  49701. if ( useMultisampledRTT( renderTarget ) ) {
  49702. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49703. } else {
  49704. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49705. }
  49706. } else {
  49707. throw new Error( 'Unknown depthTexture format' );
  49708. }
  49709. }
  49710. // Setup GL resources for a non-texture depth buffer
  49711. function setupDepthRenderbuffer( renderTarget ) {
  49712. const renderTargetProperties = properties.get( renderTarget );
  49713. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49714. // if the bound depth texture has changed
  49715. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  49716. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  49717. const depthTexture = renderTarget.depthTexture;
  49718. if ( renderTargetProperties.__depthDisposeCallback ) {
  49719. renderTargetProperties.__depthDisposeCallback();
  49720. }
  49721. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  49722. if ( depthTexture ) {
  49723. const disposeEvent = () => {
  49724. delete renderTargetProperties.__boundDepthTexture;
  49725. delete renderTargetProperties.__depthDisposeCallback;
  49726. depthTexture.removeEventListener( 'dispose', disposeEvent );
  49727. };
  49728. depthTexture.addEventListener( 'dispose', disposeEvent );
  49729. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  49730. }
  49731. renderTargetProperties.__boundDepthTexture = depthTexture;
  49732. }
  49733. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  49734. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  49735. const mipmaps = renderTarget.texture.mipmaps;
  49736. if ( mipmaps && mipmaps.length > 0 ) {
  49737. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget );
  49738. } else {
  49739. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  49740. }
  49741. } else {
  49742. if ( isCube ) {
  49743. renderTargetProperties.__webglDepthbuffer = [];
  49744. for ( let i = 0; i < 6; i ++ ) {
  49745. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  49746. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  49747. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  49748. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  49749. } else {
  49750. // attach buffer if it's been created already
  49751. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49752. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  49753. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49754. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49755. }
  49756. }
  49757. } else {
  49758. const mipmaps = renderTarget.texture.mipmaps;
  49759. if ( mipmaps && mipmaps.length > 0 ) {
  49760. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49761. } else {
  49762. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49763. }
  49764. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  49765. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  49766. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  49767. } else {
  49768. // attach buffer if it's been created already
  49769. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49770. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  49771. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49772. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49773. }
  49774. }
  49775. }
  49776. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49777. }
  49778. // rebind framebuffer with external textures
  49779. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  49780. const renderTargetProperties = properties.get( renderTarget );
  49781. if ( colorTexture !== undefined ) {
  49782. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  49783. }
  49784. if ( depthTexture !== undefined ) {
  49785. setupDepthRenderbuffer( renderTarget );
  49786. }
  49787. }
  49788. // Set up GL resources for the render target
  49789. function setupRenderTarget( renderTarget ) {
  49790. const texture = renderTarget.texture;
  49791. const renderTargetProperties = properties.get( renderTarget );
  49792. const textureProperties = properties.get( texture );
  49793. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  49794. const textures = renderTarget.textures;
  49795. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49796. const isMultipleRenderTargets = ( textures.length > 1 );
  49797. if ( ! isMultipleRenderTargets ) {
  49798. if ( textureProperties.__webglTexture === undefined ) {
  49799. textureProperties.__webglTexture = _gl.createTexture();
  49800. }
  49801. textureProperties.__version = texture.version;
  49802. info.memory.textures ++;
  49803. }
  49804. // Setup framebuffer
  49805. if ( isCube ) {
  49806. renderTargetProperties.__webglFramebuffer = [];
  49807. for ( let i = 0; i < 6; i ++ ) {
  49808. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49809. renderTargetProperties.__webglFramebuffer[ i ] = [];
  49810. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49811. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  49812. }
  49813. } else {
  49814. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  49815. }
  49816. }
  49817. } else {
  49818. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49819. renderTargetProperties.__webglFramebuffer = [];
  49820. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49821. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  49822. }
  49823. } else {
  49824. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  49825. }
  49826. if ( isMultipleRenderTargets ) {
  49827. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49828. const attachmentProperties = properties.get( textures[ i ] );
  49829. if ( attachmentProperties.__webglTexture === undefined ) {
  49830. attachmentProperties.__webglTexture = _gl.createTexture();
  49831. info.memory.textures ++;
  49832. }
  49833. }
  49834. }
  49835. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  49836. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  49837. renderTargetProperties.__webglColorRenderbuffer = [];
  49838. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49839. for ( let i = 0; i < textures.length; i ++ ) {
  49840. const texture = textures[ i ];
  49841. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  49842. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49843. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49844. const glType = utils.convert( texture.type );
  49845. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  49846. const samples = getRenderTargetSamples( renderTarget );
  49847. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49848. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49849. }
  49850. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49851. if ( renderTarget.depthBuffer ) {
  49852. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  49853. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  49854. }
  49855. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49856. }
  49857. }
  49858. // Setup color buffer
  49859. if ( isCube ) {
  49860. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  49861. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49862. for ( let i = 0; i < 6; i ++ ) {
  49863. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49864. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49865. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  49866. }
  49867. } else {
  49868. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  49869. }
  49870. }
  49871. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49872. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49873. }
  49874. state.unbindTexture();
  49875. } else if ( isMultipleRenderTargets ) {
  49876. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49877. const attachment = textures[ i ];
  49878. const attachmentProperties = properties.get( attachment );
  49879. let glTextureType = _gl.TEXTURE_2D;
  49880. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49881. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49882. }
  49883. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  49884. setTextureParameters( glTextureType, attachment );
  49885. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  49886. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  49887. generateMipmap( glTextureType );
  49888. }
  49889. }
  49890. state.unbindTexture();
  49891. } else {
  49892. let glTextureType = _gl.TEXTURE_2D;
  49893. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49894. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49895. }
  49896. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  49897. setTextureParameters( glTextureType, texture );
  49898. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49899. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49900. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  49901. }
  49902. } else {
  49903. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  49904. }
  49905. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49906. generateMipmap( glTextureType );
  49907. }
  49908. state.unbindTexture();
  49909. }
  49910. // Setup depth and stencil buffers
  49911. if ( renderTarget.depthBuffer ) {
  49912. setupDepthRenderbuffer( renderTarget );
  49913. }
  49914. }
  49915. function updateRenderTargetMipmap( renderTarget ) {
  49916. const textures = renderTarget.textures;
  49917. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49918. const texture = textures[ i ];
  49919. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49920. const targetType = getTargetType( renderTarget );
  49921. const webglTexture = properties.get( texture ).__webglTexture;
  49922. state.bindTexture( targetType, webglTexture );
  49923. generateMipmap( targetType );
  49924. state.unbindTexture();
  49925. }
  49926. }
  49927. }
  49928. const invalidationArrayRead = [];
  49929. const invalidationArrayDraw = [];
  49930. function updateMultisampleRenderTarget( renderTarget ) {
  49931. if ( renderTarget.samples > 0 ) {
  49932. if ( useMultisampledRTT( renderTarget ) === false ) {
  49933. const textures = renderTarget.textures;
  49934. const width = renderTarget.width;
  49935. const height = renderTarget.height;
  49936. let mask = _gl.COLOR_BUFFER_BIT;
  49937. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49938. const renderTargetProperties = properties.get( renderTarget );
  49939. const isMultipleRenderTargets = ( textures.length > 1 );
  49940. // If MRT we need to remove FBO attachments
  49941. if ( isMultipleRenderTargets ) {
  49942. for ( let i = 0; i < textures.length; i ++ ) {
  49943. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49944. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  49945. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49946. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  49947. }
  49948. }
  49949. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49950. const mipmaps = renderTarget.texture.mipmaps;
  49951. if ( mipmaps && mipmaps.length > 0 ) {
  49952. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49953. } else {
  49954. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49955. }
  49956. for ( let i = 0; i < textures.length; i ++ ) {
  49957. if ( renderTarget.resolveDepthBuffer ) {
  49958. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  49959. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  49960. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  49961. }
  49962. if ( isMultipleRenderTargets ) {
  49963. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49964. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  49965. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  49966. }
  49967. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  49968. if ( supportsInvalidateFramebuffer === true ) {
  49969. invalidationArrayRead.length = 0;
  49970. invalidationArrayDraw.length = 0;
  49971. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  49972. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  49973. invalidationArrayRead.push( depthStyle );
  49974. invalidationArrayDraw.push( depthStyle );
  49975. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  49976. }
  49977. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  49978. }
  49979. }
  49980. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  49981. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  49982. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  49983. if ( isMultipleRenderTargets ) {
  49984. for ( let i = 0; i < textures.length; i ++ ) {
  49985. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49986. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49987. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  49988. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49989. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  49990. }
  49991. }
  49992. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49993. } else {
  49994. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  49995. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49996. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  49997. }
  49998. }
  49999. }
  50000. }
  50001. function getRenderTargetSamples( renderTarget ) {
  50002. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50003. }
  50004. function useMultisampledRTT( renderTarget ) {
  50005. const renderTargetProperties = properties.get( renderTarget );
  50006. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50007. }
  50008. function updateVideoTexture( texture ) {
  50009. const frame = info.render.frame;
  50010. // Check the last frame we updated the VideoTexture
  50011. if ( _videoTextures.get( texture ) !== frame ) {
  50012. _videoTextures.set( texture, frame );
  50013. texture.update();
  50014. }
  50015. }
  50016. function verifyColorSpace( texture, image ) {
  50017. const colorSpace = texture.colorSpace;
  50018. const format = texture.format;
  50019. const type = texture.type;
  50020. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50021. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50022. // sRGB
  50023. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50024. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50025. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50026. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50027. }
  50028. } else {
  50029. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  50030. }
  50031. }
  50032. return image;
  50033. }
  50034. function getDimensions( image ) {
  50035. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50036. // if intrinsic data are not available, fallback to width/height
  50037. _imageDimensions.width = image.naturalWidth || image.width;
  50038. _imageDimensions.height = image.naturalHeight || image.height;
  50039. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50040. _imageDimensions.width = image.displayWidth;
  50041. _imageDimensions.height = image.displayHeight;
  50042. } else {
  50043. _imageDimensions.width = image.width;
  50044. _imageDimensions.height = image.height;
  50045. }
  50046. return _imageDimensions;
  50047. }
  50048. //
  50049. this.allocateTextureUnit = allocateTextureUnit;
  50050. this.resetTextureUnits = resetTextureUnits;
  50051. this.setTexture2D = setTexture2D;
  50052. this.setTexture2DArray = setTexture2DArray;
  50053. this.setTexture3D = setTexture3D;
  50054. this.setTextureCube = setTextureCube;
  50055. this.rebindTextures = rebindTextures;
  50056. this.setupRenderTarget = setupRenderTarget;
  50057. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50058. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50059. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50060. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50061. this.useMultisampledRTT = useMultisampledRTT;
  50062. }
  50063. function WebGLUtils( gl, extensions ) {
  50064. function convert( p, colorSpace = NoColorSpace ) {
  50065. let extension;
  50066. const transfer = ColorManagement.getTransfer( colorSpace );
  50067. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50068. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50069. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50070. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50071. if ( p === ByteType ) return gl.BYTE;
  50072. if ( p === ShortType ) return gl.SHORT;
  50073. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50074. if ( p === IntType ) return gl.INT;
  50075. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50076. if ( p === FloatType ) return gl.FLOAT;
  50077. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50078. if ( p === AlphaFormat ) return gl.ALPHA;
  50079. if ( p === RGBFormat ) return gl.RGB;
  50080. if ( p === RGBAFormat ) return gl.RGBA;
  50081. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50082. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50083. // WebGL2 formats.
  50084. if ( p === RedFormat ) return gl.RED;
  50085. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50086. if ( p === RGFormat ) return gl.RG;
  50087. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50088. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50089. // S3TC
  50090. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50091. if ( transfer === SRGBTransfer ) {
  50092. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50093. if ( extension !== null ) {
  50094. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50095. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50096. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50097. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50098. } else {
  50099. return null;
  50100. }
  50101. } else {
  50102. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50103. if ( extension !== null ) {
  50104. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50105. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50106. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50107. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50108. } else {
  50109. return null;
  50110. }
  50111. }
  50112. }
  50113. // PVRTC
  50114. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50115. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50116. if ( extension !== null ) {
  50117. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50118. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50119. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50120. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50121. } else {
  50122. return null;
  50123. }
  50124. }
  50125. // ETC
  50126. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  50127. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50128. if ( extension !== null ) {
  50129. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50130. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50131. } else {
  50132. return null;
  50133. }
  50134. }
  50135. // ASTC
  50136. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50137. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50138. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50139. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50140. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50141. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50142. if ( extension !== null ) {
  50143. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50144. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50145. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50146. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50147. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50148. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50149. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50150. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50151. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50152. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50153. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50154. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50155. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50156. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50157. } else {
  50158. return null;
  50159. }
  50160. }
  50161. // BPTC
  50162. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50163. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50164. if ( extension !== null ) {
  50165. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50166. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50167. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50168. } else {
  50169. return null;
  50170. }
  50171. }
  50172. // RGTC
  50173. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50174. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50175. if ( extension !== null ) {
  50176. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50177. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50178. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50179. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50180. } else {
  50181. return null;
  50182. }
  50183. }
  50184. //
  50185. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50186. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50187. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50188. }
  50189. return { convert: convert };
  50190. }
  50191. /**
  50192. * Represents a texture created externally from the renderer context.
  50193. *
  50194. * This may be a texture from a protected media stream, device camera feed,
  50195. * or other data feeds like a depth sensor.
  50196. *
  50197. * Note that this class is only supported in {@link WebGLRenderer} right now.
  50198. *
  50199. * @augments Texture
  50200. */
  50201. class ExternalTexture extends Texture {
  50202. /**
  50203. * Creates a new raw texture.
  50204. *
  50205. * @param {?WebGLTexture} [sourceTexture=null] - The external texture.
  50206. */
  50207. constructor( sourceTexture = null ) {
  50208. super();
  50209. /**
  50210. * The external source texture.
  50211. *
  50212. * @type {?WebGLTexture}
  50213. * @default null
  50214. */
  50215. this.sourceTexture = sourceTexture;
  50216. /**
  50217. * This flag can be used for type testing.
  50218. *
  50219. * @type {boolean}
  50220. * @readonly
  50221. * @default true
  50222. */
  50223. this.isExternalTexture = true;
  50224. }
  50225. }
  50226. const _occlusion_vertex = `
  50227. void main() {
  50228. gl_Position = vec4( position, 1.0 );
  50229. }`;
  50230. const _occlusion_fragment = `
  50231. uniform sampler2DArray depthColor;
  50232. uniform float depthWidth;
  50233. uniform float depthHeight;
  50234. void main() {
  50235. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50236. if ( coord.x >= 1.0 ) {
  50237. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50238. } else {
  50239. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50240. }
  50241. }`;
  50242. /**
  50243. * A XR module that manages the access to the Depth Sensing API.
  50244. */
  50245. class WebXRDepthSensing {
  50246. /**
  50247. * Constructs a new depth sensing module.
  50248. */
  50249. constructor() {
  50250. /**
  50251. * An opaque texture representing the depth of the user's environment.
  50252. *
  50253. * @type {?ExternalTexture}
  50254. */
  50255. this.texture = null;
  50256. /**
  50257. * A plane mesh for visualizing the depth texture.
  50258. *
  50259. * @type {?Mesh}
  50260. */
  50261. this.mesh = null;
  50262. /**
  50263. * The depth near value.
  50264. *
  50265. * @type {number}
  50266. */
  50267. this.depthNear = 0;
  50268. /**
  50269. * The depth near far.
  50270. *
  50271. * @type {number}
  50272. */
  50273. this.depthFar = 0;
  50274. }
  50275. /**
  50276. * Inits the depth sensing module
  50277. *
  50278. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  50279. * @param {XRRenderState} renderState - The XR render state.
  50280. */
  50281. init( depthData, renderState ) {
  50282. if ( this.texture === null ) {
  50283. const texture = new ExternalTexture( depthData.texture );
  50284. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  50285. this.depthNear = depthData.depthNear;
  50286. this.depthFar = depthData.depthFar;
  50287. }
  50288. this.texture = texture;
  50289. }
  50290. }
  50291. /**
  50292. * Returns a plane mesh that visualizes the depth texture.
  50293. *
  50294. * @param {ArrayCamera} cameraXR - The XR camera.
  50295. * @return {?Mesh} The plane mesh.
  50296. */
  50297. getMesh( cameraXR ) {
  50298. if ( this.texture !== null ) {
  50299. if ( this.mesh === null ) {
  50300. const viewport = cameraXR.cameras[ 0 ].viewport;
  50301. const material = new ShaderMaterial( {
  50302. vertexShader: _occlusion_vertex,
  50303. fragmentShader: _occlusion_fragment,
  50304. uniforms: {
  50305. depthColor: { value: this.texture },
  50306. depthWidth: { value: viewport.z },
  50307. depthHeight: { value: viewport.w }
  50308. }
  50309. } );
  50310. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  50311. }
  50312. }
  50313. return this.mesh;
  50314. }
  50315. /**
  50316. * Resets the module
  50317. */
  50318. reset() {
  50319. this.texture = null;
  50320. this.mesh = null;
  50321. }
  50322. /**
  50323. * Returns a texture representing the depth of the user's environment.
  50324. *
  50325. * @return {?ExternalTexture} The depth texture.
  50326. */
  50327. getDepthTexture() {
  50328. return this.texture;
  50329. }
  50330. }
  50331. /**
  50332. * This class represents an abstraction of the WebXR Device API and is
  50333. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  50334. * interface that allows users to enable/disable XR and perform XR related
  50335. * tasks like for instance retrieving controllers.
  50336. *
  50337. * @augments EventDispatcher
  50338. * @hideconstructor
  50339. */
  50340. class WebXRManager extends EventDispatcher {
  50341. /**
  50342. * Constructs a new WebGL renderer.
  50343. *
  50344. * @param {WebGLRenderer} renderer - The renderer.
  50345. * @param {WebGL2RenderingContext} gl - The rendering context.
  50346. */
  50347. constructor( renderer, gl ) {
  50348. super();
  50349. const scope = this;
  50350. let session = null;
  50351. let framebufferScaleFactor = 1.0;
  50352. let referenceSpace = null;
  50353. let referenceSpaceType = 'local-floor';
  50354. // Set default foveation to maximum.
  50355. let foveation = 1.0;
  50356. let customReferenceSpace = null;
  50357. let pose = null;
  50358. let glBinding = null;
  50359. let glProjLayer = null;
  50360. let glBaseLayer = null;
  50361. let xrFrame = null;
  50362. const depthSensing = new WebXRDepthSensing();
  50363. const cameraAccessTextures = {};
  50364. const attributes = gl.getContextAttributes();
  50365. let initialRenderTarget = null;
  50366. let newRenderTarget = null;
  50367. const controllers = [];
  50368. const controllerInputSources = [];
  50369. const currentSize = new Vector2();
  50370. let currentPixelRatio = null;
  50371. //
  50372. const cameraL = new PerspectiveCamera();
  50373. cameraL.viewport = new Vector4();
  50374. const cameraR = new PerspectiveCamera();
  50375. cameraR.viewport = new Vector4();
  50376. const cameras = [ cameraL, cameraR ];
  50377. const cameraXR = new ArrayCamera();
  50378. let _currentDepthNear = null;
  50379. let _currentDepthFar = null;
  50380. //
  50381. /**
  50382. * Whether the manager's XR camera should be automatically updated or not.
  50383. *
  50384. * @type {boolean}
  50385. * @default true
  50386. */
  50387. this.cameraAutoUpdate = true;
  50388. /**
  50389. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  50390. * if you are going to use XR in your app.
  50391. *
  50392. * @type {boolean}
  50393. * @default false
  50394. */
  50395. this.enabled = false;
  50396. /**
  50397. * Whether XR presentation is active or not.
  50398. *
  50399. * @type {boolean}
  50400. * @readonly
  50401. * @default false
  50402. */
  50403. this.isPresenting = false;
  50404. /**
  50405. * Returns a group representing the `target ray` space of the XR controller.
  50406. * Use this space for visualizing 3D objects that support the user in pointing
  50407. * tasks like UI interaction.
  50408. *
  50409. * @param {number} index - The index of the controller.
  50410. * @return {Group} A group representing the `target ray` space.
  50411. */
  50412. this.getController = function ( index ) {
  50413. let controller = controllers[ index ];
  50414. if ( controller === undefined ) {
  50415. controller = new WebXRController();
  50416. controllers[ index ] = controller;
  50417. }
  50418. return controller.getTargetRaySpace();
  50419. };
  50420. /**
  50421. * Returns a group representing the `grip` space of the XR controller.
  50422. * Use this space for visualizing 3D objects that support the user in pointing
  50423. * tasks like UI interaction.
  50424. *
  50425. * Note: If you want to show something in the user's hand AND offer a
  50426. * pointing ray at the same time, you'll want to attached the handheld object
  50427. * to the group returned by `getControllerGrip()` and the ray to the
  50428. * group returned by `getController()`. The idea is to have two
  50429. * different groups in two different coordinate spaces for the same WebXR
  50430. * controller.
  50431. *
  50432. * @param {number} index - The index of the controller.
  50433. * @return {Group} A group representing the `grip` space.
  50434. */
  50435. this.getControllerGrip = function ( index ) {
  50436. let controller = controllers[ index ];
  50437. if ( controller === undefined ) {
  50438. controller = new WebXRController();
  50439. controllers[ index ] = controller;
  50440. }
  50441. return controller.getGripSpace();
  50442. };
  50443. /**
  50444. * Returns a group representing the `hand` space of the XR controller.
  50445. * Use this space for visualizing 3D objects that support the user in pointing
  50446. * tasks like UI interaction.
  50447. *
  50448. * @param {number} index - The index of the controller.
  50449. * @return {Group} A group representing the `hand` space.
  50450. */
  50451. this.getHand = function ( index ) {
  50452. let controller = controllers[ index ];
  50453. if ( controller === undefined ) {
  50454. controller = new WebXRController();
  50455. controllers[ index ] = controller;
  50456. }
  50457. return controller.getHandSpace();
  50458. };
  50459. //
  50460. function onSessionEvent( event ) {
  50461. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  50462. if ( controllerIndex === -1 ) {
  50463. return;
  50464. }
  50465. const controller = controllers[ controllerIndex ];
  50466. if ( controller !== undefined ) {
  50467. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  50468. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  50469. }
  50470. }
  50471. function onSessionEnd() {
  50472. session.removeEventListener( 'select', onSessionEvent );
  50473. session.removeEventListener( 'selectstart', onSessionEvent );
  50474. session.removeEventListener( 'selectend', onSessionEvent );
  50475. session.removeEventListener( 'squeeze', onSessionEvent );
  50476. session.removeEventListener( 'squeezestart', onSessionEvent );
  50477. session.removeEventListener( 'squeezeend', onSessionEvent );
  50478. session.removeEventListener( 'end', onSessionEnd );
  50479. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  50480. for ( let i = 0; i < controllers.length; i ++ ) {
  50481. const inputSource = controllerInputSources[ i ];
  50482. if ( inputSource === null ) continue;
  50483. controllerInputSources[ i ] = null;
  50484. controllers[ i ].disconnect( inputSource );
  50485. }
  50486. _currentDepthNear = null;
  50487. _currentDepthFar = null;
  50488. depthSensing.reset();
  50489. for ( const key in cameraAccessTextures ) {
  50490. delete cameraAccessTextures[ key ];
  50491. }
  50492. // restore framebuffer/rendering state
  50493. renderer.setRenderTarget( initialRenderTarget );
  50494. glBaseLayer = null;
  50495. glProjLayer = null;
  50496. glBinding = null;
  50497. session = null;
  50498. newRenderTarget = null;
  50499. //
  50500. animation.stop();
  50501. scope.isPresenting = false;
  50502. renderer.setPixelRatio( currentPixelRatio );
  50503. renderer.setSize( currentSize.width, currentSize.height, false );
  50504. scope.dispatchEvent( { type: 'sessionend' } );
  50505. }
  50506. /**
  50507. * Sets the framebuffer scale factor.
  50508. *
  50509. * This method can not be used during a XR session.
  50510. *
  50511. * @param {number} value - The framebuffer scale factor.
  50512. */
  50513. this.setFramebufferScaleFactor = function ( value ) {
  50514. framebufferScaleFactor = value;
  50515. if ( scope.isPresenting === true ) {
  50516. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  50517. }
  50518. };
  50519. /**
  50520. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  50521. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  50522. * improve tracking. Default is `local-floor`. Valid values can be found here
  50523. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  50524. *
  50525. * This method can not be used during a XR session.
  50526. *
  50527. * @param {string} value - The reference space type.
  50528. */
  50529. this.setReferenceSpaceType = function ( value ) {
  50530. referenceSpaceType = value;
  50531. if ( scope.isPresenting === true ) {
  50532. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  50533. }
  50534. };
  50535. /**
  50536. * Returns the XR reference space.
  50537. *
  50538. * @return {XRReferenceSpace} The XR reference space.
  50539. */
  50540. this.getReferenceSpace = function () {
  50541. return customReferenceSpace || referenceSpace;
  50542. };
  50543. /**
  50544. * Sets a custom XR reference space.
  50545. *
  50546. * @param {XRReferenceSpace} space - The XR reference space.
  50547. */
  50548. this.setReferenceSpace = function ( space ) {
  50549. customReferenceSpace = space;
  50550. };
  50551. /**
  50552. * Returns the current base layer.
  50553. *
  50554. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  50555. */
  50556. this.getBaseLayer = function () {
  50557. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  50558. };
  50559. /**
  50560. * Returns the current XR binding.
  50561. *
  50562. * @return {?XRWebGLBinding} The XR binding.
  50563. */
  50564. this.getBinding = function () {
  50565. return glBinding;
  50566. };
  50567. /**
  50568. * Returns the current XR frame.
  50569. *
  50570. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  50571. */
  50572. this.getFrame = function () {
  50573. return xrFrame;
  50574. };
  50575. /**
  50576. * Returns the current XR session.
  50577. *
  50578. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  50579. */
  50580. this.getSession = function () {
  50581. return session;
  50582. };
  50583. /**
  50584. * After a XR session has been requested usually with one of the `*Button` modules, it
  50585. * is injected into the renderer with this method. This method triggers the start of
  50586. * the actual XR rendering.
  50587. *
  50588. * @async
  50589. * @param {XRSession} value - The XR session to set.
  50590. * @return {Promise} A Promise that resolves when the session has been set.
  50591. */
  50592. this.setSession = async function ( value ) {
  50593. session = value;
  50594. if ( session !== null ) {
  50595. initialRenderTarget = renderer.getRenderTarget();
  50596. session.addEventListener( 'select', onSessionEvent );
  50597. session.addEventListener( 'selectstart', onSessionEvent );
  50598. session.addEventListener( 'selectend', onSessionEvent );
  50599. session.addEventListener( 'squeeze', onSessionEvent );
  50600. session.addEventListener( 'squeezestart', onSessionEvent );
  50601. session.addEventListener( 'squeezeend', onSessionEvent );
  50602. session.addEventListener( 'end', onSessionEnd );
  50603. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  50604. if ( attributes.xrCompatible !== true ) {
  50605. await gl.makeXRCompatible();
  50606. }
  50607. currentPixelRatio = renderer.getPixelRatio();
  50608. renderer.getSize( currentSize );
  50609. if ( typeof XRWebGLBinding !== 'undefined' ) {
  50610. glBinding = new XRWebGLBinding( session, gl );
  50611. }
  50612. // Check that the browser implements the necessary APIs to use an
  50613. // XRProjectionLayer rather than an XRWebGLLayer
  50614. const useLayers = glBinding !== null && 'createProjectionLayer' in XRWebGLBinding.prototype;
  50615. if ( ! useLayers ) {
  50616. const layerInit = {
  50617. antialias: attributes.antialias,
  50618. alpha: true,
  50619. depth: attributes.depth,
  50620. stencil: attributes.stencil,
  50621. framebufferScaleFactor: framebufferScaleFactor
  50622. };
  50623. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  50624. session.updateRenderState( { baseLayer: glBaseLayer } );
  50625. renderer.setPixelRatio( 1 );
  50626. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  50627. newRenderTarget = new WebGLRenderTarget(
  50628. glBaseLayer.framebufferWidth,
  50629. glBaseLayer.framebufferHeight,
  50630. {
  50631. format: RGBAFormat,
  50632. type: UnsignedByteType,
  50633. colorSpace: renderer.outputColorSpace,
  50634. stencilBuffer: attributes.stencil,
  50635. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  50636. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  50637. }
  50638. );
  50639. } else {
  50640. let depthFormat = null;
  50641. let depthType = null;
  50642. let glDepthFormat = null;
  50643. if ( attributes.depth ) {
  50644. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50645. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  50646. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  50647. }
  50648. const projectionlayerInit = {
  50649. colorFormat: gl.RGBA8,
  50650. depthFormat: glDepthFormat,
  50651. scaleFactor: framebufferScaleFactor
  50652. };
  50653. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  50654. session.updateRenderState( { layers: [ glProjLayer ] } );
  50655. renderer.setPixelRatio( 1 );
  50656. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  50657. newRenderTarget = new WebGLRenderTarget(
  50658. glProjLayer.textureWidth,
  50659. glProjLayer.textureHeight,
  50660. {
  50661. format: RGBAFormat,
  50662. type: UnsignedByteType,
  50663. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  50664. stencilBuffer: attributes.stencil,
  50665. colorSpace: renderer.outputColorSpace,
  50666. samples: attributes.antialias ? 4 : 0,
  50667. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  50668. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  50669. } );
  50670. }
  50671. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  50672. this.setFoveation( foveation );
  50673. customReferenceSpace = null;
  50674. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  50675. animation.setContext( session );
  50676. animation.start();
  50677. scope.isPresenting = true;
  50678. scope.dispatchEvent( { type: 'sessionstart' } );
  50679. }
  50680. };
  50681. /**
  50682. * Returns the environment blend mode from the current XR session.
  50683. *
  50684. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  50685. */
  50686. this.getEnvironmentBlendMode = function () {
  50687. if ( session !== null ) {
  50688. return session.environmentBlendMode;
  50689. }
  50690. };
  50691. /**
  50692. * Returns the current depth texture computed via depth sensing.
  50693. *
  50694. * @return {?Texture} The depth texture.
  50695. */
  50696. this.getDepthTexture = function () {
  50697. return depthSensing.getDepthTexture();
  50698. };
  50699. function onInputSourcesChange( event ) {
  50700. // Notify disconnected
  50701. for ( let i = 0; i < event.removed.length; i ++ ) {
  50702. const inputSource = event.removed[ i ];
  50703. const index = controllerInputSources.indexOf( inputSource );
  50704. if ( index >= 0 ) {
  50705. controllerInputSources[ index ] = null;
  50706. controllers[ index ].disconnect( inputSource );
  50707. }
  50708. }
  50709. // Notify connected
  50710. for ( let i = 0; i < event.added.length; i ++ ) {
  50711. const inputSource = event.added[ i ];
  50712. let controllerIndex = controllerInputSources.indexOf( inputSource );
  50713. if ( controllerIndex === -1 ) {
  50714. // Assign input source a controller that currently has no input source
  50715. for ( let i = 0; i < controllers.length; i ++ ) {
  50716. if ( i >= controllerInputSources.length ) {
  50717. controllerInputSources.push( inputSource );
  50718. controllerIndex = i;
  50719. break;
  50720. } else if ( controllerInputSources[ i ] === null ) {
  50721. controllerInputSources[ i ] = inputSource;
  50722. controllerIndex = i;
  50723. break;
  50724. }
  50725. }
  50726. // If all controllers do currently receive input we ignore new ones
  50727. if ( controllerIndex === -1 ) break;
  50728. }
  50729. const controller = controllers[ controllerIndex ];
  50730. if ( controller ) {
  50731. controller.connect( inputSource );
  50732. }
  50733. }
  50734. }
  50735. //
  50736. const cameraLPos = new Vector3();
  50737. const cameraRPos = new Vector3();
  50738. /**
  50739. * Assumes 2 cameras that are parallel and share an X-axis, and that
  50740. * the cameras' projection and world matrices have already been set.
  50741. * And that near and far planes are identical for both cameras.
  50742. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  50743. *
  50744. * @param {ArrayCamera} camera - The camera to update.
  50745. * @param {PerspectiveCamera} cameraL - The left camera.
  50746. * @param {PerspectiveCamera} cameraR - The right camera.
  50747. */
  50748. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  50749. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  50750. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  50751. const ipd = cameraLPos.distanceTo( cameraRPos );
  50752. const projL = cameraL.projectionMatrix.elements;
  50753. const projR = cameraR.projectionMatrix.elements;
  50754. // VR systems will have identical far and near planes, and
  50755. // most likely identical top and bottom frustum extents.
  50756. // Use the left camera for these values.
  50757. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  50758. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  50759. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  50760. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  50761. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  50762. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  50763. const left = near * leftFov;
  50764. const right = near * rightFov;
  50765. // Calculate the new camera's position offset from the
  50766. // left camera. xOffset should be roughly half `ipd`.
  50767. const zOffset = ipd / ( - leftFov + rightFov );
  50768. const xOffset = zOffset * - leftFov;
  50769. // TODO: Better way to apply this offset?
  50770. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  50771. camera.translateX( xOffset );
  50772. camera.translateZ( zOffset );
  50773. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  50774. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50775. // Check if the projection uses an infinite far plane.
  50776. if ( projL[ 10 ] === -1 ) {
  50777. // Use the projection matrix from the left eye.
  50778. // The camera offset is sufficient to include the view volumes
  50779. // of both eyes (assuming symmetric projections).
  50780. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  50781. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  50782. } else {
  50783. // Find the union of the frustum values of the cameras and scale
  50784. // the values so that the near plane's position does not change in world space,
  50785. // although must now be relative to the new union camera.
  50786. const near2 = near + zOffset;
  50787. const far2 = far + zOffset;
  50788. const left2 = left - xOffset;
  50789. const right2 = right + ( ipd - xOffset );
  50790. const top2 = topFov * far / far2 * near2;
  50791. const bottom2 = bottomFov * far / far2 * near2;
  50792. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  50793. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50794. }
  50795. }
  50796. function updateCamera( camera, parent ) {
  50797. if ( parent === null ) {
  50798. camera.matrixWorld.copy( camera.matrix );
  50799. } else {
  50800. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  50801. }
  50802. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50803. }
  50804. /**
  50805. * Updates the state of the XR camera. Use this method on app level if you
  50806. * set cameraAutoUpdate` to `false`. The method requires the non-XR
  50807. * camera of the scene as a parameter. The passed in camera's transformation
  50808. * is automatically adjusted to the position of the XR camera when calling
  50809. * this method.
  50810. *
  50811. * @param {Camera} camera - The camera.
  50812. */
  50813. this.updateCamera = function ( camera ) {
  50814. if ( session === null ) return;
  50815. let depthNear = camera.near;
  50816. let depthFar = camera.far;
  50817. if ( depthSensing.texture !== null ) {
  50818. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  50819. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  50820. }
  50821. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  50822. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  50823. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  50824. // Note that the new renderState won't apply until the next frame. See #18320
  50825. session.updateRenderState( {
  50826. depthNear: cameraXR.near,
  50827. depthFar: cameraXR.far
  50828. } );
  50829. _currentDepthNear = cameraXR.near;
  50830. _currentDepthFar = cameraXR.far;
  50831. }
  50832. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  50833. cameraXR.layers.mask = camera.layers.mask | 0b110;
  50834. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  50835. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  50836. const parent = camera.parent;
  50837. const cameras = cameraXR.cameras;
  50838. updateCamera( cameraXR, parent );
  50839. for ( let i = 0; i < cameras.length; i ++ ) {
  50840. updateCamera( cameras[ i ], parent );
  50841. }
  50842. // update projection matrix for proper view frustum culling
  50843. if ( cameras.length === 2 ) {
  50844. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  50845. } else {
  50846. // assume single camera setup (AR)
  50847. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  50848. }
  50849. // update user camera and its children
  50850. updateUserCamera( camera, cameraXR, parent );
  50851. };
  50852. function updateUserCamera( camera, cameraXR, parent ) {
  50853. if ( parent === null ) {
  50854. camera.matrix.copy( cameraXR.matrixWorld );
  50855. } else {
  50856. camera.matrix.copy( parent.matrixWorld );
  50857. camera.matrix.invert();
  50858. camera.matrix.multiply( cameraXR.matrixWorld );
  50859. }
  50860. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50861. camera.updateMatrixWorld( true );
  50862. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  50863. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  50864. if ( camera.isPerspectiveCamera ) {
  50865. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  50866. camera.zoom = 1;
  50867. }
  50868. }
  50869. /**
  50870. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  50871. * of the active XR session. For each view it holds a separate camera object.
  50872. *
  50873. * The camera's `fov` is currently not used and does not reflect the fov of
  50874. * the XR camera. If you need the fov on app level, you have to compute in
  50875. * manually from the XR camera's projection matrices.
  50876. *
  50877. * @return {ArrayCamera} The XR camera.
  50878. */
  50879. this.getCamera = function () {
  50880. return cameraXR;
  50881. };
  50882. /**
  50883. * Returns the amount of foveation used by the XR compositor for the projection layer.
  50884. *
  50885. * @return {number|undefined} The amount of foveation.
  50886. */
  50887. this.getFoveation = function () {
  50888. if ( glProjLayer === null && glBaseLayer === null ) {
  50889. return undefined;
  50890. }
  50891. return foveation;
  50892. };
  50893. /**
  50894. * Sets the foveation value.
  50895. *
  50896. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  50897. * and `1` means maximum foveation (the edges render at lower resolution).
  50898. */
  50899. this.setFoveation = function ( value ) {
  50900. // 0 = no foveation = full resolution
  50901. // 1 = maximum foveation = the edges render at lower resolution
  50902. foveation = value;
  50903. if ( glProjLayer !== null ) {
  50904. glProjLayer.fixedFoveation = value;
  50905. }
  50906. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  50907. glBaseLayer.fixedFoveation = value;
  50908. }
  50909. };
  50910. /**
  50911. * Returns `true` if depth sensing is supported.
  50912. *
  50913. * @return {boolean} Whether depth sensing is supported or not.
  50914. */
  50915. this.hasDepthSensing = function () {
  50916. return depthSensing.texture !== null;
  50917. };
  50918. /**
  50919. * Returns the depth sensing mesh.
  50920. *
  50921. * @return {Mesh} The depth sensing mesh.
  50922. */
  50923. this.getDepthSensingMesh = function () {
  50924. return depthSensing.getMesh( cameraXR );
  50925. };
  50926. /**
  50927. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  50928. * Only available during the current animation loop.
  50929. *
  50930. * @param {XRCamera} xrCamera - The camera to query.
  50931. * @return {?Texture} An opaque texture representing the current raw camera frame.
  50932. */
  50933. this.getCameraTexture = function ( xrCamera ) {
  50934. return cameraAccessTextures[ xrCamera ];
  50935. };
  50936. // Animation Loop
  50937. let onAnimationFrameCallback = null;
  50938. function onAnimationFrame( time, frame ) {
  50939. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  50940. xrFrame = frame;
  50941. if ( pose !== null ) {
  50942. const views = pose.views;
  50943. if ( glBaseLayer !== null ) {
  50944. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  50945. renderer.setRenderTarget( newRenderTarget );
  50946. }
  50947. let cameraXRNeedsUpdate = false;
  50948. // check if it's necessary to rebuild cameraXR's camera list
  50949. if ( views.length !== cameraXR.cameras.length ) {
  50950. cameraXR.cameras.length = 0;
  50951. cameraXRNeedsUpdate = true;
  50952. }
  50953. for ( let i = 0; i < views.length; i ++ ) {
  50954. const view = views[ i ];
  50955. let viewport = null;
  50956. if ( glBaseLayer !== null ) {
  50957. viewport = glBaseLayer.getViewport( view );
  50958. } else {
  50959. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  50960. viewport = glSubImage.viewport;
  50961. // For side-by-side projection, we only produce a single texture for both eyes.
  50962. if ( i === 0 ) {
  50963. renderer.setRenderTargetTextures(
  50964. newRenderTarget,
  50965. glSubImage.colorTexture,
  50966. glSubImage.depthStencilTexture );
  50967. renderer.setRenderTarget( newRenderTarget );
  50968. }
  50969. }
  50970. let camera = cameras[ i ];
  50971. if ( camera === undefined ) {
  50972. camera = new PerspectiveCamera();
  50973. camera.layers.enable( i );
  50974. camera.viewport = new Vector4();
  50975. cameras[ i ] = camera;
  50976. }
  50977. camera.matrix.fromArray( view.transform.matrix );
  50978. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50979. camera.projectionMatrix.fromArray( view.projectionMatrix );
  50980. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50981. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  50982. if ( i === 0 ) {
  50983. cameraXR.matrix.copy( camera.matrix );
  50984. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  50985. }
  50986. if ( cameraXRNeedsUpdate === true ) {
  50987. cameraXR.cameras.push( camera );
  50988. }
  50989. }
  50990. //
  50991. const enabledFeatures = session.enabledFeatures;
  50992. const gpuDepthSensingEnabled = enabledFeatures &&
  50993. enabledFeatures.includes( 'depth-sensing' ) &&
  50994. session.depthUsage == 'gpu-optimized';
  50995. if ( gpuDepthSensingEnabled && glBinding ) {
  50996. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  50997. if ( depthData && depthData.isValid && depthData.texture ) {
  50998. depthSensing.init( depthData, session.renderState );
  50999. }
  51000. }
  51001. const cameraAccessEnabled = enabledFeatures &&
  51002. enabledFeatures.includes( 'camera-access' );
  51003. if ( cameraAccessEnabled ) {
  51004. renderer.state.unbindTexture();
  51005. if ( glBinding ) {
  51006. for ( let i = 0; i < views.length; i ++ ) {
  51007. const camera = views[ i ].camera;
  51008. if ( camera ) {
  51009. let cameraTex = cameraAccessTextures[ camera ];
  51010. if ( ! cameraTex ) {
  51011. cameraTex = new ExternalTexture();
  51012. cameraAccessTextures[ camera ] = cameraTex;
  51013. }
  51014. const glTexture = glBinding.getCameraImage( camera );
  51015. cameraTex.sourceTexture = glTexture;
  51016. }
  51017. }
  51018. }
  51019. }
  51020. }
  51021. //
  51022. for ( let i = 0; i < controllers.length; i ++ ) {
  51023. const inputSource = controllerInputSources[ i ];
  51024. const controller = controllers[ i ];
  51025. if ( inputSource !== null && controller !== undefined ) {
  51026. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51027. }
  51028. }
  51029. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51030. if ( frame.detectedPlanes ) {
  51031. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51032. }
  51033. xrFrame = null;
  51034. }
  51035. const animation = new WebGLAnimation();
  51036. animation.setAnimationLoop( onAnimationFrame );
  51037. this.setAnimationLoop = function ( callback ) {
  51038. onAnimationFrameCallback = callback;
  51039. };
  51040. this.dispose = function () {};
  51041. }
  51042. }
  51043. const _e1 = /*@__PURE__*/ new Euler();
  51044. const _m1 = /*@__PURE__*/ new Matrix4();
  51045. function WebGLMaterials( renderer, properties ) {
  51046. function refreshTransformUniform( map, uniform ) {
  51047. if ( map.matrixAutoUpdate === true ) {
  51048. map.updateMatrix();
  51049. }
  51050. uniform.value.copy( map.matrix );
  51051. }
  51052. function refreshFogUniforms( uniforms, fog ) {
  51053. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51054. if ( fog.isFog ) {
  51055. uniforms.fogNear.value = fog.near;
  51056. uniforms.fogFar.value = fog.far;
  51057. } else if ( fog.isFogExp2 ) {
  51058. uniforms.fogDensity.value = fog.density;
  51059. }
  51060. }
  51061. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51062. if ( material.isMeshBasicMaterial ) {
  51063. refreshUniformsCommon( uniforms, material );
  51064. } else if ( material.isMeshLambertMaterial ) {
  51065. refreshUniformsCommon( uniforms, material );
  51066. } else if ( material.isMeshToonMaterial ) {
  51067. refreshUniformsCommon( uniforms, material );
  51068. refreshUniformsToon( uniforms, material );
  51069. } else if ( material.isMeshPhongMaterial ) {
  51070. refreshUniformsCommon( uniforms, material );
  51071. refreshUniformsPhong( uniforms, material );
  51072. } else if ( material.isMeshStandardMaterial ) {
  51073. refreshUniformsCommon( uniforms, material );
  51074. refreshUniformsStandard( uniforms, material );
  51075. if ( material.isMeshPhysicalMaterial ) {
  51076. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51077. }
  51078. } else if ( material.isMeshMatcapMaterial ) {
  51079. refreshUniformsCommon( uniforms, material );
  51080. refreshUniformsMatcap( uniforms, material );
  51081. } else if ( material.isMeshDepthMaterial ) {
  51082. refreshUniformsCommon( uniforms, material );
  51083. } else if ( material.isMeshDistanceMaterial ) {
  51084. refreshUniformsCommon( uniforms, material );
  51085. refreshUniformsDistance( uniforms, material );
  51086. } else if ( material.isMeshNormalMaterial ) {
  51087. refreshUniformsCommon( uniforms, material );
  51088. } else if ( material.isLineBasicMaterial ) {
  51089. refreshUniformsLine( uniforms, material );
  51090. if ( material.isLineDashedMaterial ) {
  51091. refreshUniformsDash( uniforms, material );
  51092. }
  51093. } else if ( material.isPointsMaterial ) {
  51094. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51095. } else if ( material.isSpriteMaterial ) {
  51096. refreshUniformsSprites( uniforms, material );
  51097. } else if ( material.isShadowMaterial ) {
  51098. uniforms.color.value.copy( material.color );
  51099. uniforms.opacity.value = material.opacity;
  51100. } else if ( material.isShaderMaterial ) {
  51101. material.uniformsNeedUpdate = false; // #15581
  51102. }
  51103. }
  51104. function refreshUniformsCommon( uniforms, material ) {
  51105. uniforms.opacity.value = material.opacity;
  51106. if ( material.color ) {
  51107. uniforms.diffuse.value.copy( material.color );
  51108. }
  51109. if ( material.emissive ) {
  51110. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51111. }
  51112. if ( material.map ) {
  51113. uniforms.map.value = material.map;
  51114. refreshTransformUniform( material.map, uniforms.mapTransform );
  51115. }
  51116. if ( material.alphaMap ) {
  51117. uniforms.alphaMap.value = material.alphaMap;
  51118. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51119. }
  51120. if ( material.bumpMap ) {
  51121. uniforms.bumpMap.value = material.bumpMap;
  51122. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51123. uniforms.bumpScale.value = material.bumpScale;
  51124. if ( material.side === BackSide ) {
  51125. uniforms.bumpScale.value *= -1;
  51126. }
  51127. }
  51128. if ( material.normalMap ) {
  51129. uniforms.normalMap.value = material.normalMap;
  51130. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51131. uniforms.normalScale.value.copy( material.normalScale );
  51132. if ( material.side === BackSide ) {
  51133. uniforms.normalScale.value.negate();
  51134. }
  51135. }
  51136. if ( material.displacementMap ) {
  51137. uniforms.displacementMap.value = material.displacementMap;
  51138. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51139. uniforms.displacementScale.value = material.displacementScale;
  51140. uniforms.displacementBias.value = material.displacementBias;
  51141. }
  51142. if ( material.emissiveMap ) {
  51143. uniforms.emissiveMap.value = material.emissiveMap;
  51144. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51145. }
  51146. if ( material.specularMap ) {
  51147. uniforms.specularMap.value = material.specularMap;
  51148. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51149. }
  51150. if ( material.alphaTest > 0 ) {
  51151. uniforms.alphaTest.value = material.alphaTest;
  51152. }
  51153. const materialProperties = properties.get( material );
  51154. const envMap = materialProperties.envMap;
  51155. const envMapRotation = materialProperties.envMapRotation;
  51156. if ( envMap ) {
  51157. uniforms.envMap.value = envMap;
  51158. _e1.copy( envMapRotation );
  51159. // accommodate left-handed frame
  51160. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51161. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51162. // environment maps which are not cube render targets or PMREMs follow a different convention
  51163. _e1.y *= -1;
  51164. _e1.z *= -1;
  51165. }
  51166. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51167. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51168. uniforms.reflectivity.value = material.reflectivity;
  51169. uniforms.ior.value = material.ior;
  51170. uniforms.refractionRatio.value = material.refractionRatio;
  51171. }
  51172. if ( material.lightMap ) {
  51173. uniforms.lightMap.value = material.lightMap;
  51174. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51175. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51176. }
  51177. if ( material.aoMap ) {
  51178. uniforms.aoMap.value = material.aoMap;
  51179. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51180. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51181. }
  51182. }
  51183. function refreshUniformsLine( uniforms, material ) {
  51184. uniforms.diffuse.value.copy( material.color );
  51185. uniforms.opacity.value = material.opacity;
  51186. if ( material.map ) {
  51187. uniforms.map.value = material.map;
  51188. refreshTransformUniform( material.map, uniforms.mapTransform );
  51189. }
  51190. }
  51191. function refreshUniformsDash( uniforms, material ) {
  51192. uniforms.dashSize.value = material.dashSize;
  51193. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51194. uniforms.scale.value = material.scale;
  51195. }
  51196. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51197. uniforms.diffuse.value.copy( material.color );
  51198. uniforms.opacity.value = material.opacity;
  51199. uniforms.size.value = material.size * pixelRatio;
  51200. uniforms.scale.value = height * 0.5;
  51201. if ( material.map ) {
  51202. uniforms.map.value = material.map;
  51203. refreshTransformUniform( material.map, uniforms.uvTransform );
  51204. }
  51205. if ( material.alphaMap ) {
  51206. uniforms.alphaMap.value = material.alphaMap;
  51207. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51208. }
  51209. if ( material.alphaTest > 0 ) {
  51210. uniforms.alphaTest.value = material.alphaTest;
  51211. }
  51212. }
  51213. function refreshUniformsSprites( uniforms, material ) {
  51214. uniforms.diffuse.value.copy( material.color );
  51215. uniforms.opacity.value = material.opacity;
  51216. uniforms.rotation.value = material.rotation;
  51217. if ( material.map ) {
  51218. uniforms.map.value = material.map;
  51219. refreshTransformUniform( material.map, uniforms.mapTransform );
  51220. }
  51221. if ( material.alphaMap ) {
  51222. uniforms.alphaMap.value = material.alphaMap;
  51223. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51224. }
  51225. if ( material.alphaTest > 0 ) {
  51226. uniforms.alphaTest.value = material.alphaTest;
  51227. }
  51228. }
  51229. function refreshUniformsPhong( uniforms, material ) {
  51230. uniforms.specular.value.copy( material.specular );
  51231. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51232. }
  51233. function refreshUniformsToon( uniforms, material ) {
  51234. if ( material.gradientMap ) {
  51235. uniforms.gradientMap.value = material.gradientMap;
  51236. }
  51237. }
  51238. function refreshUniformsStandard( uniforms, material ) {
  51239. uniforms.metalness.value = material.metalness;
  51240. if ( material.metalnessMap ) {
  51241. uniforms.metalnessMap.value = material.metalnessMap;
  51242. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51243. }
  51244. uniforms.roughness.value = material.roughness;
  51245. if ( material.roughnessMap ) {
  51246. uniforms.roughnessMap.value = material.roughnessMap;
  51247. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51248. }
  51249. if ( material.envMap ) {
  51250. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51251. uniforms.envMapIntensity.value = material.envMapIntensity;
  51252. }
  51253. }
  51254. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  51255. uniforms.ior.value = material.ior; // also part of uniforms common
  51256. if ( material.sheen > 0 ) {
  51257. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  51258. uniforms.sheenRoughness.value = material.sheenRoughness;
  51259. if ( material.sheenColorMap ) {
  51260. uniforms.sheenColorMap.value = material.sheenColorMap;
  51261. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  51262. }
  51263. if ( material.sheenRoughnessMap ) {
  51264. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  51265. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  51266. }
  51267. }
  51268. if ( material.clearcoat > 0 ) {
  51269. uniforms.clearcoat.value = material.clearcoat;
  51270. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  51271. if ( material.clearcoatMap ) {
  51272. uniforms.clearcoatMap.value = material.clearcoatMap;
  51273. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  51274. }
  51275. if ( material.clearcoatRoughnessMap ) {
  51276. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  51277. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  51278. }
  51279. if ( material.clearcoatNormalMap ) {
  51280. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  51281. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  51282. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  51283. if ( material.side === BackSide ) {
  51284. uniforms.clearcoatNormalScale.value.negate();
  51285. }
  51286. }
  51287. }
  51288. if ( material.dispersion > 0 ) {
  51289. uniforms.dispersion.value = material.dispersion;
  51290. }
  51291. if ( material.iridescence > 0 ) {
  51292. uniforms.iridescence.value = material.iridescence;
  51293. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  51294. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  51295. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  51296. if ( material.iridescenceMap ) {
  51297. uniforms.iridescenceMap.value = material.iridescenceMap;
  51298. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  51299. }
  51300. if ( material.iridescenceThicknessMap ) {
  51301. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  51302. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  51303. }
  51304. }
  51305. if ( material.transmission > 0 ) {
  51306. uniforms.transmission.value = material.transmission;
  51307. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  51308. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  51309. if ( material.transmissionMap ) {
  51310. uniforms.transmissionMap.value = material.transmissionMap;
  51311. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  51312. }
  51313. uniforms.thickness.value = material.thickness;
  51314. if ( material.thicknessMap ) {
  51315. uniforms.thicknessMap.value = material.thicknessMap;
  51316. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  51317. }
  51318. uniforms.attenuationDistance.value = material.attenuationDistance;
  51319. uniforms.attenuationColor.value.copy( material.attenuationColor );
  51320. }
  51321. if ( material.anisotropy > 0 ) {
  51322. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  51323. if ( material.anisotropyMap ) {
  51324. uniforms.anisotropyMap.value = material.anisotropyMap;
  51325. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  51326. }
  51327. }
  51328. uniforms.specularIntensity.value = material.specularIntensity;
  51329. uniforms.specularColor.value.copy( material.specularColor );
  51330. if ( material.specularColorMap ) {
  51331. uniforms.specularColorMap.value = material.specularColorMap;
  51332. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  51333. }
  51334. if ( material.specularIntensityMap ) {
  51335. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  51336. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  51337. }
  51338. }
  51339. function refreshUniformsMatcap( uniforms, material ) {
  51340. if ( material.matcap ) {
  51341. uniforms.matcap.value = material.matcap;
  51342. }
  51343. }
  51344. function refreshUniformsDistance( uniforms, material ) {
  51345. const light = properties.get( material ).light;
  51346. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  51347. uniforms.nearDistance.value = light.shadow.camera.near;
  51348. uniforms.farDistance.value = light.shadow.camera.far;
  51349. }
  51350. return {
  51351. refreshFogUniforms: refreshFogUniforms,
  51352. refreshMaterialUniforms: refreshMaterialUniforms
  51353. };
  51354. }
  51355. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  51356. let buffers = {};
  51357. let updateList = {};
  51358. let allocatedBindingPoints = [];
  51359. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  51360. function bind( uniformsGroup, program ) {
  51361. const webglProgram = program.program;
  51362. state.uniformBlockBinding( uniformsGroup, webglProgram );
  51363. }
  51364. function update( uniformsGroup, program ) {
  51365. let buffer = buffers[ uniformsGroup.id ];
  51366. if ( buffer === undefined ) {
  51367. prepareUniformsGroup( uniformsGroup );
  51368. buffer = createBuffer( uniformsGroup );
  51369. buffers[ uniformsGroup.id ] = buffer;
  51370. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  51371. }
  51372. // ensure to update the binding points/block indices mapping for this program
  51373. const webglProgram = program.program;
  51374. state.updateUBOMapping( uniformsGroup, webglProgram );
  51375. // update UBO once per frame
  51376. const frame = info.render.frame;
  51377. if ( updateList[ uniformsGroup.id ] !== frame ) {
  51378. updateBufferData( uniformsGroup );
  51379. updateList[ uniformsGroup.id ] = frame;
  51380. }
  51381. }
  51382. function createBuffer( uniformsGroup ) {
  51383. // the setup of an UBO is independent of a particular shader program but global
  51384. const bindingPointIndex = allocateBindingPointIndex();
  51385. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  51386. const buffer = gl.createBuffer();
  51387. const size = uniformsGroup.__size;
  51388. const usage = uniformsGroup.usage;
  51389. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51390. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  51391. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51392. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  51393. return buffer;
  51394. }
  51395. function allocateBindingPointIndex() {
  51396. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  51397. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  51398. allocatedBindingPoints.push( i );
  51399. return i;
  51400. }
  51401. }
  51402. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  51403. return 0;
  51404. }
  51405. function updateBufferData( uniformsGroup ) {
  51406. const buffer = buffers[ uniformsGroup.id ];
  51407. const uniforms = uniformsGroup.uniforms;
  51408. const cache = uniformsGroup.__cache;
  51409. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51410. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  51411. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51412. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51413. const uniform = uniformArray[ j ];
  51414. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  51415. const offset = uniform.__offset;
  51416. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51417. let arrayOffset = 0;
  51418. for ( let k = 0; k < values.length; k ++ ) {
  51419. const value = values[ k ];
  51420. const info = getUniformSize( value );
  51421. // TODO add integer and struct support
  51422. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51423. uniform.__data[ 0 ] = value;
  51424. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  51425. } else if ( value.isMatrix3 ) {
  51426. // manually converting 3x3 to 3x4
  51427. uniform.__data[ 0 ] = value.elements[ 0 ];
  51428. uniform.__data[ 1 ] = value.elements[ 1 ];
  51429. uniform.__data[ 2 ] = value.elements[ 2 ];
  51430. uniform.__data[ 3 ] = 0;
  51431. uniform.__data[ 4 ] = value.elements[ 3 ];
  51432. uniform.__data[ 5 ] = value.elements[ 4 ];
  51433. uniform.__data[ 6 ] = value.elements[ 5 ];
  51434. uniform.__data[ 7 ] = 0;
  51435. uniform.__data[ 8 ] = value.elements[ 6 ];
  51436. uniform.__data[ 9 ] = value.elements[ 7 ];
  51437. uniform.__data[ 10 ] = value.elements[ 8 ];
  51438. uniform.__data[ 11 ] = 0;
  51439. } else {
  51440. value.toArray( uniform.__data, arrayOffset );
  51441. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  51442. }
  51443. }
  51444. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  51445. }
  51446. }
  51447. }
  51448. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51449. }
  51450. function hasUniformChanged( uniform, index, indexArray, cache ) {
  51451. const value = uniform.value;
  51452. const indexString = index + '_' + indexArray;
  51453. if ( cache[ indexString ] === undefined ) {
  51454. // cache entry does not exist so far
  51455. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51456. cache[ indexString ] = value;
  51457. } else {
  51458. cache[ indexString ] = value.clone();
  51459. }
  51460. return true;
  51461. } else {
  51462. const cachedObject = cache[ indexString ];
  51463. // compare current value with cached entry
  51464. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51465. if ( cachedObject !== value ) {
  51466. cache[ indexString ] = value;
  51467. return true;
  51468. }
  51469. } else {
  51470. if ( cachedObject.equals( value ) === false ) {
  51471. cachedObject.copy( value );
  51472. return true;
  51473. }
  51474. }
  51475. }
  51476. return false;
  51477. }
  51478. function prepareUniformsGroup( uniformsGroup ) {
  51479. // determine total buffer size according to the STD140 layout
  51480. // Hint: STD140 is the only supported layout in WebGL 2
  51481. const uniforms = uniformsGroup.uniforms;
  51482. let offset = 0; // global buffer offset in bytes
  51483. const chunkSize = 16; // size of a chunk in bytes
  51484. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  51485. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51486. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51487. const uniform = uniformArray[ j ];
  51488. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51489. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  51490. const value = values[ k ];
  51491. const info = getUniformSize( value );
  51492. const chunkOffset = offset % chunkSize; // offset in the current chunk
  51493. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  51494. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  51495. offset += chunkPadding;
  51496. // Check for chunk overflow
  51497. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  51498. // Add padding and adjust offset
  51499. offset += ( chunkSize - chunkStart );
  51500. }
  51501. // the following two properties will be used for partial buffer updates
  51502. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  51503. uniform.__offset = offset;
  51504. // Update the global offset
  51505. offset += info.storage;
  51506. }
  51507. }
  51508. }
  51509. // ensure correct final padding
  51510. const chunkOffset = offset % chunkSize;
  51511. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  51512. //
  51513. uniformsGroup.__size = offset;
  51514. uniformsGroup.__cache = {};
  51515. return this;
  51516. }
  51517. function getUniformSize( value ) {
  51518. const info = {
  51519. boundary: 0, // bytes
  51520. storage: 0 // bytes
  51521. };
  51522. // determine sizes according to STD140
  51523. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51524. // float/int/bool
  51525. info.boundary = 4;
  51526. info.storage = 4;
  51527. } else if ( value.isVector2 ) {
  51528. // vec2
  51529. info.boundary = 8;
  51530. info.storage = 8;
  51531. } else if ( value.isVector3 || value.isColor ) {
  51532. // vec3
  51533. info.boundary = 16;
  51534. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  51535. } else if ( value.isVector4 ) {
  51536. // vec4
  51537. info.boundary = 16;
  51538. info.storage = 16;
  51539. } else if ( value.isMatrix3 ) {
  51540. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  51541. info.boundary = 48;
  51542. info.storage = 48;
  51543. } else if ( value.isMatrix4 ) {
  51544. // mat4
  51545. info.boundary = 64;
  51546. info.storage = 64;
  51547. } else if ( value.isTexture ) {
  51548. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  51549. } else {
  51550. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  51551. }
  51552. return info;
  51553. }
  51554. function onUniformsGroupsDispose( event ) {
  51555. const uniformsGroup = event.target;
  51556. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  51557. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  51558. allocatedBindingPoints.splice( index, 1 );
  51559. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  51560. delete buffers[ uniformsGroup.id ];
  51561. delete updateList[ uniformsGroup.id ];
  51562. }
  51563. function dispose() {
  51564. for ( const id in buffers ) {
  51565. gl.deleteBuffer( buffers[ id ] );
  51566. }
  51567. allocatedBindingPoints = [];
  51568. buffers = {};
  51569. updateList = {};
  51570. }
  51571. return {
  51572. bind: bind,
  51573. update: update,
  51574. dispose: dispose
  51575. };
  51576. }
  51577. /**
  51578. * This renderer uses WebGL 2 to display scenes.
  51579. *
  51580. * WebGL 1 is not supported since `r163`.
  51581. */
  51582. class WebGLRenderer {
  51583. /**
  51584. * Constructs a new WebGL renderer.
  51585. *
  51586. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  51587. */
  51588. constructor( parameters = {} ) {
  51589. const {
  51590. canvas = createCanvasElement(),
  51591. context = null,
  51592. depth = true,
  51593. stencil = false,
  51594. alpha = false,
  51595. antialias = false,
  51596. premultipliedAlpha = true,
  51597. preserveDrawingBuffer = false,
  51598. powerPreference = 'default',
  51599. failIfMajorPerformanceCaveat = false,
  51600. reversedDepthBuffer = false,
  51601. } = parameters;
  51602. /**
  51603. * This flag can be used for type testing.
  51604. *
  51605. * @type {boolean}
  51606. * @readonly
  51607. * @default true
  51608. */
  51609. this.isWebGLRenderer = true;
  51610. let _alpha;
  51611. if ( context !== null ) {
  51612. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  51613. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  51614. }
  51615. _alpha = context.getContextAttributes().alpha;
  51616. } else {
  51617. _alpha = alpha;
  51618. }
  51619. const uintClearColor = new Uint32Array( 4 );
  51620. const intClearColor = new Int32Array( 4 );
  51621. let currentRenderList = null;
  51622. let currentRenderState = null;
  51623. // render() can be called from within a callback triggered by another render.
  51624. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  51625. const renderListStack = [];
  51626. const renderStateStack = [];
  51627. // public properties
  51628. /**
  51629. * A canvas where the renderer draws its output.This is automatically created by the renderer
  51630. * in the constructor (if not provided already); you just need to add it to your page like so:
  51631. * ```js
  51632. * document.body.appendChild( renderer.domElement );
  51633. * ```
  51634. *
  51635. * @type {DOMElement}
  51636. */
  51637. this.domElement = canvas;
  51638. /**
  51639. * A object with debug configuration settings.
  51640. *
  51641. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  51642. * checked for errors during compilation and linkage process. It may be useful to disable
  51643. * this check in production for performance gain. It is strongly recommended to keep these
  51644. * checks enabled during development. If the shader does not compile and link - it will not
  51645. * work and associated material will not render.
  51646. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  51647. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  51648. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  51649. * Assigning a custom function disables the default error reporting.
  51650. *
  51651. * @type {Object}
  51652. */
  51653. this.debug = {
  51654. /**
  51655. * Enables error checking and reporting when shader programs are being compiled.
  51656. * @type {boolean}
  51657. */
  51658. checkShaderErrors: true,
  51659. /**
  51660. * Callback for custom error reporting.
  51661. * @type {?Function}
  51662. */
  51663. onShaderError: null
  51664. };
  51665. // clearing
  51666. /**
  51667. * Whether the renderer should automatically clear its output before rendering a frame or not.
  51668. *
  51669. * @type {boolean}
  51670. * @default true
  51671. */
  51672. this.autoClear = true;
  51673. /**
  51674. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51675. * the color buffer or not.
  51676. *
  51677. * @type {boolean}
  51678. * @default true
  51679. */
  51680. this.autoClearColor = true;
  51681. /**
  51682. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51683. * the depth buffer or not.
  51684. *
  51685. * @type {boolean}
  51686. * @default true
  51687. */
  51688. this.autoClearDepth = true;
  51689. /**
  51690. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51691. * the stencil buffer or not.
  51692. *
  51693. * @type {boolean}
  51694. * @default true
  51695. */
  51696. this.autoClearStencil = true;
  51697. // scene graph
  51698. /**
  51699. * Whether the renderer should sort objects or not.
  51700. *
  51701. * Note: Sorting is used to attempt to properly render objects that have some
  51702. * degree of transparency. By definition, sorting objects may not work in all
  51703. * cases. Depending on the needs of application, it may be necessary to turn
  51704. * off sorting and use other methods to deal with transparency rendering e.g.
  51705. * manually determining each object's rendering order.
  51706. *
  51707. * @type {boolean}
  51708. * @default true
  51709. */
  51710. this.sortObjects = true;
  51711. // user-defined clipping
  51712. /**
  51713. * User-defined clipping planes specified in world space. These planes apply globally.
  51714. * Points in space whose dot product with the plane is negative are cut away.
  51715. *
  51716. * @type {Array<Plane>}
  51717. */
  51718. this.clippingPlanes = [];
  51719. /**
  51720. * Whether the renderer respects object-level clipping planes or not.
  51721. *
  51722. * @type {boolean}
  51723. * @default false
  51724. */
  51725. this.localClippingEnabled = false;
  51726. // tone mapping
  51727. /**
  51728. * The tone mapping technique of the renderer.
  51729. *
  51730. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  51731. * @default NoToneMapping
  51732. */
  51733. this.toneMapping = NoToneMapping;
  51734. /**
  51735. * Exposure level of tone mapping.
  51736. *
  51737. * @type {number}
  51738. * @default 1
  51739. */
  51740. this.toneMappingExposure = 1.0;
  51741. // transmission
  51742. /**
  51743. * The normalized resolution scale for the transmission render target, measured in percentage
  51744. * of viewport dimensions. Lowering this value can result in significant performance improvements
  51745. * when using {@link MeshPhysicalMaterial#transmission}.
  51746. *
  51747. * @type {number}
  51748. * @default 1
  51749. */
  51750. this.transmissionResolutionScale = 1.0;
  51751. // internal properties
  51752. const _this = this;
  51753. let _isContextLost = false;
  51754. // internal state cache
  51755. this._outputColorSpace = SRGBColorSpace;
  51756. let _currentActiveCubeFace = 0;
  51757. let _currentActiveMipmapLevel = 0;
  51758. let _currentRenderTarget = null;
  51759. let _currentMaterialId = -1;
  51760. let _currentCamera = null;
  51761. const _currentViewport = new Vector4();
  51762. const _currentScissor = new Vector4();
  51763. let _currentScissorTest = null;
  51764. const _currentClearColor = new Color( 0x000000 );
  51765. let _currentClearAlpha = 0;
  51766. //
  51767. let _width = canvas.width;
  51768. let _height = canvas.height;
  51769. let _pixelRatio = 1;
  51770. let _opaqueSort = null;
  51771. let _transparentSort = null;
  51772. const _viewport = new Vector4( 0, 0, _width, _height );
  51773. const _scissor = new Vector4( 0, 0, _width, _height );
  51774. let _scissorTest = false;
  51775. // frustum
  51776. const _frustum = new Frustum();
  51777. // clipping
  51778. let _clippingEnabled = false;
  51779. let _localClippingEnabled = false;
  51780. // camera matrices cache
  51781. const _projScreenMatrix = new Matrix4();
  51782. const _vector3 = new Vector3();
  51783. const _vector4 = new Vector4();
  51784. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  51785. let _renderBackground = false;
  51786. function getTargetPixelRatio() {
  51787. return _currentRenderTarget === null ? _pixelRatio : 1;
  51788. }
  51789. // initialize
  51790. let _gl = context;
  51791. function getContext( contextName, contextAttributes ) {
  51792. return canvas.getContext( contextName, contextAttributes );
  51793. }
  51794. try {
  51795. const contextAttributes = {
  51796. alpha: true,
  51797. depth,
  51798. stencil,
  51799. antialias,
  51800. premultipliedAlpha,
  51801. preserveDrawingBuffer,
  51802. powerPreference,
  51803. failIfMajorPerformanceCaveat,
  51804. };
  51805. // OffscreenCanvas does not have setAttribute, see #22811
  51806. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  51807. // event listeners must be registered before WebGL context is created, see #12753
  51808. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  51809. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  51810. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51811. if ( _gl === null ) {
  51812. const contextName = 'webgl2';
  51813. _gl = getContext( contextName, contextAttributes );
  51814. if ( _gl === null ) {
  51815. if ( getContext( contextName ) ) {
  51816. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  51817. } else {
  51818. throw new Error( 'Error creating WebGL context.' );
  51819. }
  51820. }
  51821. }
  51822. } catch ( error ) {
  51823. console.error( 'THREE.WebGLRenderer: ' + error.message );
  51824. throw error;
  51825. }
  51826. let extensions, capabilities, state, info;
  51827. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  51828. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  51829. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  51830. let utils, bindingStates, uniformsGroups;
  51831. function initGLContext() {
  51832. extensions = new WebGLExtensions( _gl );
  51833. extensions.init();
  51834. utils = new WebGLUtils( _gl, extensions );
  51835. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  51836. state = new WebGLState( _gl, extensions );
  51837. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  51838. state.buffers.depth.setReversed( true );
  51839. }
  51840. info = new WebGLInfo( _gl );
  51841. properties = new WebGLProperties();
  51842. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  51843. cubemaps = new WebGLCubeMaps( _this );
  51844. cubeuvmaps = new WebGLCubeUVMaps( _this );
  51845. attributes = new WebGLAttributes( _gl );
  51846. bindingStates = new WebGLBindingStates( _gl, attributes );
  51847. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  51848. objects = new WebGLObjects( _gl, geometries, attributes, info );
  51849. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  51850. clipping = new WebGLClipping( properties );
  51851. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  51852. materials = new WebGLMaterials( _this, properties );
  51853. renderLists = new WebGLRenderLists();
  51854. renderStates = new WebGLRenderStates( extensions );
  51855. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  51856. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  51857. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  51858. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  51859. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  51860. info.programs = programCache.programs;
  51861. /**
  51862. * Holds details about the capabilities of the current rendering context.
  51863. *
  51864. * @name WebGLRenderer#capabilities
  51865. * @type {WebGLRenderer~Capabilities}
  51866. */
  51867. _this.capabilities = capabilities;
  51868. /**
  51869. * Provides methods for retrieving and testing WebGL extensions.
  51870. *
  51871. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  51872. * and return the extension object if available.
  51873. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  51874. *
  51875. * @name WebGLRenderer#extensions
  51876. * @type {Object}
  51877. */
  51878. _this.extensions = extensions;
  51879. /**
  51880. * Used to track properties of other objects like native WebGL objects.
  51881. *
  51882. * @name WebGLRenderer#properties
  51883. * @type {Object}
  51884. */
  51885. _this.properties = properties;
  51886. /**
  51887. * Manages the render lists of the renderer.
  51888. *
  51889. * @name WebGLRenderer#renderLists
  51890. * @type {Object}
  51891. */
  51892. _this.renderLists = renderLists;
  51893. /**
  51894. * Interface for managing shadows.
  51895. *
  51896. * @name WebGLRenderer#shadowMap
  51897. * @type {WebGLRenderer~ShadowMap}
  51898. */
  51899. _this.shadowMap = shadowMap;
  51900. /**
  51901. * Interface for managing the WebGL state.
  51902. *
  51903. * @name WebGLRenderer#state
  51904. * @type {Object}
  51905. */
  51906. _this.state = state;
  51907. /**
  51908. * Holds a series of statistical information about the GPU memory
  51909. * and the rendering process. Useful for debugging and monitoring.
  51910. *
  51911. * By default these data are reset at each render call but when having
  51912. * multiple render passes per frame (e.g. when using post processing) it can
  51913. * be preferred to reset with a custom pattern. First, set `autoReset` to
  51914. * `false`.
  51915. * ```js
  51916. * renderer.info.autoReset = false;
  51917. * ```
  51918. * Call `reset()` whenever you have finished to render a single frame.
  51919. * ```js
  51920. * renderer.info.reset();
  51921. * ```
  51922. *
  51923. * @name WebGLRenderer#info
  51924. * @type {WebGLRenderer~Info}
  51925. */
  51926. _this.info = info;
  51927. }
  51928. initGLContext();
  51929. // xr
  51930. const xr = new WebXRManager( _this, _gl );
  51931. /**
  51932. * A reference to the XR manager.
  51933. *
  51934. * @type {WebXRManager}
  51935. */
  51936. this.xr = xr;
  51937. /**
  51938. * Returns the rendering context.
  51939. *
  51940. * @return {WebGL2RenderingContext} The rendering context.
  51941. */
  51942. this.getContext = function () {
  51943. return _gl;
  51944. };
  51945. /**
  51946. * Returns the rendering context attributes.
  51947. *
  51948. * @return {WebGLContextAttributes} The rendering context attributes.
  51949. */
  51950. this.getContextAttributes = function () {
  51951. return _gl.getContextAttributes();
  51952. };
  51953. /**
  51954. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  51955. */
  51956. this.forceContextLoss = function () {
  51957. const extension = extensions.get( 'WEBGL_lose_context' );
  51958. if ( extension ) extension.loseContext();
  51959. };
  51960. /**
  51961. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  51962. */
  51963. this.forceContextRestore = function () {
  51964. const extension = extensions.get( 'WEBGL_lose_context' );
  51965. if ( extension ) extension.restoreContext();
  51966. };
  51967. /**
  51968. * Returns the pixel ratio.
  51969. *
  51970. * @return {number} The pixel ratio.
  51971. */
  51972. this.getPixelRatio = function () {
  51973. return _pixelRatio;
  51974. };
  51975. /**
  51976. * Sets the given pixel ratio and resizes the canvas if necessary.
  51977. *
  51978. * @param {number} value - The pixel ratio.
  51979. */
  51980. this.setPixelRatio = function ( value ) {
  51981. if ( value === undefined ) return;
  51982. _pixelRatio = value;
  51983. this.setSize( _width, _height, false );
  51984. };
  51985. /**
  51986. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  51987. *
  51988. * @param {Vector2} target - The method writes the result in this target object.
  51989. * @return {Vector2} The renderer's size in logical pixels.
  51990. */
  51991. this.getSize = function ( target ) {
  51992. return target.set( _width, _height );
  51993. };
  51994. /**
  51995. * Resizes the output canvas to (width, height) with device pixel ratio taken
  51996. * into account, and also sets the viewport to fit that size, starting in (0,
  51997. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  51998. *
  51999. * @param {number} width - The width in logical pixels.
  52000. * @param {number} height - The height in logical pixels.
  52001. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52002. */
  52003. this.setSize = function ( width, height, updateStyle = true ) {
  52004. if ( xr.isPresenting ) {
  52005. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52006. return;
  52007. }
  52008. _width = width;
  52009. _height = height;
  52010. canvas.width = Math.floor( width * _pixelRatio );
  52011. canvas.height = Math.floor( height * _pixelRatio );
  52012. if ( updateStyle === true ) {
  52013. canvas.style.width = width + 'px';
  52014. canvas.style.height = height + 'px';
  52015. }
  52016. this.setViewport( 0, 0, width, height );
  52017. };
  52018. /**
  52019. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52020. *
  52021. * @param {Vector2} target - The method writes the result in this target object.
  52022. * @return {Vector2} The drawing buffer size.
  52023. */
  52024. this.getDrawingBufferSize = function ( target ) {
  52025. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52026. };
  52027. /**
  52028. * This method allows to define the drawing buffer size by specifying
  52029. * width, height and pixel ratio all at once. The size of the drawing
  52030. * buffer is computed with this formula:
  52031. * ```js
  52032. * size.x = width * pixelRatio;
  52033. * size.y = height * pixelRatio;
  52034. * ```
  52035. *
  52036. * @param {number} width - The width in logical pixels.
  52037. * @param {number} height - The height in logical pixels.
  52038. * @param {number} pixelRatio - The pixel ratio.
  52039. */
  52040. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52041. _width = width;
  52042. _height = height;
  52043. _pixelRatio = pixelRatio;
  52044. canvas.width = Math.floor( width * pixelRatio );
  52045. canvas.height = Math.floor( height * pixelRatio );
  52046. this.setViewport( 0, 0, width, height );
  52047. };
  52048. /**
  52049. * Returns the current viewport definition.
  52050. *
  52051. * @param {Vector2} target - The method writes the result in this target object.
  52052. * @return {Vector2} The current viewport definition.
  52053. */
  52054. this.getCurrentViewport = function ( target ) {
  52055. return target.copy( _currentViewport );
  52056. };
  52057. /**
  52058. * Returns the viewport definition.
  52059. *
  52060. * @param {Vector4} target - The method writes the result in this target object.
  52061. * @return {Vector4} The viewport definition.
  52062. */
  52063. this.getViewport = function ( target ) {
  52064. return target.copy( _viewport );
  52065. };
  52066. /**
  52067. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52068. *
  52069. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52070. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52071. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52072. * @param {number} width - The width of the viewport in logical pixel unit.
  52073. * @param {number} height - The height of the viewport in logical pixel unit.
  52074. */
  52075. this.setViewport = function ( x, y, width, height ) {
  52076. if ( x.isVector4 ) {
  52077. _viewport.set( x.x, x.y, x.z, x.w );
  52078. } else {
  52079. _viewport.set( x, y, width, height );
  52080. }
  52081. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52082. };
  52083. /**
  52084. * Returns the scissor region.
  52085. *
  52086. * @param {Vector4} target - The method writes the result in this target object.
  52087. * @return {Vector4} The scissor region.
  52088. */
  52089. this.getScissor = function ( target ) {
  52090. return target.copy( _scissor );
  52091. };
  52092. /**
  52093. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52094. *
  52095. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52096. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52097. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52098. * @param {number} width - The width of the scissor region in logical pixel unit.
  52099. * @param {number} height - The height of the scissor region in logical pixel unit.
  52100. */
  52101. this.setScissor = function ( x, y, width, height ) {
  52102. if ( x.isVector4 ) {
  52103. _scissor.set( x.x, x.y, x.z, x.w );
  52104. } else {
  52105. _scissor.set( x, y, width, height );
  52106. }
  52107. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52108. };
  52109. /**
  52110. * Returns `true` if the scissor test is enabled.
  52111. *
  52112. * @return {boolean} Whether the scissor test is enabled or not.
  52113. */
  52114. this.getScissorTest = function () {
  52115. return _scissorTest;
  52116. };
  52117. /**
  52118. * Enable or disable the scissor test. When this is enabled, only the pixels
  52119. * within the defined scissor area will be affected by further renderer
  52120. * actions.
  52121. *
  52122. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52123. */
  52124. this.setScissorTest = function ( boolean ) {
  52125. state.setScissorTest( _scissorTest = boolean );
  52126. };
  52127. /**
  52128. * Sets a custom opaque sort function for the render lists. Pass `null`
  52129. * to use the default `painterSortStable` function.
  52130. *
  52131. * @param {?Function} method - The opaque sort function.
  52132. */
  52133. this.setOpaqueSort = function ( method ) {
  52134. _opaqueSort = method;
  52135. };
  52136. /**
  52137. * Sets a custom transparent sort function for the render lists. Pass `null`
  52138. * to use the default `reversePainterSortStable` function.
  52139. *
  52140. * @param {?Function} method - The opaque sort function.
  52141. */
  52142. this.setTransparentSort = function ( method ) {
  52143. _transparentSort = method;
  52144. };
  52145. // Clearing
  52146. /**
  52147. * Returns the clear color.
  52148. *
  52149. * @param {Color} target - The method writes the result in this target object.
  52150. * @return {Color} The clear color.
  52151. */
  52152. this.getClearColor = function ( target ) {
  52153. return target.copy( background.getClearColor() );
  52154. };
  52155. /**
  52156. * Sets the clear color and alpha.
  52157. *
  52158. * @param {Color} color - The clear color.
  52159. * @param {number} [alpha=1] - The clear alpha.
  52160. */
  52161. this.setClearColor = function () {
  52162. background.setClearColor( ...arguments );
  52163. };
  52164. /**
  52165. * Returns the clear alpha. Ranges within `[0,1]`.
  52166. *
  52167. * @return {number} The clear alpha.
  52168. */
  52169. this.getClearAlpha = function () {
  52170. return background.getClearAlpha();
  52171. };
  52172. /**
  52173. * Sets the clear alpha.
  52174. *
  52175. * @param {number} alpha - The clear alpha.
  52176. */
  52177. this.setClearAlpha = function () {
  52178. background.setClearAlpha( ...arguments );
  52179. };
  52180. /**
  52181. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  52182. * This method initializes the buffers to the current clear color values.
  52183. *
  52184. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  52185. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  52186. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  52187. */
  52188. this.clear = function ( color = true, depth = true, stencil = true ) {
  52189. let bits = 0;
  52190. if ( color ) {
  52191. // check if we're trying to clear an integer target
  52192. let isIntegerFormat = false;
  52193. if ( _currentRenderTarget !== null ) {
  52194. const targetFormat = _currentRenderTarget.texture.format;
  52195. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  52196. targetFormat === RGIntegerFormat ||
  52197. targetFormat === RedIntegerFormat;
  52198. }
  52199. // use the appropriate clear functions to clear the target if it's a signed
  52200. // or unsigned integer target
  52201. if ( isIntegerFormat ) {
  52202. const targetType = _currentRenderTarget.texture.type;
  52203. const isUnsignedType = targetType === UnsignedByteType ||
  52204. targetType === UnsignedIntType ||
  52205. targetType === UnsignedShortType ||
  52206. targetType === UnsignedInt248Type ||
  52207. targetType === UnsignedShort4444Type ||
  52208. targetType === UnsignedShort5551Type;
  52209. const clearColor = background.getClearColor();
  52210. const a = background.getClearAlpha();
  52211. const r = clearColor.r;
  52212. const g = clearColor.g;
  52213. const b = clearColor.b;
  52214. if ( isUnsignedType ) {
  52215. uintClearColor[ 0 ] = r;
  52216. uintClearColor[ 1 ] = g;
  52217. uintClearColor[ 2 ] = b;
  52218. uintClearColor[ 3 ] = a;
  52219. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  52220. } else {
  52221. intClearColor[ 0 ] = r;
  52222. intClearColor[ 1 ] = g;
  52223. intClearColor[ 2 ] = b;
  52224. intClearColor[ 3 ] = a;
  52225. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  52226. }
  52227. } else {
  52228. bits |= _gl.COLOR_BUFFER_BIT;
  52229. }
  52230. }
  52231. if ( depth ) {
  52232. bits |= _gl.DEPTH_BUFFER_BIT;
  52233. }
  52234. if ( stencil ) {
  52235. bits |= _gl.STENCIL_BUFFER_BIT;
  52236. this.state.buffers.stencil.setMask( 0xffffffff );
  52237. }
  52238. _gl.clear( bits );
  52239. };
  52240. /**
  52241. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  52242. */
  52243. this.clearColor = function () {
  52244. this.clear( true, false, false );
  52245. };
  52246. /**
  52247. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  52248. */
  52249. this.clearDepth = function () {
  52250. this.clear( false, true, false );
  52251. };
  52252. /**
  52253. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  52254. */
  52255. this.clearStencil = function () {
  52256. this.clear( false, false, true );
  52257. };
  52258. /**
  52259. * Frees the GPU-related resources allocated by this instance. Call this
  52260. * method whenever this instance is no longer used in your app.
  52261. */
  52262. this.dispose = function () {
  52263. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  52264. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  52265. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52266. background.dispose();
  52267. renderLists.dispose();
  52268. renderStates.dispose();
  52269. properties.dispose();
  52270. cubemaps.dispose();
  52271. cubeuvmaps.dispose();
  52272. objects.dispose();
  52273. bindingStates.dispose();
  52274. uniformsGroups.dispose();
  52275. programCache.dispose();
  52276. xr.dispose();
  52277. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  52278. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  52279. animation.stop();
  52280. };
  52281. // Events
  52282. function onContextLost( event ) {
  52283. event.preventDefault();
  52284. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  52285. _isContextLost = true;
  52286. }
  52287. function onContextRestore( /* event */ ) {
  52288. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  52289. _isContextLost = false;
  52290. const infoAutoReset = info.autoReset;
  52291. const shadowMapEnabled = shadowMap.enabled;
  52292. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  52293. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  52294. const shadowMapType = shadowMap.type;
  52295. initGLContext();
  52296. info.autoReset = infoAutoReset;
  52297. shadowMap.enabled = shadowMapEnabled;
  52298. shadowMap.autoUpdate = shadowMapAutoUpdate;
  52299. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  52300. shadowMap.type = shadowMapType;
  52301. }
  52302. function onContextCreationError( event ) {
  52303. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  52304. }
  52305. function onMaterialDispose( event ) {
  52306. const material = event.target;
  52307. material.removeEventListener( 'dispose', onMaterialDispose );
  52308. deallocateMaterial( material );
  52309. }
  52310. // Buffer deallocation
  52311. function deallocateMaterial( material ) {
  52312. releaseMaterialProgramReferences( material );
  52313. properties.remove( material );
  52314. }
  52315. function releaseMaterialProgramReferences( material ) {
  52316. const programs = properties.get( material ).programs;
  52317. if ( programs !== undefined ) {
  52318. programs.forEach( function ( program ) {
  52319. programCache.releaseProgram( program );
  52320. } );
  52321. if ( material.isShaderMaterial ) {
  52322. programCache.releaseShaderCache( material );
  52323. }
  52324. }
  52325. }
  52326. // Buffer rendering
  52327. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  52328. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  52329. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  52330. const program = setProgram( camera, scene, geometry, material, object );
  52331. state.setMaterial( material, frontFaceCW );
  52332. //
  52333. let index = geometry.index;
  52334. let rangeFactor = 1;
  52335. if ( material.wireframe === true ) {
  52336. index = geometries.getWireframeAttribute( geometry );
  52337. if ( index === undefined ) return;
  52338. rangeFactor = 2;
  52339. }
  52340. //
  52341. const drawRange = geometry.drawRange;
  52342. const position = geometry.attributes.position;
  52343. let drawStart = drawRange.start * rangeFactor;
  52344. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  52345. if ( group !== null ) {
  52346. drawStart = Math.max( drawStart, group.start * rangeFactor );
  52347. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  52348. }
  52349. if ( index !== null ) {
  52350. drawStart = Math.max( drawStart, 0 );
  52351. drawEnd = Math.min( drawEnd, index.count );
  52352. } else if ( position !== undefined && position !== null ) {
  52353. drawStart = Math.max( drawStart, 0 );
  52354. drawEnd = Math.min( drawEnd, position.count );
  52355. }
  52356. const drawCount = drawEnd - drawStart;
  52357. if ( drawCount < 0 || drawCount === Infinity ) return;
  52358. //
  52359. bindingStates.setup( object, material, program, geometry, index );
  52360. let attribute;
  52361. let renderer = bufferRenderer;
  52362. if ( index !== null ) {
  52363. attribute = attributes.get( index );
  52364. renderer = indexedBufferRenderer;
  52365. renderer.setIndex( attribute );
  52366. }
  52367. //
  52368. if ( object.isMesh ) {
  52369. if ( material.wireframe === true ) {
  52370. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  52371. renderer.setMode( _gl.LINES );
  52372. } else {
  52373. renderer.setMode( _gl.TRIANGLES );
  52374. }
  52375. } else if ( object.isLine ) {
  52376. let lineWidth = material.linewidth;
  52377. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  52378. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  52379. if ( object.isLineSegments ) {
  52380. renderer.setMode( _gl.LINES );
  52381. } else if ( object.isLineLoop ) {
  52382. renderer.setMode( _gl.LINE_LOOP );
  52383. } else {
  52384. renderer.setMode( _gl.LINE_STRIP );
  52385. }
  52386. } else if ( object.isPoints ) {
  52387. renderer.setMode( _gl.POINTS );
  52388. } else if ( object.isSprite ) {
  52389. renderer.setMode( _gl.TRIANGLES );
  52390. }
  52391. if ( object.isBatchedMesh ) {
  52392. if ( object._multiDrawInstances !== null ) {
  52393. // @deprecated, r174
  52394. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52395. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  52396. } else {
  52397. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  52398. const starts = object._multiDrawStarts;
  52399. const counts = object._multiDrawCounts;
  52400. const drawCount = object._multiDrawCount;
  52401. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  52402. const uniforms = properties.get( material ).currentProgram.getUniforms();
  52403. for ( let i = 0; i < drawCount; i ++ ) {
  52404. uniforms.setValue( _gl, '_gl_DrawID', i );
  52405. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  52406. }
  52407. } else {
  52408. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  52409. }
  52410. }
  52411. } else if ( object.isInstancedMesh ) {
  52412. renderer.renderInstances( drawStart, drawCount, object.count );
  52413. } else if ( geometry.isInstancedBufferGeometry ) {
  52414. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  52415. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  52416. renderer.renderInstances( drawStart, drawCount, instanceCount );
  52417. } else {
  52418. renderer.render( drawStart, drawCount );
  52419. }
  52420. };
  52421. // Compile
  52422. function prepareMaterial( material, scene, object ) {
  52423. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52424. material.side = BackSide;
  52425. material.needsUpdate = true;
  52426. getProgram( material, scene, object );
  52427. material.side = FrontSide;
  52428. material.needsUpdate = true;
  52429. getProgram( material, scene, object );
  52430. material.side = DoubleSide;
  52431. } else {
  52432. getProgram( material, scene, object );
  52433. }
  52434. }
  52435. /**
  52436. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  52437. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  52438. * optional parameter for applying the target scene.
  52439. *
  52440. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  52441. *
  52442. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52443. * @param {Camera} camera - The camera.
  52444. * @param {?Scene} [targetScene=null] - The target scene.
  52445. * @return {Set<Material>} The precompiled materials.
  52446. */
  52447. this.compile = function ( scene, camera, targetScene = null ) {
  52448. if ( targetScene === null ) targetScene = scene;
  52449. currentRenderState = renderStates.get( targetScene );
  52450. currentRenderState.init( camera );
  52451. renderStateStack.push( currentRenderState );
  52452. // gather lights from both the target scene and the new object that will be added to the scene.
  52453. targetScene.traverseVisible( function ( object ) {
  52454. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52455. currentRenderState.pushLight( object );
  52456. if ( object.castShadow ) {
  52457. currentRenderState.pushShadow( object );
  52458. }
  52459. }
  52460. } );
  52461. if ( scene !== targetScene ) {
  52462. scene.traverseVisible( function ( object ) {
  52463. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52464. currentRenderState.pushLight( object );
  52465. if ( object.castShadow ) {
  52466. currentRenderState.pushShadow( object );
  52467. }
  52468. }
  52469. } );
  52470. }
  52471. currentRenderState.setupLights();
  52472. // Only initialize materials in the new scene, not the targetScene.
  52473. const materials = new Set();
  52474. scene.traverse( function ( object ) {
  52475. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  52476. return;
  52477. }
  52478. const material = object.material;
  52479. if ( material ) {
  52480. if ( Array.isArray( material ) ) {
  52481. for ( let i = 0; i < material.length; i ++ ) {
  52482. const material2 = material[ i ];
  52483. prepareMaterial( material2, targetScene, object );
  52484. materials.add( material2 );
  52485. }
  52486. } else {
  52487. prepareMaterial( material, targetScene, object );
  52488. materials.add( material );
  52489. }
  52490. }
  52491. } );
  52492. currentRenderState = renderStateStack.pop();
  52493. return materials;
  52494. };
  52495. // compileAsync
  52496. /**
  52497. * Asynchronous version of {@link WebGLRenderer#compile}.
  52498. *
  52499. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  52500. * it is recommended to use this version of `compile()` whenever possible.
  52501. *
  52502. * @async
  52503. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52504. * @param {Camera} camera - The camera.
  52505. * @param {?Scene} [targetScene=null] - The target scene.
  52506. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  52507. */
  52508. this.compileAsync = function ( scene, camera, targetScene = null ) {
  52509. const materials = this.compile( scene, camera, targetScene );
  52510. // Wait for all the materials in the new object to indicate that they're
  52511. // ready to be used before resolving the promise.
  52512. return new Promise( ( resolve ) => {
  52513. function checkMaterialsReady() {
  52514. materials.forEach( function ( material ) {
  52515. const materialProperties = properties.get( material );
  52516. const program = materialProperties.currentProgram;
  52517. if ( program.isReady() ) {
  52518. // remove any programs that report they're ready to use from the list
  52519. materials.delete( material );
  52520. }
  52521. } );
  52522. // once the list of compiling materials is empty, call the callback
  52523. if ( materials.size === 0 ) {
  52524. resolve( scene );
  52525. return;
  52526. }
  52527. // if some materials are still not ready, wait a bit and check again
  52528. setTimeout( checkMaterialsReady, 10 );
  52529. }
  52530. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  52531. // If we can check the compilation status of the materials without
  52532. // blocking then do so right away.
  52533. checkMaterialsReady();
  52534. } else {
  52535. // Otherwise start by waiting a bit to give the materials we just
  52536. // initialized a chance to finish.
  52537. setTimeout( checkMaterialsReady, 10 );
  52538. }
  52539. } );
  52540. };
  52541. // Animation Loop
  52542. let onAnimationFrameCallback = null;
  52543. function onAnimationFrame( time ) {
  52544. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  52545. }
  52546. function onXRSessionStart() {
  52547. animation.stop();
  52548. }
  52549. function onXRSessionEnd() {
  52550. animation.start();
  52551. }
  52552. const animation = new WebGLAnimation();
  52553. animation.setAnimationLoop( onAnimationFrame );
  52554. if ( typeof self !== 'undefined' ) animation.setContext( self );
  52555. this.setAnimationLoop = function ( callback ) {
  52556. onAnimationFrameCallback = callback;
  52557. xr.setAnimationLoop( callback );
  52558. ( callback === null ) ? animation.stop() : animation.start();
  52559. };
  52560. xr.addEventListener( 'sessionstart', onXRSessionStart );
  52561. xr.addEventListener( 'sessionend', onXRSessionEnd );
  52562. // Rendering
  52563. /**
  52564. * Renders the given scene (or other type of 3D object) using the given camera.
  52565. *
  52566. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  52567. * or to the canvas as usual.
  52568. *
  52569. * By default render buffers are cleared before rendering but you can prevent
  52570. * this by setting the property `autoClear` to `false`. If you want to prevent
  52571. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  52572. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  52573. *
  52574. * @param {Object3D} scene - The scene to render.
  52575. * @param {Camera} camera - The camera.
  52576. */
  52577. this.render = function ( scene, camera ) {
  52578. if ( camera !== undefined && camera.isCamera !== true ) {
  52579. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  52580. return;
  52581. }
  52582. if ( _isContextLost === true ) return;
  52583. // update scene graph
  52584. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  52585. // update camera matrices and frustum
  52586. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  52587. if ( xr.enabled === true && xr.isPresenting === true ) {
  52588. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  52589. camera = xr.getCamera(); // use XR camera for rendering
  52590. }
  52591. //
  52592. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  52593. currentRenderState = renderStates.get( scene, renderStateStack.length );
  52594. currentRenderState.init( camera );
  52595. renderStateStack.push( currentRenderState );
  52596. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  52597. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  52598. _localClippingEnabled = this.localClippingEnabled;
  52599. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  52600. currentRenderList = renderLists.get( scene, renderListStack.length );
  52601. currentRenderList.init();
  52602. renderListStack.push( currentRenderList );
  52603. if ( xr.enabled === true && xr.isPresenting === true ) {
  52604. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  52605. if ( depthSensingMesh !== null ) {
  52606. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  52607. }
  52608. }
  52609. projectObject( scene, camera, 0, _this.sortObjects );
  52610. currentRenderList.finish();
  52611. if ( _this.sortObjects === true ) {
  52612. currentRenderList.sort( _opaqueSort, _transparentSort );
  52613. }
  52614. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  52615. if ( _renderBackground ) {
  52616. background.addToRenderList( currentRenderList, scene );
  52617. }
  52618. //
  52619. this.info.render.frame ++;
  52620. if ( _clippingEnabled === true ) clipping.beginShadows();
  52621. const shadowsArray = currentRenderState.state.shadowsArray;
  52622. shadowMap.render( shadowsArray, scene, camera );
  52623. if ( _clippingEnabled === true ) clipping.endShadows();
  52624. //
  52625. if ( this.info.autoReset === true ) this.info.reset();
  52626. // render scene
  52627. const opaqueObjects = currentRenderList.opaque;
  52628. const transmissiveObjects = currentRenderList.transmissive;
  52629. currentRenderState.setupLights();
  52630. if ( camera.isArrayCamera ) {
  52631. const cameras = camera.cameras;
  52632. if ( transmissiveObjects.length > 0 ) {
  52633. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52634. const camera2 = cameras[ i ];
  52635. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  52636. }
  52637. }
  52638. if ( _renderBackground ) background.render( scene );
  52639. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52640. const camera2 = cameras[ i ];
  52641. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  52642. }
  52643. } else {
  52644. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  52645. if ( _renderBackground ) background.render( scene );
  52646. renderScene( currentRenderList, scene, camera );
  52647. }
  52648. //
  52649. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  52650. // resolve multisample renderbuffers to a single-sample texture if necessary
  52651. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  52652. // Generate mipmap if we're using any kind of mipmap filtering
  52653. textures.updateRenderTargetMipmap( _currentRenderTarget );
  52654. }
  52655. //
  52656. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  52657. // _gl.finish();
  52658. bindingStates.resetDefaultState();
  52659. _currentMaterialId = -1;
  52660. _currentCamera = null;
  52661. renderStateStack.pop();
  52662. if ( renderStateStack.length > 0 ) {
  52663. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  52664. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  52665. } else {
  52666. currentRenderState = null;
  52667. }
  52668. renderListStack.pop();
  52669. if ( renderListStack.length > 0 ) {
  52670. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  52671. } else {
  52672. currentRenderList = null;
  52673. }
  52674. };
  52675. function projectObject( object, camera, groupOrder, sortObjects ) {
  52676. if ( object.visible === false ) return;
  52677. const visible = object.layers.test( camera.layers );
  52678. if ( visible ) {
  52679. if ( object.isGroup ) {
  52680. groupOrder = object.renderOrder;
  52681. } else if ( object.isLOD ) {
  52682. if ( object.autoUpdate === true ) object.update( camera );
  52683. } else if ( object.isLight ) {
  52684. currentRenderState.pushLight( object );
  52685. if ( object.castShadow ) {
  52686. currentRenderState.pushShadow( object );
  52687. }
  52688. } else if ( object.isSprite ) {
  52689. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  52690. if ( sortObjects ) {
  52691. _vector4.setFromMatrixPosition( object.matrixWorld )
  52692. .applyMatrix4( _projScreenMatrix );
  52693. }
  52694. const geometry = objects.update( object );
  52695. const material = object.material;
  52696. if ( material.visible ) {
  52697. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52698. }
  52699. }
  52700. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  52701. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  52702. const geometry = objects.update( object );
  52703. const material = object.material;
  52704. if ( sortObjects ) {
  52705. if ( object.boundingSphere !== undefined ) {
  52706. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  52707. _vector4.copy( object.boundingSphere.center );
  52708. } else {
  52709. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  52710. _vector4.copy( geometry.boundingSphere.center );
  52711. }
  52712. _vector4
  52713. .applyMatrix4( object.matrixWorld )
  52714. .applyMatrix4( _projScreenMatrix );
  52715. }
  52716. if ( Array.isArray( material ) ) {
  52717. const groups = geometry.groups;
  52718. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52719. const group = groups[ i ];
  52720. const groupMaterial = material[ group.materialIndex ];
  52721. if ( groupMaterial && groupMaterial.visible ) {
  52722. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  52723. }
  52724. }
  52725. } else if ( material.visible ) {
  52726. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52727. }
  52728. }
  52729. }
  52730. }
  52731. const children = object.children;
  52732. for ( let i = 0, l = children.length; i < l; i ++ ) {
  52733. projectObject( children[ i ], camera, groupOrder, sortObjects );
  52734. }
  52735. }
  52736. function renderScene( currentRenderList, scene, camera, viewport ) {
  52737. const opaqueObjects = currentRenderList.opaque;
  52738. const transmissiveObjects = currentRenderList.transmissive;
  52739. const transparentObjects = currentRenderList.transparent;
  52740. currentRenderState.setupLightsView( camera );
  52741. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52742. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  52743. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  52744. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  52745. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  52746. // Ensure depth buffer writing is enabled so it can be cleared on next render
  52747. state.buffers.depth.setTest( true );
  52748. state.buffers.depth.setMask( true );
  52749. state.buffers.color.setMask( true );
  52750. state.setPolygonOffset( false );
  52751. }
  52752. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  52753. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52754. if ( overrideMaterial !== null ) {
  52755. return;
  52756. }
  52757. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  52758. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  52759. generateMipmaps: true,
  52760. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  52761. minFilter: LinearMipmapLinearFilter,
  52762. samples: 4,
  52763. stencilBuffer: stencil,
  52764. resolveDepthBuffer: false,
  52765. resolveStencilBuffer: false,
  52766. colorSpace: ColorManagement.workingColorSpace,
  52767. } );
  52768. // debug
  52769. /*
  52770. const geometry = new PlaneGeometry();
  52771. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  52772. const mesh = new Mesh( geometry, material );
  52773. scene.add( mesh );
  52774. */
  52775. }
  52776. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  52777. const activeViewport = camera.viewport || _currentViewport;
  52778. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  52779. //
  52780. const currentRenderTarget = _this.getRenderTarget();
  52781. const currentActiveCubeFace = _this.getActiveCubeFace();
  52782. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  52783. _this.setRenderTarget( transmissionRenderTarget );
  52784. _this.getClearColor( _currentClearColor );
  52785. _currentClearAlpha = _this.getClearAlpha();
  52786. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  52787. _this.clear();
  52788. if ( _renderBackground ) background.render( scene );
  52789. // Turn off the features which can affect the frag color for opaque objects pass.
  52790. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  52791. const currentToneMapping = _this.toneMapping;
  52792. _this.toneMapping = NoToneMapping;
  52793. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  52794. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  52795. const currentCameraViewport = camera.viewport;
  52796. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  52797. currentRenderState.setupLightsView( camera );
  52798. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52799. renderObjects( opaqueObjects, scene, camera );
  52800. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52801. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52802. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  52803. let renderTargetNeedsUpdate = false;
  52804. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  52805. const renderItem = transmissiveObjects[ i ];
  52806. const object = renderItem.object;
  52807. const geometry = renderItem.geometry;
  52808. const material = renderItem.material;
  52809. const group = renderItem.group;
  52810. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  52811. const currentSide = material.side;
  52812. material.side = BackSide;
  52813. material.needsUpdate = true;
  52814. renderObject( object, scene, camera, geometry, material, group );
  52815. material.side = currentSide;
  52816. material.needsUpdate = true;
  52817. renderTargetNeedsUpdate = true;
  52818. }
  52819. }
  52820. if ( renderTargetNeedsUpdate === true ) {
  52821. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52822. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52823. }
  52824. }
  52825. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  52826. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  52827. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  52828. _this.toneMapping = currentToneMapping;
  52829. }
  52830. function renderObjects( renderList, scene, camera ) {
  52831. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52832. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  52833. const renderItem = renderList[ i ];
  52834. const object = renderItem.object;
  52835. const geometry = renderItem.geometry;
  52836. const group = renderItem.group;
  52837. let material = renderItem.material;
  52838. if ( material.allowOverride === true && overrideMaterial !== null ) {
  52839. material = overrideMaterial;
  52840. }
  52841. if ( object.layers.test( camera.layers ) ) {
  52842. renderObject( object, scene, camera, geometry, material, group );
  52843. }
  52844. }
  52845. }
  52846. function renderObject( object, scene, camera, geometry, material, group ) {
  52847. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  52848. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  52849. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  52850. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  52851. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52852. material.side = BackSide;
  52853. material.needsUpdate = true;
  52854. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52855. material.side = FrontSide;
  52856. material.needsUpdate = true;
  52857. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52858. material.side = DoubleSide;
  52859. } else {
  52860. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52861. }
  52862. object.onAfterRender( _this, scene, camera, geometry, material, group );
  52863. }
  52864. function getProgram( material, scene, object ) {
  52865. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52866. const materialProperties = properties.get( material );
  52867. const lights = currentRenderState.state.lights;
  52868. const shadowsArray = currentRenderState.state.shadowsArray;
  52869. const lightsStateVersion = lights.state.version;
  52870. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  52871. const programCacheKey = programCache.getProgramCacheKey( parameters );
  52872. let programs = materialProperties.programs;
  52873. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  52874. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  52875. materialProperties.fog = scene.fog;
  52876. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  52877. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  52878. if ( programs === undefined ) {
  52879. // new material
  52880. material.addEventListener( 'dispose', onMaterialDispose );
  52881. programs = new Map();
  52882. materialProperties.programs = programs;
  52883. }
  52884. let program = programs.get( programCacheKey );
  52885. if ( program !== undefined ) {
  52886. // early out if program and light state is identical
  52887. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  52888. updateCommonMaterialProperties( material, parameters );
  52889. return program;
  52890. }
  52891. } else {
  52892. parameters.uniforms = programCache.getUniforms( material );
  52893. material.onBeforeCompile( parameters, _this );
  52894. program = programCache.acquireProgram( parameters, programCacheKey );
  52895. programs.set( programCacheKey, program );
  52896. materialProperties.uniforms = parameters.uniforms;
  52897. }
  52898. const uniforms = materialProperties.uniforms;
  52899. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  52900. uniforms.clippingPlanes = clipping.uniform;
  52901. }
  52902. updateCommonMaterialProperties( material, parameters );
  52903. // store the light setup it was created for
  52904. materialProperties.needsLights = materialNeedsLights( material );
  52905. materialProperties.lightsStateVersion = lightsStateVersion;
  52906. if ( materialProperties.needsLights ) {
  52907. // wire up the material to this renderer's lighting state
  52908. uniforms.ambientLightColor.value = lights.state.ambient;
  52909. uniforms.lightProbe.value = lights.state.probe;
  52910. uniforms.directionalLights.value = lights.state.directional;
  52911. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  52912. uniforms.spotLights.value = lights.state.spot;
  52913. uniforms.spotLightShadows.value = lights.state.spotShadow;
  52914. uniforms.rectAreaLights.value = lights.state.rectArea;
  52915. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  52916. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  52917. uniforms.pointLights.value = lights.state.point;
  52918. uniforms.pointLightShadows.value = lights.state.pointShadow;
  52919. uniforms.hemisphereLights.value = lights.state.hemi;
  52920. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  52921. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  52922. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  52923. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  52924. uniforms.spotLightMap.value = lights.state.spotLightMap;
  52925. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  52926. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  52927. // TODO (abelnation): add area lights shadow info to uniforms
  52928. }
  52929. materialProperties.currentProgram = program;
  52930. materialProperties.uniformsList = null;
  52931. return program;
  52932. }
  52933. function getUniformList( materialProperties ) {
  52934. if ( materialProperties.uniformsList === null ) {
  52935. const progUniforms = materialProperties.currentProgram.getUniforms();
  52936. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  52937. }
  52938. return materialProperties.uniformsList;
  52939. }
  52940. function updateCommonMaterialProperties( material, parameters ) {
  52941. const materialProperties = properties.get( material );
  52942. materialProperties.outputColorSpace = parameters.outputColorSpace;
  52943. materialProperties.batching = parameters.batching;
  52944. materialProperties.batchingColor = parameters.batchingColor;
  52945. materialProperties.instancing = parameters.instancing;
  52946. materialProperties.instancingColor = parameters.instancingColor;
  52947. materialProperties.instancingMorph = parameters.instancingMorph;
  52948. materialProperties.skinning = parameters.skinning;
  52949. materialProperties.morphTargets = parameters.morphTargets;
  52950. materialProperties.morphNormals = parameters.morphNormals;
  52951. materialProperties.morphColors = parameters.morphColors;
  52952. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  52953. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  52954. materialProperties.numIntersection = parameters.numClipIntersection;
  52955. materialProperties.vertexAlphas = parameters.vertexAlphas;
  52956. materialProperties.vertexTangents = parameters.vertexTangents;
  52957. materialProperties.toneMapping = parameters.toneMapping;
  52958. }
  52959. function setProgram( camera, scene, geometry, material, object ) {
  52960. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52961. textures.resetTextureUnits();
  52962. const fog = scene.fog;
  52963. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  52964. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  52965. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  52966. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  52967. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  52968. const morphTargets = !! geometry.morphAttributes.position;
  52969. const morphNormals = !! geometry.morphAttributes.normal;
  52970. const morphColors = !! geometry.morphAttributes.color;
  52971. let toneMapping = NoToneMapping;
  52972. if ( material.toneMapped ) {
  52973. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  52974. toneMapping = _this.toneMapping;
  52975. }
  52976. }
  52977. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  52978. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  52979. const materialProperties = properties.get( material );
  52980. const lights = currentRenderState.state.lights;
  52981. if ( _clippingEnabled === true ) {
  52982. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  52983. const useCache =
  52984. camera === _currentCamera &&
  52985. material.id === _currentMaterialId;
  52986. // we might want to call this function with some ClippingGroup
  52987. // object instead of the material, once it becomes feasible
  52988. // (#8465, #8379)
  52989. clipping.setState( material, camera, useCache );
  52990. }
  52991. }
  52992. //
  52993. let needsProgramChange = false;
  52994. if ( material.version === materialProperties.__version ) {
  52995. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  52996. needsProgramChange = true;
  52997. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  52998. needsProgramChange = true;
  52999. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53000. needsProgramChange = true;
  53001. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53002. needsProgramChange = true;
  53003. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53004. needsProgramChange = true;
  53005. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53006. needsProgramChange = true;
  53007. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53008. needsProgramChange = true;
  53009. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53010. needsProgramChange = true;
  53011. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53012. needsProgramChange = true;
  53013. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53014. needsProgramChange = true;
  53015. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53016. needsProgramChange = true;
  53017. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53018. needsProgramChange = true;
  53019. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53020. needsProgramChange = true;
  53021. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53022. needsProgramChange = true;
  53023. } else if ( materialProperties.envMap !== envMap ) {
  53024. needsProgramChange = true;
  53025. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53026. needsProgramChange = true;
  53027. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53028. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53029. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53030. needsProgramChange = true;
  53031. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53032. needsProgramChange = true;
  53033. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53034. needsProgramChange = true;
  53035. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53036. needsProgramChange = true;
  53037. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53038. needsProgramChange = true;
  53039. } else if ( materialProperties.morphColors !== morphColors ) {
  53040. needsProgramChange = true;
  53041. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53042. needsProgramChange = true;
  53043. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53044. needsProgramChange = true;
  53045. }
  53046. } else {
  53047. needsProgramChange = true;
  53048. materialProperties.__version = material.version;
  53049. }
  53050. //
  53051. let program = materialProperties.currentProgram;
  53052. if ( needsProgramChange === true ) {
  53053. program = getProgram( material, scene, object );
  53054. }
  53055. let refreshProgram = false;
  53056. let refreshMaterial = false;
  53057. let refreshLights = false;
  53058. const p_uniforms = program.getUniforms(),
  53059. m_uniforms = materialProperties.uniforms;
  53060. if ( state.useProgram( program.program ) ) {
  53061. refreshProgram = true;
  53062. refreshMaterial = true;
  53063. refreshLights = true;
  53064. }
  53065. if ( material.id !== _currentMaterialId ) {
  53066. _currentMaterialId = material.id;
  53067. refreshMaterial = true;
  53068. }
  53069. if ( refreshProgram || _currentCamera !== camera ) {
  53070. // common camera uniforms
  53071. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53072. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53073. camera._reversedDepth = true;
  53074. camera.updateProjectionMatrix();
  53075. }
  53076. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53077. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53078. const uCamPos = p_uniforms.map.cameraPosition;
  53079. if ( uCamPos !== undefined ) {
  53080. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53081. }
  53082. if ( capabilities.logarithmicDepthBuffer ) {
  53083. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53084. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53085. }
  53086. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53087. if ( material.isMeshPhongMaterial ||
  53088. material.isMeshToonMaterial ||
  53089. material.isMeshLambertMaterial ||
  53090. material.isMeshBasicMaterial ||
  53091. material.isMeshStandardMaterial ||
  53092. material.isShaderMaterial ) {
  53093. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53094. }
  53095. if ( _currentCamera !== camera ) {
  53096. _currentCamera = camera;
  53097. // lighting uniforms depend on the camera so enforce an update
  53098. // now, in case this material supports lights - or later, when
  53099. // the next material that does gets activated:
  53100. refreshMaterial = true; // set to true on material change
  53101. refreshLights = true; // remains set until update done
  53102. }
  53103. }
  53104. // skinning and morph target uniforms must be set even if material didn't change
  53105. // auto-setting of texture unit for bone and morph texture must go before other textures
  53106. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53107. if ( object.isSkinnedMesh ) {
  53108. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53109. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53110. const skeleton = object.skeleton;
  53111. if ( skeleton ) {
  53112. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53113. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53114. }
  53115. }
  53116. if ( object.isBatchedMesh ) {
  53117. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53118. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53119. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53120. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53121. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53122. if ( object._colorsTexture !== null ) {
  53123. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53124. }
  53125. }
  53126. const morphAttributes = geometry.morphAttributes;
  53127. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53128. morphtargets.update( object, geometry, program );
  53129. }
  53130. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53131. materialProperties.receiveShadow = object.receiveShadow;
  53132. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53133. }
  53134. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  53135. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  53136. m_uniforms.envMap.value = envMap;
  53137. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  53138. }
  53139. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53140. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53141. }
  53142. if ( refreshMaterial ) {
  53143. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53144. if ( materialProperties.needsLights ) {
  53145. // the current material requires lighting info
  53146. // note: all lighting uniforms are always set correctly
  53147. // they simply reference the renderer's state for their
  53148. // values
  53149. //
  53150. // use the current material's .needsUpdate flags to set
  53151. // the GL state when required
  53152. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53153. }
  53154. // refresh uniforms common to several materials
  53155. if ( fog && material.fog === true ) {
  53156. materials.refreshFogUniforms( m_uniforms, fog );
  53157. }
  53158. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  53159. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53160. }
  53161. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  53162. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53163. material.uniformsNeedUpdate = false;
  53164. }
  53165. if ( material.isSpriteMaterial ) {
  53166. p_uniforms.setValue( _gl, 'center', object.center );
  53167. }
  53168. // common matrices
  53169. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  53170. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  53171. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  53172. // UBOs
  53173. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  53174. const groups = material.uniformsGroups;
  53175. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53176. const group = groups[ i ];
  53177. uniformsGroups.update( group, program );
  53178. uniformsGroups.bind( group, program );
  53179. }
  53180. }
  53181. return program;
  53182. }
  53183. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  53184. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  53185. uniforms.ambientLightColor.needsUpdate = value;
  53186. uniforms.lightProbe.needsUpdate = value;
  53187. uniforms.directionalLights.needsUpdate = value;
  53188. uniforms.directionalLightShadows.needsUpdate = value;
  53189. uniforms.pointLights.needsUpdate = value;
  53190. uniforms.pointLightShadows.needsUpdate = value;
  53191. uniforms.spotLights.needsUpdate = value;
  53192. uniforms.spotLightShadows.needsUpdate = value;
  53193. uniforms.rectAreaLights.needsUpdate = value;
  53194. uniforms.hemisphereLights.needsUpdate = value;
  53195. }
  53196. function materialNeedsLights( material ) {
  53197. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  53198. material.isMeshStandardMaterial || material.isShadowMaterial ||
  53199. ( material.isShaderMaterial && material.lights === true );
  53200. }
  53201. /**
  53202. * Returns the active cube face.
  53203. *
  53204. * @return {number} The active cube face.
  53205. */
  53206. this.getActiveCubeFace = function () {
  53207. return _currentActiveCubeFace;
  53208. };
  53209. /**
  53210. * Returns the active mipmap level.
  53211. *
  53212. * @return {number} The active mipmap level.
  53213. */
  53214. this.getActiveMipmapLevel = function () {
  53215. return _currentActiveMipmapLevel;
  53216. };
  53217. /**
  53218. * Returns the active render target.
  53219. *
  53220. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  53221. * is currently set.
  53222. */
  53223. this.getRenderTarget = function () {
  53224. return _currentRenderTarget;
  53225. };
  53226. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  53227. const renderTargetProperties = properties.get( renderTarget );
  53228. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  53229. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  53230. // The multisample_render_to_texture extension doesn't work properly if there
  53231. // are midframe flushes and an external depth buffer. Disable use of the extension.
  53232. renderTargetProperties.__useRenderToTexture = false;
  53233. }
  53234. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  53235. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  53236. renderTargetProperties.__hasExternalTextures = true;
  53237. };
  53238. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  53239. const renderTargetProperties = properties.get( renderTarget );
  53240. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  53241. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  53242. };
  53243. const _scratchFrameBuffer = _gl.createFramebuffer();
  53244. /**
  53245. * Sets the active rendertarget.
  53246. *
  53247. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  53248. * the canvas is set as the active render target instead.
  53249. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  53250. * Indicates the z layer to render in to when using 3D or array render targets.
  53251. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  53252. */
  53253. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  53254. _currentRenderTarget = renderTarget;
  53255. _currentActiveCubeFace = activeCubeFace;
  53256. _currentActiveMipmapLevel = activeMipmapLevel;
  53257. let useDefaultFramebuffer = true;
  53258. let framebuffer = null;
  53259. let isCube = false;
  53260. let isRenderTarget3D = false;
  53261. if ( renderTarget ) {
  53262. const renderTargetProperties = properties.get( renderTarget );
  53263. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  53264. // We need to make sure to rebind the framebuffer.
  53265. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  53266. useDefaultFramebuffer = false;
  53267. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  53268. textures.setupRenderTarget( renderTarget );
  53269. } else if ( renderTargetProperties.__hasExternalTextures ) {
  53270. // Color and depth texture must be rebound in order for the swapchain to update.
  53271. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  53272. } else if ( renderTarget.depthBuffer ) {
  53273. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  53274. const depthTexture = renderTarget.depthTexture;
  53275. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  53276. // check if the depth texture is compatible
  53277. if (
  53278. depthTexture !== null &&
  53279. properties.has( depthTexture ) &&
  53280. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  53281. ) {
  53282. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  53283. }
  53284. // Swap the depth buffer to the currently attached one
  53285. textures.setupDepthRenderbuffer( renderTarget );
  53286. }
  53287. }
  53288. const texture = renderTarget.texture;
  53289. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53290. isRenderTarget3D = true;
  53291. }
  53292. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53293. if ( renderTarget.isWebGLCubeRenderTarget ) {
  53294. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  53295. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  53296. } else {
  53297. framebuffer = __webglFramebuffer[ activeCubeFace ];
  53298. }
  53299. isCube = true;
  53300. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  53301. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  53302. } else {
  53303. if ( Array.isArray( __webglFramebuffer ) ) {
  53304. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  53305. } else {
  53306. framebuffer = __webglFramebuffer;
  53307. }
  53308. }
  53309. _currentViewport.copy( renderTarget.viewport );
  53310. _currentScissor.copy( renderTarget.scissor );
  53311. _currentScissorTest = renderTarget.scissorTest;
  53312. } else {
  53313. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  53314. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  53315. _currentScissorTest = _scissorTest;
  53316. }
  53317. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  53318. // being bound that are different sizes.
  53319. if ( activeMipmapLevel !== 0 ) {
  53320. framebuffer = _scratchFrameBuffer;
  53321. }
  53322. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53323. if ( framebufferBound && useDefaultFramebuffer ) {
  53324. state.drawBuffers( renderTarget, framebuffer );
  53325. }
  53326. state.viewport( _currentViewport );
  53327. state.scissor( _currentScissor );
  53328. state.setScissorTest( _currentScissorTest );
  53329. if ( isCube ) {
  53330. const textureProperties = properties.get( renderTarget.texture );
  53331. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  53332. } else if ( isRenderTarget3D ) {
  53333. const layer = activeCubeFace;
  53334. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  53335. const textureProperties = properties.get( renderTarget.textures[ i ] );
  53336. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  53337. }
  53338. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  53339. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  53340. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  53341. const textureProperties = properties.get( renderTarget.texture );
  53342. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  53343. }
  53344. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  53345. };
  53346. /**
  53347. * Reads the pixel data from the given render target into the given buffer.
  53348. *
  53349. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53350. * @param {number} x - The `x` coordinate of the copy region's origin.
  53351. * @param {number} y - The `y` coordinate of the copy region's origin.
  53352. * @param {number} width - The width of the copy region.
  53353. * @param {number} height - The height of the copy region.
  53354. * @param {TypedArray} buffer - The result buffer.
  53355. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53356. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53357. */
  53358. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53359. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53360. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53361. return;
  53362. }
  53363. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53364. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53365. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53366. }
  53367. if ( framebuffer ) {
  53368. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53369. try {
  53370. const texture = renderTarget.textures[ textureIndex ];
  53371. const textureFormat = texture.format;
  53372. const textureType = texture.type;
  53373. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53374. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  53375. return;
  53376. }
  53377. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53378. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53379. return;
  53380. }
  53381. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53382. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53383. // when using MRT, select the correct color buffer for the subsequent read command
  53384. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53385. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  53386. }
  53387. } finally {
  53388. // restore framebuffer of current render target if necessary
  53389. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53390. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53391. }
  53392. }
  53393. };
  53394. /**
  53395. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  53396. *
  53397. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  53398. *
  53399. * @async
  53400. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53401. * @param {number} x - The `x` coordinate of the copy region's origin.
  53402. * @param {number} y - The `y` coordinate of the copy region's origin.
  53403. * @param {number} width - The width of the copy region.
  53404. * @param {number} height - The height of the copy region.
  53405. * @param {TypedArray} buffer - The result buffer.
  53406. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53407. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53408. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  53409. */
  53410. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53411. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53412. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53413. }
  53414. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53415. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53416. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53417. }
  53418. if ( framebuffer ) {
  53419. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53420. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53421. // set the active frame buffer to the one we want to read
  53422. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53423. const texture = renderTarget.textures[ textureIndex ];
  53424. const textureFormat = texture.format;
  53425. const textureType = texture.type;
  53426. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53427. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  53428. }
  53429. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53430. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53431. }
  53432. const glBuffer = _gl.createBuffer();
  53433. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53434. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  53435. // when using MRT, select the correct color buffer for the subsequent read command
  53436. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53437. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  53438. // reset the frame buffer to the currently set buffer before waiting
  53439. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53440. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  53441. // check if the commands have finished every 8 ms
  53442. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  53443. _gl.flush();
  53444. await probeAsync( _gl, sync, 4 );
  53445. // read the data and delete the buffer
  53446. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53447. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  53448. _gl.deleteBuffer( glBuffer );
  53449. _gl.deleteSync( sync );
  53450. return buffer;
  53451. } else {
  53452. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  53453. }
  53454. }
  53455. };
  53456. /**
  53457. * Copies pixels from the current bound framebuffer into the given texture.
  53458. *
  53459. * @param {FramebufferTexture} texture - The texture.
  53460. * @param {?Vector2} [position=null] - The start position of the copy operation.
  53461. * @param {number} [level=0] - The mip level. The default represents the base mip.
  53462. */
  53463. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  53464. const levelScale = Math.pow( 2, - level );
  53465. const width = Math.floor( texture.image.width * levelScale );
  53466. const height = Math.floor( texture.image.height * levelScale );
  53467. const x = position !== null ? position.x : 0;
  53468. const y = position !== null ? position.y : 0;
  53469. textures.setTexture2D( texture, 0 );
  53470. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  53471. state.unbindTexture();
  53472. };
  53473. const _srcFramebuffer = _gl.createFramebuffer();
  53474. const _dstFramebuffer = _gl.createFramebuffer();
  53475. /**
  53476. * Copies data of the given source texture into a destination texture.
  53477. *
  53478. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  53479. * {@link WebGLRenderer#initRenderTarget}.
  53480. *
  53481. * @param {Texture} srcTexture - The source texture.
  53482. * @param {Texture} dstTexture - The destination texture.
  53483. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  53484. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  53485. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  53486. * @param {?number} [dstLevel=null] - The destination mipmap level.
  53487. */
  53488. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  53489. // support the previous signature with just a single dst mipmap level
  53490. if ( dstLevel === null ) {
  53491. if ( srcLevel !== 0 ) {
  53492. // @deprecated, r171
  53493. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  53494. dstLevel = srcLevel;
  53495. srcLevel = 0;
  53496. } else {
  53497. dstLevel = 0;
  53498. }
  53499. }
  53500. // gather the necessary dimensions to copy
  53501. let width, height, depth, minX, minY, minZ;
  53502. let dstX, dstY, dstZ;
  53503. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  53504. if ( srcRegion !== null ) {
  53505. width = srcRegion.max.x - srcRegion.min.x;
  53506. height = srcRegion.max.y - srcRegion.min.y;
  53507. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  53508. minX = srcRegion.min.x;
  53509. minY = srcRegion.min.y;
  53510. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  53511. } else {
  53512. const levelScale = Math.pow( 2, - srcLevel );
  53513. width = Math.floor( image.width * levelScale );
  53514. height = Math.floor( image.height * levelScale );
  53515. if ( srcTexture.isDataArrayTexture ) {
  53516. depth = image.depth;
  53517. } else if ( srcTexture.isData3DTexture ) {
  53518. depth = Math.floor( image.depth * levelScale );
  53519. } else {
  53520. depth = 1;
  53521. }
  53522. minX = 0;
  53523. minY = 0;
  53524. minZ = 0;
  53525. }
  53526. if ( dstPosition !== null ) {
  53527. dstX = dstPosition.x;
  53528. dstY = dstPosition.y;
  53529. dstZ = dstPosition.z;
  53530. } else {
  53531. dstX = 0;
  53532. dstY = 0;
  53533. dstZ = 0;
  53534. }
  53535. // Set up the destination target
  53536. const glFormat = utils.convert( dstTexture.format );
  53537. const glType = utils.convert( dstTexture.type );
  53538. let glTarget;
  53539. if ( dstTexture.isData3DTexture ) {
  53540. textures.setTexture3D( dstTexture, 0 );
  53541. glTarget = _gl.TEXTURE_3D;
  53542. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  53543. textures.setTexture2DArray( dstTexture, 0 );
  53544. glTarget = _gl.TEXTURE_2D_ARRAY;
  53545. } else {
  53546. textures.setTexture2D( dstTexture, 0 );
  53547. glTarget = _gl.TEXTURE_2D;
  53548. }
  53549. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  53550. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  53551. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  53552. // used for copying data from cpu
  53553. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  53554. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  53555. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  53556. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  53557. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  53558. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  53559. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  53560. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  53561. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  53562. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  53563. // set up the src texture
  53564. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  53565. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  53566. if ( srcTexture.isDepthTexture ) {
  53567. const srcTextureProperties = properties.get( srcTexture );
  53568. const dstTextureProperties = properties.get( dstTexture );
  53569. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  53570. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  53571. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  53572. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  53573. for ( let i = 0; i < depth; i ++ ) {
  53574. // if the source or destination are a 3d target then a layer needs to be bound
  53575. if ( isSrc3D ) {
  53576. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  53577. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  53578. }
  53579. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  53580. }
  53581. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53582. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53583. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  53584. // get the appropriate frame buffers
  53585. const srcTextureProperties = properties.get( srcTexture );
  53586. const dstTextureProperties = properties.get( dstTexture );
  53587. // bind the frame buffer targets
  53588. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  53589. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  53590. for ( let i = 0; i < depth; i ++ ) {
  53591. // assign the correct layers and mip maps to the frame buffers
  53592. if ( isSrc3D ) {
  53593. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  53594. } else {
  53595. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  53596. }
  53597. if ( isDst3D ) {
  53598. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  53599. } else {
  53600. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  53601. }
  53602. // copy the data using the fastest function that can achieve the copy
  53603. if ( srcLevel !== 0 ) {
  53604. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  53605. } else if ( isDst3D ) {
  53606. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  53607. } else {
  53608. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  53609. }
  53610. }
  53611. // unbind read, draw buffers
  53612. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53613. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53614. } else {
  53615. if ( isDst3D ) {
  53616. // copy data into the 3d texture
  53617. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  53618. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  53619. } else if ( dstTexture.isCompressedArrayTexture ) {
  53620. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  53621. } else {
  53622. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  53623. }
  53624. } else {
  53625. // copy data into the 2d texture
  53626. if ( srcTexture.isDataTexture ) {
  53627. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  53628. } else if ( srcTexture.isCompressedTexture ) {
  53629. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  53630. } else {
  53631. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  53632. }
  53633. }
  53634. }
  53635. // reset values
  53636. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  53637. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  53638. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  53639. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  53640. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  53641. // Generate mipmaps only when copying level 0
  53642. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53643. _gl.generateMipmap( glTarget );
  53644. }
  53645. state.unbindTexture();
  53646. };
  53647. /**
  53648. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  53649. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  53650. * rendered to.
  53651. *
  53652. * @param {WebGLRenderTarget} target - The render target.
  53653. */
  53654. this.initRenderTarget = function ( target ) {
  53655. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  53656. textures.setupRenderTarget( target );
  53657. }
  53658. };
  53659. /**
  53660. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  53661. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  53662. *
  53663. * @param {Texture} texture - The texture.
  53664. */
  53665. this.initTexture = function ( texture ) {
  53666. if ( texture.isCubeTexture ) {
  53667. textures.setTextureCube( texture, 0 );
  53668. } else if ( texture.isData3DTexture ) {
  53669. textures.setTexture3D( texture, 0 );
  53670. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53671. textures.setTexture2DArray( texture, 0 );
  53672. } else {
  53673. textures.setTexture2D( texture, 0 );
  53674. }
  53675. state.unbindTexture();
  53676. };
  53677. /**
  53678. * Can be used to reset the internal WebGL state. This method is mostly
  53679. * relevant for applications which share a single WebGL context across
  53680. * multiple WebGL libraries.
  53681. */
  53682. this.resetState = function () {
  53683. _currentActiveCubeFace = 0;
  53684. _currentActiveMipmapLevel = 0;
  53685. _currentRenderTarget = null;
  53686. state.reset();
  53687. bindingStates.reset();
  53688. };
  53689. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53690. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53691. }
  53692. }
  53693. /**
  53694. * Defines the coordinate system of the renderer.
  53695. *
  53696. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  53697. *
  53698. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  53699. * @default WebGLCoordinateSystem
  53700. * @readonly
  53701. */
  53702. get coordinateSystem() {
  53703. return WebGLCoordinateSystem;
  53704. }
  53705. /**
  53706. * Defines the output color space of the renderer.
  53707. *
  53708. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  53709. * @default SRGBColorSpace
  53710. */
  53711. get outputColorSpace() {
  53712. return this._outputColorSpace;
  53713. }
  53714. set outputColorSpace( colorSpace ) {
  53715. this._outputColorSpace = colorSpace;
  53716. const gl = this.getContext();
  53717. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  53718. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  53719. }
  53720. }
  53721. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  53722. exports.AddEquation = AddEquation;
  53723. exports.AddOperation = AddOperation;
  53724. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  53725. exports.AdditiveBlending = AdditiveBlending;
  53726. exports.AgXToneMapping = AgXToneMapping;
  53727. exports.AlphaFormat = AlphaFormat;
  53728. exports.AlwaysCompare = AlwaysCompare;
  53729. exports.AlwaysDepth = AlwaysDepth;
  53730. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  53731. exports.AmbientLight = AmbientLight;
  53732. exports.AnimationAction = AnimationAction;
  53733. exports.AnimationClip = AnimationClip;
  53734. exports.AnimationLoader = AnimationLoader;
  53735. exports.AnimationMixer = AnimationMixer;
  53736. exports.AnimationObjectGroup = AnimationObjectGroup;
  53737. exports.AnimationUtils = AnimationUtils;
  53738. exports.ArcCurve = ArcCurve;
  53739. exports.ArrayCamera = ArrayCamera;
  53740. exports.ArrowHelper = ArrowHelper;
  53741. exports.AttachedBindMode = AttachedBindMode;
  53742. exports.Audio = Audio;
  53743. exports.AudioAnalyser = AudioAnalyser;
  53744. exports.AudioContext = AudioContext;
  53745. exports.AudioListener = AudioListener;
  53746. exports.AudioLoader = AudioLoader;
  53747. exports.AxesHelper = AxesHelper;
  53748. exports.BackSide = BackSide;
  53749. exports.BasicDepthPacking = BasicDepthPacking;
  53750. exports.BasicShadowMap = BasicShadowMap;
  53751. exports.BatchedMesh = BatchedMesh;
  53752. exports.Bone = Bone;
  53753. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  53754. exports.Box2 = Box2;
  53755. exports.Box3 = Box3;
  53756. exports.Box3Helper = Box3Helper;
  53757. exports.BoxGeometry = BoxGeometry;
  53758. exports.BoxHelper = BoxHelper;
  53759. exports.BufferAttribute = BufferAttribute;
  53760. exports.BufferGeometry = BufferGeometry;
  53761. exports.BufferGeometryLoader = BufferGeometryLoader;
  53762. exports.ByteType = ByteType;
  53763. exports.Cache = Cache;
  53764. exports.Camera = Camera;
  53765. exports.CameraHelper = CameraHelper;
  53766. exports.CanvasTexture = CanvasTexture;
  53767. exports.CapsuleGeometry = CapsuleGeometry;
  53768. exports.CatmullRomCurve3 = CatmullRomCurve3;
  53769. exports.CineonToneMapping = CineonToneMapping;
  53770. exports.CircleGeometry = CircleGeometry;
  53771. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  53772. exports.Clock = Clock;
  53773. exports.Color = Color;
  53774. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  53775. exports.ColorManagement = ColorManagement;
  53776. exports.CompressedArrayTexture = CompressedArrayTexture;
  53777. exports.CompressedCubeTexture = CompressedCubeTexture;
  53778. exports.CompressedTexture = CompressedTexture;
  53779. exports.CompressedTextureLoader = CompressedTextureLoader;
  53780. exports.ConeGeometry = ConeGeometry;
  53781. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  53782. exports.ConstantColorFactor = ConstantColorFactor;
  53783. exports.Controls = Controls;
  53784. exports.CubeCamera = CubeCamera;
  53785. exports.CubeReflectionMapping = CubeReflectionMapping;
  53786. exports.CubeRefractionMapping = CubeRefractionMapping;
  53787. exports.CubeTexture = CubeTexture;
  53788. exports.CubeTextureLoader = CubeTextureLoader;
  53789. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  53790. exports.CubicBezierCurve = CubicBezierCurve;
  53791. exports.CubicBezierCurve3 = CubicBezierCurve3;
  53792. exports.CubicInterpolant = CubicInterpolant;
  53793. exports.CullFaceBack = CullFaceBack;
  53794. exports.CullFaceFront = CullFaceFront;
  53795. exports.CullFaceFrontBack = CullFaceFrontBack;
  53796. exports.CullFaceNone = CullFaceNone;
  53797. exports.Curve = Curve;
  53798. exports.CurvePath = CurvePath;
  53799. exports.CustomBlending = CustomBlending;
  53800. exports.CustomToneMapping = CustomToneMapping;
  53801. exports.CylinderGeometry = CylinderGeometry;
  53802. exports.Cylindrical = Cylindrical;
  53803. exports.Data3DTexture = Data3DTexture;
  53804. exports.DataArrayTexture = DataArrayTexture;
  53805. exports.DataTexture = DataTexture;
  53806. exports.DataTextureLoader = DataTextureLoader;
  53807. exports.DataUtils = DataUtils;
  53808. exports.DecrementStencilOp = DecrementStencilOp;
  53809. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  53810. exports.DefaultLoadingManager = DefaultLoadingManager;
  53811. exports.DepthFormat = DepthFormat;
  53812. exports.DepthStencilFormat = DepthStencilFormat;
  53813. exports.DepthTexture = DepthTexture;
  53814. exports.DetachedBindMode = DetachedBindMode;
  53815. exports.DirectionalLight = DirectionalLight;
  53816. exports.DirectionalLightHelper = DirectionalLightHelper;
  53817. exports.DiscreteInterpolant = DiscreteInterpolant;
  53818. exports.DodecahedronGeometry = DodecahedronGeometry;
  53819. exports.DoubleSide = DoubleSide;
  53820. exports.DstAlphaFactor = DstAlphaFactor;
  53821. exports.DstColorFactor = DstColorFactor;
  53822. exports.DynamicCopyUsage = DynamicCopyUsage;
  53823. exports.DynamicDrawUsage = DynamicDrawUsage;
  53824. exports.DynamicReadUsage = DynamicReadUsage;
  53825. exports.EdgesGeometry = EdgesGeometry;
  53826. exports.EllipseCurve = EllipseCurve;
  53827. exports.EqualCompare = EqualCompare;
  53828. exports.EqualDepth = EqualDepth;
  53829. exports.EqualStencilFunc = EqualStencilFunc;
  53830. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  53831. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  53832. exports.Euler = Euler;
  53833. exports.EventDispatcher = EventDispatcher;
  53834. exports.ExtrudeGeometry = ExtrudeGeometry;
  53835. exports.FileLoader = FileLoader;
  53836. exports.Float16BufferAttribute = Float16BufferAttribute;
  53837. exports.Float32BufferAttribute = Float32BufferAttribute;
  53838. exports.FloatType = FloatType;
  53839. exports.Fog = Fog;
  53840. exports.FogExp2 = FogExp2;
  53841. exports.FramebufferTexture = FramebufferTexture;
  53842. exports.FrontSide = FrontSide;
  53843. exports.Frustum = Frustum;
  53844. exports.FrustumArray = FrustumArray;
  53845. exports.GLBufferAttribute = GLBufferAttribute;
  53846. exports.GLSL1 = GLSL1;
  53847. exports.GLSL3 = GLSL3;
  53848. exports.GreaterCompare = GreaterCompare;
  53849. exports.GreaterDepth = GreaterDepth;
  53850. exports.GreaterEqualCompare = GreaterEqualCompare;
  53851. exports.GreaterEqualDepth = GreaterEqualDepth;
  53852. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  53853. exports.GreaterStencilFunc = GreaterStencilFunc;
  53854. exports.GridHelper = GridHelper;
  53855. exports.Group = Group;
  53856. exports.HalfFloatType = HalfFloatType;
  53857. exports.HemisphereLight = HemisphereLight;
  53858. exports.HemisphereLightHelper = HemisphereLightHelper;
  53859. exports.IcosahedronGeometry = IcosahedronGeometry;
  53860. exports.ImageBitmapLoader = ImageBitmapLoader;
  53861. exports.ImageLoader = ImageLoader;
  53862. exports.ImageUtils = ImageUtils;
  53863. exports.IncrementStencilOp = IncrementStencilOp;
  53864. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  53865. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  53866. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  53867. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  53868. exports.InstancedMesh = InstancedMesh;
  53869. exports.Int16BufferAttribute = Int16BufferAttribute;
  53870. exports.Int32BufferAttribute = Int32BufferAttribute;
  53871. exports.Int8BufferAttribute = Int8BufferAttribute;
  53872. exports.IntType = IntType;
  53873. exports.InterleavedBuffer = InterleavedBuffer;
  53874. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  53875. exports.Interpolant = Interpolant;
  53876. exports.InterpolateDiscrete = InterpolateDiscrete;
  53877. exports.InterpolateLinear = InterpolateLinear;
  53878. exports.InterpolateSmooth = InterpolateSmooth;
  53879. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  53880. exports.InterpolationSamplingType = InterpolationSamplingType;
  53881. exports.InvertStencilOp = InvertStencilOp;
  53882. exports.KeepStencilOp = KeepStencilOp;
  53883. exports.KeyframeTrack = KeyframeTrack;
  53884. exports.LOD = LOD;
  53885. exports.LatheGeometry = LatheGeometry;
  53886. exports.Layers = Layers;
  53887. exports.LessCompare = LessCompare;
  53888. exports.LessDepth = LessDepth;
  53889. exports.LessEqualCompare = LessEqualCompare;
  53890. exports.LessEqualDepth = LessEqualDepth;
  53891. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  53892. exports.LessStencilFunc = LessStencilFunc;
  53893. exports.Light = Light;
  53894. exports.LightProbe = LightProbe;
  53895. exports.Line = Line;
  53896. exports.Line3 = Line3;
  53897. exports.LineBasicMaterial = LineBasicMaterial;
  53898. exports.LineCurve = LineCurve;
  53899. exports.LineCurve3 = LineCurve3;
  53900. exports.LineDashedMaterial = LineDashedMaterial;
  53901. exports.LineLoop = LineLoop;
  53902. exports.LineSegments = LineSegments;
  53903. exports.LinearFilter = LinearFilter;
  53904. exports.LinearInterpolant = LinearInterpolant;
  53905. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  53906. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  53907. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  53908. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  53909. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  53910. exports.LinearToneMapping = LinearToneMapping;
  53911. exports.LinearTransfer = LinearTransfer;
  53912. exports.Loader = Loader;
  53913. exports.LoaderUtils = LoaderUtils;
  53914. exports.LoadingManager = LoadingManager;
  53915. exports.LoopOnce = LoopOnce;
  53916. exports.LoopPingPong = LoopPingPong;
  53917. exports.LoopRepeat = LoopRepeat;
  53918. exports.MOUSE = MOUSE;
  53919. exports.Material = Material;
  53920. exports.MaterialLoader = MaterialLoader;
  53921. exports.MathUtils = MathUtils;
  53922. exports.Matrix2 = Matrix2;
  53923. exports.Matrix3 = Matrix3;
  53924. exports.Matrix4 = Matrix4;
  53925. exports.MaxEquation = MaxEquation;
  53926. exports.Mesh = Mesh;
  53927. exports.MeshBasicMaterial = MeshBasicMaterial;
  53928. exports.MeshDepthMaterial = MeshDepthMaterial;
  53929. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  53930. exports.MeshLambertMaterial = MeshLambertMaterial;
  53931. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  53932. exports.MeshNormalMaterial = MeshNormalMaterial;
  53933. exports.MeshPhongMaterial = MeshPhongMaterial;
  53934. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  53935. exports.MeshStandardMaterial = MeshStandardMaterial;
  53936. exports.MeshToonMaterial = MeshToonMaterial;
  53937. exports.MinEquation = MinEquation;
  53938. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  53939. exports.MixOperation = MixOperation;
  53940. exports.MultiplyBlending = MultiplyBlending;
  53941. exports.MultiplyOperation = MultiplyOperation;
  53942. exports.NearestFilter = NearestFilter;
  53943. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  53944. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  53945. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  53946. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  53947. exports.NeutralToneMapping = NeutralToneMapping;
  53948. exports.NeverCompare = NeverCompare;
  53949. exports.NeverDepth = NeverDepth;
  53950. exports.NeverStencilFunc = NeverStencilFunc;
  53951. exports.NoBlending = NoBlending;
  53952. exports.NoColorSpace = NoColorSpace;
  53953. exports.NoToneMapping = NoToneMapping;
  53954. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  53955. exports.NormalBlending = NormalBlending;
  53956. exports.NotEqualCompare = NotEqualCompare;
  53957. exports.NotEqualDepth = NotEqualDepth;
  53958. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  53959. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  53960. exports.Object3D = Object3D;
  53961. exports.ObjectLoader = ObjectLoader;
  53962. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  53963. exports.OctahedronGeometry = OctahedronGeometry;
  53964. exports.OneFactor = OneFactor;
  53965. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  53966. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  53967. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  53968. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  53969. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  53970. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  53971. exports.OrthographicCamera = OrthographicCamera;
  53972. exports.PCFShadowMap = PCFShadowMap;
  53973. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  53974. exports.PMREMGenerator = PMREMGenerator;
  53975. exports.Path = Path;
  53976. exports.PerspectiveCamera = PerspectiveCamera;
  53977. exports.Plane = Plane;
  53978. exports.PlaneGeometry = PlaneGeometry;
  53979. exports.PlaneHelper = PlaneHelper;
  53980. exports.PointLight = PointLight;
  53981. exports.PointLightHelper = PointLightHelper;
  53982. exports.Points = Points;
  53983. exports.PointsMaterial = PointsMaterial;
  53984. exports.PolarGridHelper = PolarGridHelper;
  53985. exports.PolyhedronGeometry = PolyhedronGeometry;
  53986. exports.PositionalAudio = PositionalAudio;
  53987. exports.PropertyBinding = PropertyBinding;
  53988. exports.PropertyMixer = PropertyMixer;
  53989. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  53990. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  53991. exports.Quaternion = Quaternion;
  53992. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  53993. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  53994. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  53995. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  53996. exports.REVISION = REVISION;
  53997. exports.RGBADepthPacking = RGBADepthPacking;
  53998. exports.RGBAFormat = RGBAFormat;
  53999. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54000. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54001. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54002. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54003. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54004. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54005. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54006. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54007. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54008. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54009. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54010. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54011. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54012. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54013. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54014. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54015. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54016. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54017. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54018. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54019. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54020. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54021. exports.RGBDepthPacking = RGBDepthPacking;
  54022. exports.RGBFormat = RGBFormat;
  54023. exports.RGBIntegerFormat = RGBIntegerFormat;
  54024. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54025. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54026. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54027. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54028. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54029. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54030. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54031. exports.RGDepthPacking = RGDepthPacking;
  54032. exports.RGFormat = RGFormat;
  54033. exports.RGIntegerFormat = RGIntegerFormat;
  54034. exports.RawShaderMaterial = RawShaderMaterial;
  54035. exports.Ray = Ray;
  54036. exports.Raycaster = Raycaster;
  54037. exports.RectAreaLight = RectAreaLight;
  54038. exports.RedFormat = RedFormat;
  54039. exports.RedIntegerFormat = RedIntegerFormat;
  54040. exports.ReinhardToneMapping = ReinhardToneMapping;
  54041. exports.RenderTarget = RenderTarget;
  54042. exports.RenderTarget3D = RenderTarget3D;
  54043. exports.RepeatWrapping = RepeatWrapping;
  54044. exports.ReplaceStencilOp = ReplaceStencilOp;
  54045. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54046. exports.RingGeometry = RingGeometry;
  54047. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54048. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54049. exports.SRGBColorSpace = SRGBColorSpace;
  54050. exports.SRGBTransfer = SRGBTransfer;
  54051. exports.Scene = Scene;
  54052. exports.ShaderChunk = ShaderChunk;
  54053. exports.ShaderLib = ShaderLib;
  54054. exports.ShaderMaterial = ShaderMaterial;
  54055. exports.ShadowMaterial = ShadowMaterial;
  54056. exports.Shape = Shape;
  54057. exports.ShapeGeometry = ShapeGeometry;
  54058. exports.ShapePath = ShapePath;
  54059. exports.ShapeUtils = ShapeUtils;
  54060. exports.ShortType = ShortType;
  54061. exports.Skeleton = Skeleton;
  54062. exports.SkeletonHelper = SkeletonHelper;
  54063. exports.SkinnedMesh = SkinnedMesh;
  54064. exports.Source = Source;
  54065. exports.Sphere = Sphere;
  54066. exports.SphereGeometry = SphereGeometry;
  54067. exports.Spherical = Spherical;
  54068. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54069. exports.SplineCurve = SplineCurve;
  54070. exports.SpotLight = SpotLight;
  54071. exports.SpotLightHelper = SpotLightHelper;
  54072. exports.Sprite = Sprite;
  54073. exports.SpriteMaterial = SpriteMaterial;
  54074. exports.SrcAlphaFactor = SrcAlphaFactor;
  54075. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54076. exports.SrcColorFactor = SrcColorFactor;
  54077. exports.StaticCopyUsage = StaticCopyUsage;
  54078. exports.StaticDrawUsage = StaticDrawUsage;
  54079. exports.StaticReadUsage = StaticReadUsage;
  54080. exports.StereoCamera = StereoCamera;
  54081. exports.StreamCopyUsage = StreamCopyUsage;
  54082. exports.StreamDrawUsage = StreamDrawUsage;
  54083. exports.StreamReadUsage = StreamReadUsage;
  54084. exports.StringKeyframeTrack = StringKeyframeTrack;
  54085. exports.SubtractEquation = SubtractEquation;
  54086. exports.SubtractiveBlending = SubtractiveBlending;
  54087. exports.TOUCH = TOUCH;
  54088. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54089. exports.TetrahedronGeometry = TetrahedronGeometry;
  54090. exports.Texture = Texture;
  54091. exports.TextureLoader = TextureLoader;
  54092. exports.TextureUtils = TextureUtils;
  54093. exports.Timer = Timer;
  54094. exports.TimestampQuery = TimestampQuery;
  54095. exports.TorusGeometry = TorusGeometry;
  54096. exports.TorusKnotGeometry = TorusKnotGeometry;
  54097. exports.Triangle = Triangle;
  54098. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54099. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54100. exports.TrianglesDrawMode = TrianglesDrawMode;
  54101. exports.TubeGeometry = TubeGeometry;
  54102. exports.UVMapping = UVMapping;
  54103. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54104. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54105. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54106. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54107. exports.Uniform = Uniform;
  54108. exports.UniformsGroup = UniformsGroup;
  54109. exports.UniformsLib = UniformsLib;
  54110. exports.UniformsUtils = UniformsUtils;
  54111. exports.UnsignedByteType = UnsignedByteType;
  54112. exports.UnsignedInt248Type = UnsignedInt248Type;
  54113. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54114. exports.UnsignedIntType = UnsignedIntType;
  54115. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54116. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54117. exports.UnsignedShortType = UnsignedShortType;
  54118. exports.VSMShadowMap = VSMShadowMap;
  54119. exports.Vector2 = Vector2;
  54120. exports.Vector3 = Vector3;
  54121. exports.Vector4 = Vector4;
  54122. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54123. exports.VideoFrameTexture = VideoFrameTexture;
  54124. exports.VideoTexture = VideoTexture;
  54125. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54126. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54127. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54128. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54129. exports.WebGLRenderTarget = WebGLRenderTarget;
  54130. exports.WebGLRenderer = WebGLRenderer;
  54131. exports.WebGLUtils = WebGLUtils;
  54132. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54133. exports.WebXRController = WebXRController;
  54134. exports.WireframeGeometry = WireframeGeometry;
  54135. exports.WrapAroundEnding = WrapAroundEnding;
  54136. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54137. exports.ZeroFactor = ZeroFactor;
  54138. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54139. exports.ZeroStencilOp = ZeroStencilOp;
  54140. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号