three.cjs 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '174dev';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const ConstantColorFactor = 211;
  44. const OneMinusConstantColorFactor = 212;
  45. const ConstantAlphaFactor = 213;
  46. const OneMinusConstantAlphaFactor = 214;
  47. const NeverDepth = 0;
  48. const AlwaysDepth = 1;
  49. const LessDepth = 2;
  50. const LessEqualDepth = 3;
  51. const EqualDepth = 4;
  52. const GreaterEqualDepth = 5;
  53. const GreaterDepth = 6;
  54. const NotEqualDepth = 7;
  55. const MultiplyOperation = 0;
  56. const MixOperation = 1;
  57. const AddOperation = 2;
  58. const NoToneMapping = 0;
  59. const LinearToneMapping = 1;
  60. const ReinhardToneMapping = 2;
  61. const CineonToneMapping = 3;
  62. const ACESFilmicToneMapping = 4;
  63. const CustomToneMapping = 5;
  64. const AgXToneMapping = 6;
  65. const NeutralToneMapping = 7;
  66. const AttachedBindMode = 'attached';
  67. const DetachedBindMode = 'detached';
  68. const UVMapping = 300;
  69. const CubeReflectionMapping = 301;
  70. const CubeRefractionMapping = 302;
  71. const EquirectangularReflectionMapping = 303;
  72. const EquirectangularRefractionMapping = 304;
  73. const CubeUVReflectionMapping = 306;
  74. const RepeatWrapping = 1000;
  75. const ClampToEdgeWrapping = 1001;
  76. const MirroredRepeatWrapping = 1002;
  77. const NearestFilter = 1003;
  78. const NearestMipmapNearestFilter = 1004;
  79. const NearestMipMapNearestFilter = 1004;
  80. const NearestMipmapLinearFilter = 1005;
  81. const NearestMipMapLinearFilter = 1005;
  82. const LinearFilter = 1006;
  83. const LinearMipmapNearestFilter = 1007;
  84. const LinearMipMapNearestFilter = 1007;
  85. const LinearMipmapLinearFilter = 1008;
  86. const LinearMipMapLinearFilter = 1008;
  87. const UnsignedByteType = 1009;
  88. const ByteType = 1010;
  89. const ShortType = 1011;
  90. const UnsignedShortType = 1012;
  91. const IntType = 1013;
  92. const UnsignedIntType = 1014;
  93. const FloatType = 1015;
  94. const HalfFloatType = 1016;
  95. const UnsignedShort4444Type = 1017;
  96. const UnsignedShort5551Type = 1018;
  97. const UnsignedInt248Type = 1020;
  98. const UnsignedInt5999Type = 35902;
  99. const AlphaFormat = 1021;
  100. const RGBFormat = 1022;
  101. const RGBAFormat = 1023;
  102. const LuminanceFormat = 1024;
  103. const LuminanceAlphaFormat = 1025;
  104. const DepthFormat = 1026;
  105. const DepthStencilFormat = 1027;
  106. const RedFormat = 1028;
  107. const RedIntegerFormat = 1029;
  108. const RGFormat = 1030;
  109. const RGIntegerFormat = 1031;
  110. const RGBIntegerFormat = 1032;
  111. const RGBAIntegerFormat = 1033;
  112. const RGB_S3TC_DXT1_Format = 33776;
  113. const RGBA_S3TC_DXT1_Format = 33777;
  114. const RGBA_S3TC_DXT3_Format = 33778;
  115. const RGBA_S3TC_DXT5_Format = 33779;
  116. const RGB_PVRTC_4BPPV1_Format = 35840;
  117. const RGB_PVRTC_2BPPV1_Format = 35841;
  118. const RGBA_PVRTC_4BPPV1_Format = 35842;
  119. const RGBA_PVRTC_2BPPV1_Format = 35843;
  120. const RGB_ETC1_Format = 36196;
  121. const RGB_ETC2_Format = 37492;
  122. const RGBA_ETC2_EAC_Format = 37496;
  123. const RGBA_ASTC_4x4_Format = 37808;
  124. const RGBA_ASTC_5x4_Format = 37809;
  125. const RGBA_ASTC_5x5_Format = 37810;
  126. const RGBA_ASTC_6x5_Format = 37811;
  127. const RGBA_ASTC_6x6_Format = 37812;
  128. const RGBA_ASTC_8x5_Format = 37813;
  129. const RGBA_ASTC_8x6_Format = 37814;
  130. const RGBA_ASTC_8x8_Format = 37815;
  131. const RGBA_ASTC_10x5_Format = 37816;
  132. const RGBA_ASTC_10x6_Format = 37817;
  133. const RGBA_ASTC_10x8_Format = 37818;
  134. const RGBA_ASTC_10x10_Format = 37819;
  135. const RGBA_ASTC_12x10_Format = 37820;
  136. const RGBA_ASTC_12x12_Format = 37821;
  137. const RGBA_BPTC_Format = 36492;
  138. const RGB_BPTC_SIGNED_Format = 36494;
  139. const RGB_BPTC_UNSIGNED_Format = 36495;
  140. const RED_RGTC1_Format = 36283;
  141. const SIGNED_RED_RGTC1_Format = 36284;
  142. const RED_GREEN_RGTC2_Format = 36285;
  143. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  144. const LoopOnce = 2200;
  145. const LoopRepeat = 2201;
  146. const LoopPingPong = 2202;
  147. const InterpolateDiscrete = 2300;
  148. const InterpolateLinear = 2301;
  149. const InterpolateSmooth = 2302;
  150. const ZeroCurvatureEnding = 2400;
  151. const ZeroSlopeEnding = 2401;
  152. const WrapAroundEnding = 2402;
  153. const NormalAnimationBlendMode = 2500;
  154. const AdditiveAnimationBlendMode = 2501;
  155. const TrianglesDrawMode = 0;
  156. const TriangleStripDrawMode = 1;
  157. const TriangleFanDrawMode = 2;
  158. const BasicDepthPacking = 3200;
  159. const RGBADepthPacking = 3201;
  160. const RGBDepthPacking = 3202;
  161. const RGDepthPacking = 3203;
  162. const TangentSpaceNormalMap = 0;
  163. const ObjectSpaceNormalMap = 1;
  164. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  165. const NoColorSpace = '';
  166. const SRGBColorSpace = 'srgb';
  167. const LinearSRGBColorSpace = 'srgb-linear';
  168. const LinearTransfer = 'linear';
  169. const SRGBTransfer = 'srgb';
  170. const ZeroStencilOp = 0;
  171. const KeepStencilOp = 7680;
  172. const ReplaceStencilOp = 7681;
  173. const IncrementStencilOp = 7682;
  174. const DecrementStencilOp = 7683;
  175. const IncrementWrapStencilOp = 34055;
  176. const DecrementWrapStencilOp = 34056;
  177. const InvertStencilOp = 5386;
  178. const NeverStencilFunc = 512;
  179. const LessStencilFunc = 513;
  180. const EqualStencilFunc = 514;
  181. const LessEqualStencilFunc = 515;
  182. const GreaterStencilFunc = 516;
  183. const NotEqualStencilFunc = 517;
  184. const GreaterEqualStencilFunc = 518;
  185. const AlwaysStencilFunc = 519;
  186. const NeverCompare = 512;
  187. const LessCompare = 513;
  188. const EqualCompare = 514;
  189. const LessEqualCompare = 515;
  190. const GreaterCompare = 516;
  191. const NotEqualCompare = 517;
  192. const GreaterEqualCompare = 518;
  193. const AlwaysCompare = 519;
  194. const StaticDrawUsage = 35044;
  195. const DynamicDrawUsage = 35048;
  196. const StreamDrawUsage = 35040;
  197. const StaticReadUsage = 35045;
  198. const DynamicReadUsage = 35049;
  199. const StreamReadUsage = 35041;
  200. const StaticCopyUsage = 35046;
  201. const DynamicCopyUsage = 35050;
  202. const StreamCopyUsage = 35042;
  203. const GLSL1 = '100';
  204. const GLSL3 = '300 es';
  205. const WebGLCoordinateSystem = 2000;
  206. const WebGPUCoordinateSystem = 2001;
  207. const TimestampQuery = {
  208. COMPUTE: 'compute',
  209. RENDER: 'render'
  210. };
  211. /**
  212. * This modules allows to dispatch event objects on custom JavaScript objects.
  213. *
  214. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  215. *
  216. * Code Example:
  217. * ```js
  218. * class Car extends EventDispatcher {
  219. * start() {
  220. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  221. * }
  222. *};
  223. *
  224. * // Using events with the custom object
  225. * const car = new Car();
  226. * car.addEventListener( 'start', function ( event ) {
  227. * alert( event.message );
  228. * } );
  229. *
  230. * car.start();
  231. * ```
  232. */
  233. class EventDispatcher {
  234. /**
  235. * Adds the given event listener to the given event type.
  236. *
  237. * @param {string} type - The type of event to listen to.
  238. * @param {Function} listener - The function that gets called when the event is fired.
  239. */
  240. addEventListener( type, listener ) {
  241. if ( this._listeners === undefined ) this._listeners = {};
  242. const listeners = this._listeners;
  243. if ( listeners[ type ] === undefined ) {
  244. listeners[ type ] = [];
  245. }
  246. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  247. listeners[ type ].push( listener );
  248. }
  249. }
  250. /**
  251. * Returns `true` if the given event listener has been added to the given event type.
  252. *
  253. * @param {string} type - The type of event.
  254. * @param {Function} listener - The listener to check.
  255. * @return {boolean} Whether the given event listener has been added to the given event type.
  256. */
  257. hasEventListener( type, listener ) {
  258. const listeners = this._listeners;
  259. if ( listeners === undefined ) return false;
  260. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  261. }
  262. /**
  263. * Removes the given event listener from the given event type.
  264. *
  265. * @param {string} type - The type of event.
  266. * @param {Function} listener - The listener to remove.
  267. */
  268. removeEventListener( type, listener ) {
  269. const listeners = this._listeners;
  270. if ( listeners === undefined ) return;
  271. const listenerArray = listeners[ type ];
  272. if ( listenerArray !== undefined ) {
  273. const index = listenerArray.indexOf( listener );
  274. if ( index !== -1 ) {
  275. listenerArray.splice( index, 1 );
  276. }
  277. }
  278. }
  279. /**
  280. * Dispatches an event object.
  281. *
  282. * @param {Object} event - The event that gets fired.
  283. */
  284. dispatchEvent( event ) {
  285. const listeners = this._listeners;
  286. if ( listeners === undefined ) return;
  287. const listenerArray = listeners[ event.type ];
  288. if ( listenerArray !== undefined ) {
  289. event.target = this;
  290. // Make a copy, in case listeners are removed while iterating.
  291. const array = listenerArray.slice( 0 );
  292. for ( let i = 0, l = array.length; i < l; i ++ ) {
  293. array[ i ].call( this, event );
  294. }
  295. event.target = null;
  296. }
  297. }
  298. }
  299. 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' ];
  300. let _seed = 1234567;
  301. const DEG2RAD = Math.PI / 180;
  302. const RAD2DEG = 180 / Math.PI;
  303. /**
  304. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  305. * (universally unique identifier).
  306. *
  307. * @return {string} The UUID.
  308. */
  309. function generateUUID() {
  310. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  311. const d0 = Math.random() * 0xffffffff | 0;
  312. const d1 = Math.random() * 0xffffffff | 0;
  313. const d2 = Math.random() * 0xffffffff | 0;
  314. const d3 = Math.random() * 0xffffffff | 0;
  315. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  316. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  317. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  318. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  319. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  320. return uuid.toLowerCase();
  321. }
  322. /**
  323. * Clamps the given value between min and max.
  324. *
  325. * @param {number} value - The value to clamp.
  326. * @param {number} min - The min value.
  327. * @param {number} max - The max value.
  328. * @return {number} The clamped value.
  329. */
  330. function clamp( value, min, max ) {
  331. return Math.max( min, Math.min( max, value ) );
  332. }
  333. /**
  334. * Computes the Euclidean modulo of the given parameters that
  335. * is `( ( n % m ) + m ) % m`.
  336. *
  337. * @param {number} n - The first parameter.
  338. * @param {number} m - The second parameter.
  339. * @return {number} The Euclidean modulo.
  340. */
  341. function euclideanModulo( n, m ) {
  342. // https://en.wikipedia.org/wiki/Modulo_operation
  343. return ( ( n % m ) + m ) % m;
  344. }
  345. /**
  346. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  347. * for the given value.
  348. *
  349. * @param {number} x - The value to be mapped.
  350. * @param {number} a1 - Minimum value for range A.
  351. * @param {number} a2 - Maximum value for range A.
  352. * @param {number} b1 - Minimum value for range B.
  353. * @param {number} b2 - Maximum value for range B.
  354. * @return {number} The mapped value.
  355. */
  356. function mapLinear( x, a1, a2, b1, b2 ) {
  357. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  358. }
  359. /**
  360. * Returns the percentage in the closed interval `[0, 1]` of the given value
  361. * between the start and end point.
  362. *
  363. * @param {number} x - The start point
  364. * @param {number} y - The end point.
  365. * @param {number} value - A value between start and end.
  366. * @return {number} The interpolation factor.
  367. */
  368. function inverseLerp( x, y, value ) {
  369. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  370. if ( x !== y ) {
  371. return ( value - x ) / ( y - x );
  372. } else {
  373. return 0;
  374. }
  375. }
  376. /**
  377. * Returns a value linearly interpolated from two known points based on the given interval -
  378. * `t = 0` will return `x` and `t = 1` will return `y`.
  379. *
  380. * @param {number} x - The start point
  381. * @param {number} y - The end point.
  382. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  383. * @return {number} The interpolated value.
  384. */
  385. function lerp( x, y, t ) {
  386. return ( 1 - t ) * x + t * y;
  387. }
  388. /**
  389. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  390. * time to maintain frame rate independent movement. For details, see
  391. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  392. *
  393. * @param {number} x - The current point.
  394. * @param {number} y - The target point.
  395. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  396. * and a lower value will make the movement more gradual.
  397. * @param {number} dt - Delta time in seconds.
  398. * @return {number} The interpolated value.
  399. */
  400. function damp( x, y, lambda, dt ) {
  401. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  402. }
  403. /**
  404. * Returns a value that alternates between `0` and the given `length` parameter.
  405. *
  406. * @param {number} x - The value to pingpong.
  407. * @param {number} [length=1] - The positive value the function will pingpong to.
  408. * @return {number} The alternated value.
  409. */
  410. function pingpong( x, length = 1 ) {
  411. // https://www.desmos.com/calculator/vcsjnyz7x4
  412. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  413. }
  414. /**
  415. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  416. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  417. * the `min` and `max`.
  418. *
  419. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  420. *
  421. * @param {number} x - The value to evaluate based on its position between min and max.
  422. * @param {number} min - The min value. Any x value below min will be `0`.
  423. * @param {number} max - The max value. Any x value above max will be `1`.
  424. * @return {number} The alternated value.
  425. */
  426. function smoothstep( x, min, max ) {
  427. if ( x <= min ) return 0;
  428. if ( x >= max ) return 1;
  429. x = ( x - min ) / ( max - min );
  430. return x * x * ( 3 - 2 * x );
  431. }
  432. /**
  433. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  434. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  435. *
  436. * @param {number} x - The value to evaluate based on its position between min and max.
  437. * @param {number} min - The min value. Any x value below min will be `0`.
  438. * @param {number} max - The max value. Any x value above max will be `1`.
  439. * @return {number} The alternated value.
  440. */
  441. function smootherstep( x, min, max ) {
  442. if ( x <= min ) return 0;
  443. if ( x >= max ) return 1;
  444. x = ( x - min ) / ( max - min );
  445. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  446. }
  447. /**
  448. * Returns a random integer from `<low, high>` interval.
  449. *
  450. * @param {number} low - The lower value boundary.
  451. * @param {number} high - The upper value boundary
  452. * @return {number} A random integer.
  453. */
  454. function randInt( low, high ) {
  455. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  456. }
  457. /**
  458. * Returns a random float from `<low, high>` interval.
  459. *
  460. * @param {number} low - The lower value boundary.
  461. * @param {number} high - The upper value boundary
  462. * @return {number} A random float.
  463. */
  464. function randFloat( low, high ) {
  465. return low + Math.random() * ( high - low );
  466. }
  467. /**
  468. * Returns a random integer from `<-range/2, range/2>` interval.
  469. *
  470. * @param {number} range - Defines the value range.
  471. * @return {number} A random float.
  472. */
  473. function randFloatSpread( range ) {
  474. return range * ( 0.5 - Math.random() );
  475. }
  476. /**
  477. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  478. *
  479. * @param {number} [s] - The integer seed.
  480. * @return {number} A random float.
  481. */
  482. function seededRandom( s ) {
  483. if ( s !== undefined ) _seed = s;
  484. // Mulberry32 generator
  485. let t = _seed += 0x6D2B79F5;
  486. t = Math.imul( t ^ t >>> 15, t | 1 );
  487. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  488. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  489. }
  490. /**
  491. * Converts degrees to radians.
  492. *
  493. * @param {number} degrees - A value in degrees.
  494. * @return {number} The converted value in radians.
  495. */
  496. function degToRad( degrees ) {
  497. return degrees * DEG2RAD;
  498. }
  499. /**
  500. * Converts radians to degrees.
  501. *
  502. * @param {number} radians - A value in radians.
  503. * @return {number} The converted value in degrees.
  504. */
  505. function radToDeg( radians ) {
  506. return radians * RAD2DEG;
  507. }
  508. /**
  509. * Returns `true` if the given number is a power of two.
  510. *
  511. * @param {number} value - The value to check.
  512. * @return {boolean} Whether the given number is a power of two or not.
  513. */
  514. function isPowerOfTwo( value ) {
  515. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  516. }
  517. /**
  518. * Returns the smallest power of two that is greater than or equal to the given number.
  519. *
  520. * @param {number} value - The value to find a POT for.
  521. * @return {number} The smallest power of two that is greater than or equal to the given number.
  522. */
  523. function ceilPowerOfTwo( value ) {
  524. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  525. }
  526. /**
  527. * Returns the largest power of two that is less than or equal to the given number.
  528. *
  529. * @param {number} value - The value to find a POT for.
  530. * @return {number} The largest power of two that is less than or equal to the given number.
  531. */
  532. function floorPowerOfTwo( value ) {
  533. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  534. }
  535. /**
  536. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  537. * defined by the given angles and order.
  538. *
  539. * Rotations are applied to the axes in the order specified by order:
  540. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  541. *
  542. * @param {Quaternion} q - The quaternion to set.
  543. * @param {number} a - The rotation applied to the first axis, in radians.
  544. * @param {number} b - The rotation applied to the second axis, in radians.
  545. * @param {number} c - The rotation applied to the third axis, in radians.
  546. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  547. */
  548. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  549. const cos = Math.cos;
  550. const sin = Math.sin;
  551. const c2 = cos( b / 2 );
  552. const s2 = sin( b / 2 );
  553. const c13 = cos( ( a + c ) / 2 );
  554. const s13 = sin( ( a + c ) / 2 );
  555. const c1_3 = cos( ( a - c ) / 2 );
  556. const s1_3 = sin( ( a - c ) / 2 );
  557. const c3_1 = cos( ( c - a ) / 2 );
  558. const s3_1 = sin( ( c - a ) / 2 );
  559. switch ( order ) {
  560. case 'XYX':
  561. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  562. break;
  563. case 'YZY':
  564. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  565. break;
  566. case 'ZXZ':
  567. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  568. break;
  569. case 'XZX':
  570. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  571. break;
  572. case 'YXY':
  573. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  574. break;
  575. case 'ZYZ':
  576. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  577. break;
  578. default:
  579. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  580. }
  581. }
  582. /**
  583. * Denormalizes the given value according to the given typed array.
  584. *
  585. * @param {number} value - The value to denormalize.
  586. * @param {TypedArray} array - The typed array that defines the data type of the value.
  587. * @return {number} The denormalize (float) value in the range `[0,1]`.
  588. */
  589. function denormalize( value, array ) {
  590. switch ( array.constructor ) {
  591. case Float32Array:
  592. return value;
  593. case Uint32Array:
  594. return value / 4294967295.0;
  595. case Uint16Array:
  596. return value / 65535.0;
  597. case Uint8Array:
  598. return value / 255.0;
  599. case Int32Array:
  600. return Math.max( value / 2147483647.0, -1 );
  601. case Int16Array:
  602. return Math.max( value / 32767.0, -1 );
  603. case Int8Array:
  604. return Math.max( value / 127.0, -1 );
  605. default:
  606. throw new Error( 'Invalid component type.' );
  607. }
  608. }
  609. /**
  610. * Normalizes the given value according to the given typed array.
  611. *
  612. * @param {number} value - The float value in the range `[0,1]` to normalize.
  613. * @param {TypedArray} array - The typed array that defines the data type of the value.
  614. * @return {number} The normalize value.
  615. */
  616. function normalize( value, array ) {
  617. switch ( array.constructor ) {
  618. case Float32Array:
  619. return value;
  620. case Uint32Array:
  621. return Math.round( value * 4294967295.0 );
  622. case Uint16Array:
  623. return Math.round( value * 65535.0 );
  624. case Uint8Array:
  625. return Math.round( value * 255.0 );
  626. case Int32Array:
  627. return Math.round( value * 2147483647.0 );
  628. case Int16Array:
  629. return Math.round( value * 32767.0 );
  630. case Int8Array:
  631. return Math.round( value * 127.0 );
  632. default:
  633. throw new Error( 'Invalid component type.' );
  634. }
  635. }
  636. const MathUtils = {
  637. DEG2RAD: DEG2RAD,
  638. RAD2DEG: RAD2DEG,
  639. generateUUID: generateUUID,
  640. clamp: clamp,
  641. euclideanModulo: euclideanModulo,
  642. mapLinear: mapLinear,
  643. inverseLerp: inverseLerp,
  644. lerp: lerp,
  645. damp: damp,
  646. pingpong: pingpong,
  647. smoothstep: smoothstep,
  648. smootherstep: smootherstep,
  649. randInt: randInt,
  650. randFloat: randFloat,
  651. randFloatSpread: randFloatSpread,
  652. seededRandom: seededRandom,
  653. degToRad: degToRad,
  654. radToDeg: radToDeg,
  655. isPowerOfTwo: isPowerOfTwo,
  656. ceilPowerOfTwo: ceilPowerOfTwo,
  657. floorPowerOfTwo: floorPowerOfTwo,
  658. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  659. normalize: normalize,
  660. denormalize: denormalize
  661. };
  662. /**
  663. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  664. * (labeled x and y), which can be used to represent a number of things, such as:
  665. *
  666. * - A point in 2D space (i.e. a position on a plane).
  667. * - A direction and length across a plane. In three.js the length will
  668. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  669. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  670. * - Any arbitrary ordered pair of numbers.
  671. *
  672. * There are other things a 2D vector can be used to represent, such as
  673. * momentum vectors, complex numbers and so on, however these are the most
  674. * common uses in three.js.
  675. *
  676. * Iterating through a vector instance will yield its components `(x, y)` in
  677. * the corresponding order.
  678. * ```js
  679. * const a = new THREE.Vector2( 0, 1 );
  680. *
  681. * //no arguments; will be initialised to (0, 0)
  682. * const b = new THREE.Vector2( );
  683. *
  684. * const d = a.distanceTo( b );
  685. * ```
  686. */
  687. class Vector2 {
  688. /**
  689. * Constructs a new 2D vector.
  690. *
  691. * @param {number} [x=0] - The x value of this vector.
  692. * @param {number} [y=0] - The y value of this vector.
  693. */
  694. constructor( x = 0, y = 0 ) {
  695. /**
  696. * This flag can be used for type testing.
  697. *
  698. * @type {boolean}
  699. * @readonly
  700. * @default true
  701. */
  702. Vector2.prototype.isVector2 = true;
  703. /**
  704. * The x value of this vector.
  705. *
  706. * @type {number}
  707. */
  708. this.x = x;
  709. /**
  710. * The y value of this vector.
  711. *
  712. * @type {number}
  713. */
  714. this.y = y;
  715. }
  716. /**
  717. * Alias for {@link Vector2#x}.
  718. *
  719. * @type {number}
  720. */
  721. get width() {
  722. return this.x;
  723. }
  724. set width( value ) {
  725. this.x = value;
  726. }
  727. /**
  728. * Alias for {@link Vector2#y}.
  729. *
  730. * @type {number}
  731. */
  732. get height() {
  733. return this.y;
  734. }
  735. set height( value ) {
  736. this.y = value;
  737. }
  738. /**
  739. * Sets the vector components.
  740. *
  741. * @param {number} x - The value of the x component.
  742. * @param {number} y - The value of the y component.
  743. * @return {Vector2} A reference to this vector.
  744. */
  745. set( x, y ) {
  746. this.x = x;
  747. this.y = y;
  748. return this;
  749. }
  750. /**
  751. * Sets the vector components to the same value.
  752. *
  753. * @param {number} scalar - The value to set for all vector components.
  754. * @return {Vector2} A reference to this vector.
  755. */
  756. setScalar( scalar ) {
  757. this.x = scalar;
  758. this.y = scalar;
  759. return this;
  760. }
  761. /**
  762. * Sets the vector's x component to the given value
  763. *
  764. * @param {number} x - The value to set.
  765. * @return {Vector2} A reference to this vector.
  766. */
  767. setX( x ) {
  768. this.x = x;
  769. return this;
  770. }
  771. /**
  772. * Sets the vector's y component to the given value
  773. *
  774. * @param {number} y - The value to set.
  775. * @return {Vector2} A reference to this vector.
  776. */
  777. setY( y ) {
  778. this.y = y;
  779. return this;
  780. }
  781. /**
  782. * Allows to set a vector component with an index.
  783. *
  784. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  785. * @param {number} value - The value to set.
  786. * @return {Vector2} A reference to this vector.
  787. */
  788. setComponent( index, value ) {
  789. switch ( index ) {
  790. case 0: this.x = value; break;
  791. case 1: this.y = value; break;
  792. default: throw new Error( 'index is out of range: ' + index );
  793. }
  794. return this;
  795. }
  796. /**
  797. * Returns the value of the vector component which matches the given index.
  798. *
  799. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  800. * @return {number} A vector component value.
  801. */
  802. getComponent( index ) {
  803. switch ( index ) {
  804. case 0: return this.x;
  805. case 1: return this.y;
  806. default: throw new Error( 'index is out of range: ' + index );
  807. }
  808. }
  809. /**
  810. * Returns a new vector with copied values from this instance.
  811. *
  812. * @return {Vector2} A clone of this instance.
  813. */
  814. clone() {
  815. return new this.constructor( this.x, this.y );
  816. }
  817. /**
  818. * Copies the values of the given vector to this instance.
  819. *
  820. * @param {Vector2} v - The vector to copy.
  821. * @return {Vector2} A reference to this vector.
  822. */
  823. copy( v ) {
  824. this.x = v.x;
  825. this.y = v.y;
  826. return this;
  827. }
  828. /**
  829. * Adds the given vector to this instance.
  830. *
  831. * @param {Vector2} v - The vector to add.
  832. * @return {Vector2} A reference to this vector.
  833. */
  834. add( v ) {
  835. this.x += v.x;
  836. this.y += v.y;
  837. return this;
  838. }
  839. /**
  840. * Adds the given scalar value to all components of this instance.
  841. *
  842. * @param {number} s - The scalar to add.
  843. * @return {Vector2} A reference to this vector.
  844. */
  845. addScalar( s ) {
  846. this.x += s;
  847. this.y += s;
  848. return this;
  849. }
  850. /**
  851. * Adds the given vectors and stores the result in this instance.
  852. *
  853. * @param {Vector2} a - The first vector.
  854. * @param {Vector2} b - The second vector.
  855. * @return {Vector2} A reference to this vector.
  856. */
  857. addVectors( a, b ) {
  858. this.x = a.x + b.x;
  859. this.y = a.y + b.y;
  860. return this;
  861. }
  862. /**
  863. * Adds the given vector scaled by the given factor to this instance.
  864. *
  865. * @param {Vector2} v - The vector.
  866. * @param {number} s - The factor that scales `v`.
  867. * @return {Vector2} A reference to this vector.
  868. */
  869. addScaledVector( v, s ) {
  870. this.x += v.x * s;
  871. this.y += v.y * s;
  872. return this;
  873. }
  874. /**
  875. * Subtracts the given vector from this instance.
  876. *
  877. * @param {Vector2} v - The vector to subtract.
  878. * @return {Vector2} A reference to this vector.
  879. */
  880. sub( v ) {
  881. this.x -= v.x;
  882. this.y -= v.y;
  883. return this;
  884. }
  885. /**
  886. * Subtracts the given scalar value from all components of this instance.
  887. *
  888. * @param {number} s - The scalar to subtract.
  889. * @return {Vector2} A reference to this vector.
  890. */
  891. subScalar( s ) {
  892. this.x -= s;
  893. this.y -= s;
  894. return this;
  895. }
  896. /**
  897. * Subtracts the given vectors and stores the result in this instance.
  898. *
  899. * @param {Vector2} a - The first vector.
  900. * @param {Vector2} b - The second vector.
  901. * @return {Vector2} A reference to this vector.
  902. */
  903. subVectors( a, b ) {
  904. this.x = a.x - b.x;
  905. this.y = a.y - b.y;
  906. return this;
  907. }
  908. /**
  909. * Multiplies the given vector with this instance.
  910. *
  911. * @param {Vector2} v - The vector to multiply.
  912. * @return {Vector2} A reference to this vector.
  913. */
  914. multiply( v ) {
  915. this.x *= v.x;
  916. this.y *= v.y;
  917. return this;
  918. }
  919. /**
  920. * Multiplies the given scalar value with all components of this instance.
  921. *
  922. * @param {number} scalar - The scalar to multiply.
  923. * @return {Vector2} A reference to this vector.
  924. */
  925. multiplyScalar( scalar ) {
  926. this.x *= scalar;
  927. this.y *= scalar;
  928. return this;
  929. }
  930. /**
  931. * Divides this instance by the given vector.
  932. *
  933. * @param {Vector2} v - The vector to divide.
  934. * @return {Vector2} A reference to this vector.
  935. */
  936. divide( v ) {
  937. this.x /= v.x;
  938. this.y /= v.y;
  939. return this;
  940. }
  941. /**
  942. * Divides this vector by the given scalar.
  943. *
  944. * @param {number} scalar - The scalar to divide.
  945. * @return {Vector2} A reference to this vector.
  946. */
  947. divideScalar( scalar ) {
  948. return this.multiplyScalar( 1 / scalar );
  949. }
  950. /**
  951. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  952. * the given 3x3 matrix.
  953. *
  954. * @param {Matrix3} m - The matrix to apply.
  955. * @return {Vector2} A reference to this vector.
  956. */
  957. applyMatrix3( m ) {
  958. const x = this.x, y = this.y;
  959. const e = m.elements;
  960. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  961. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  962. return this;
  963. }
  964. /**
  965. * If this vector's x or y value is greater than the given vector's x or y
  966. * value, replace that value with the corresponding min value.
  967. *
  968. * @param {Vector2} v - The vector.
  969. * @return {Vector2} A reference to this vector.
  970. */
  971. min( v ) {
  972. this.x = Math.min( this.x, v.x );
  973. this.y = Math.min( this.y, v.y );
  974. return this;
  975. }
  976. /**
  977. * If this vector's x or y value is less than the given vector's x or y
  978. * value, replace that value with the corresponding max value.
  979. *
  980. * @param {Vector2} v - The vector.
  981. * @return {Vector2} A reference to this vector.
  982. */
  983. max( v ) {
  984. this.x = Math.max( this.x, v.x );
  985. this.y = Math.max( this.y, v.y );
  986. return this;
  987. }
  988. /**
  989. * If this vector's x or y value is greater than the max vector's x or y
  990. * value, it is replaced by the corresponding value.
  991. * If this vector's x or y value is less than the min vector's x or y value,
  992. * it is replaced by the corresponding value.
  993. *
  994. * @param {Vector2} min - The minimum x and y values.
  995. * @param {Vector2} max - The maximum x and y values in the desired range.
  996. * @return {Vector2} A reference to this vector.
  997. */
  998. clamp( min, max ) {
  999. // assumes min < max, componentwise
  1000. this.x = clamp( this.x, min.x, max.x );
  1001. this.y = clamp( this.y, min.y, max.y );
  1002. return this;
  1003. }
  1004. /**
  1005. * If this vector's x or y values are greater than the max value, they are
  1006. * replaced by the max value.
  1007. * If this vector's x or y values are less than the min value, they are
  1008. * replaced by the min value.
  1009. *
  1010. * @param {number} minVal - The minimum value the components will be clamped to.
  1011. * @param {number} maxVal - The maximum value the components will be clamped to.
  1012. * @return {Vector2} A reference to this vector.
  1013. */
  1014. clampScalar( minVal, maxVal ) {
  1015. this.x = clamp( this.x, minVal, maxVal );
  1016. this.y = clamp( this.y, minVal, maxVal );
  1017. return this;
  1018. }
  1019. /**
  1020. * If this vector's length is greater than the max value, it is replaced by
  1021. * the max value.
  1022. * If this vector's length is less than the min value, it is replaced by the
  1023. * min value.
  1024. *
  1025. * @param {number} min - The minimum value the vector length will be clamped to.
  1026. * @param {number} max - The maximum value the vector length will be clamped to.
  1027. * @return {Vector2} A reference to this vector.
  1028. */
  1029. clampLength( min, max ) {
  1030. const length = this.length();
  1031. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  1032. }
  1033. /**
  1034. * The components of this vector are rounded down to the nearest integer value.
  1035. *
  1036. * @return {Vector2} A reference to this vector.
  1037. */
  1038. floor() {
  1039. this.x = Math.floor( this.x );
  1040. this.y = Math.floor( this.y );
  1041. return this;
  1042. }
  1043. /**
  1044. * The components of this vector are rounded up to the nearest integer value.
  1045. *
  1046. * @return {Vector2} A reference to this vector.
  1047. */
  1048. ceil() {
  1049. this.x = Math.ceil( this.x );
  1050. this.y = Math.ceil( this.y );
  1051. return this;
  1052. }
  1053. /**
  1054. * The components of this vector are rounded to the nearest integer value
  1055. *
  1056. * @return {Vector2} A reference to this vector.
  1057. */
  1058. round() {
  1059. this.x = Math.round( this.x );
  1060. this.y = Math.round( this.y );
  1061. return this;
  1062. }
  1063. /**
  1064. * The components of this vector are rounded towards zero (up if negative,
  1065. * down if positive) to an integer value.
  1066. *
  1067. * @return {Vector2} A reference to this vector.
  1068. */
  1069. roundToZero() {
  1070. this.x = Math.trunc( this.x );
  1071. this.y = Math.trunc( this.y );
  1072. return this;
  1073. }
  1074. /**
  1075. * Inverts this vector - i.e. sets x = -x and y = -y.
  1076. *
  1077. * @return {Vector2} A reference to this vector.
  1078. */
  1079. negate() {
  1080. this.x = - this.x;
  1081. this.y = - this.y;
  1082. return this;
  1083. }
  1084. /**
  1085. * Calculates the dot product of the given vector with this instance.
  1086. *
  1087. * @param {Vector2} v - The vector to compute the dot product with.
  1088. * @return {number} The result of the dot product.
  1089. */
  1090. dot( v ) {
  1091. return this.x * v.x + this.y * v.y;
  1092. }
  1093. /**
  1094. * Calculates the cross product of the given vector with this instance.
  1095. *
  1096. * @param {Vector2} v - The vector to compute the cross product with.
  1097. * @return {Vector2} The result of the cross product.
  1098. */
  1099. cross( v ) {
  1100. return this.x * v.y - this.y * v.x;
  1101. }
  1102. /**
  1103. * Computes the square of the Euclidean length (straight-line length) from
  1104. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  1105. * compare the length squared instead as it is slightly more efficient to calculate.
  1106. *
  1107. * @return {number} The square length of this vector.
  1108. */
  1109. lengthSq() {
  1110. return this.x * this.x + this.y * this.y;
  1111. }
  1112. /**
  1113. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  1114. *
  1115. * @return {number} The length of this vector.
  1116. */
  1117. length() {
  1118. return Math.sqrt( this.x * this.x + this.y * this.y );
  1119. }
  1120. /**
  1121. * Computes the Manhattan length of this vector.
  1122. *
  1123. * @return {number} The length of this vector.
  1124. */
  1125. manhattanLength() {
  1126. return Math.abs( this.x ) + Math.abs( this.y );
  1127. }
  1128. /**
  1129. * Converts this vector to a unit vector - that is, sets it equal to a vector
  1130. * with the same direction as this one, but with a vector length of `1`.
  1131. *
  1132. * @return {Vector2} A reference to this vector.
  1133. */
  1134. normalize() {
  1135. return this.divideScalar( this.length() || 1 );
  1136. }
  1137. /**
  1138. * Computes the angle in radians of this vector with respect to the positive x-axis.
  1139. *
  1140. * @return {number} The angle in radians.
  1141. */
  1142. angle() {
  1143. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1144. return angle;
  1145. }
  1146. /**
  1147. * Returns the angle between the given vector and this instance in radians.
  1148. *
  1149. * @param {Vector2} v - The vector to compute the angle with.
  1150. * @return {number} The angle in radians.
  1151. */
  1152. angleTo( v ) {
  1153. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1154. if ( denominator === 0 ) return Math.PI / 2;
  1155. const theta = this.dot( v ) / denominator;
  1156. // clamp, to handle numerical problems
  1157. return Math.acos( clamp( theta, -1, 1 ) );
  1158. }
  1159. /**
  1160. * Computes the distance from the given vector to this instance.
  1161. *
  1162. * @param {Vector2} v - The vector to compute the distance to.
  1163. * @return {number} The distance.
  1164. */
  1165. distanceTo( v ) {
  1166. return Math.sqrt( this.distanceToSquared( v ) );
  1167. }
  1168. /**
  1169. * Computes the squared distance from the given vector to this instance.
  1170. * If you are just comparing the distance with another distance, you should compare
  1171. * the distance squared instead as it is slightly more efficient to calculate.
  1172. *
  1173. * @param {Vector2} v - The vector to compute the squared distance to.
  1174. * @return {number} The squared distance.
  1175. */
  1176. distanceToSquared( v ) {
  1177. const dx = this.x - v.x, dy = this.y - v.y;
  1178. return dx * dx + dy * dy;
  1179. }
  1180. /**
  1181. * Computes the Manhattan distance from the given vector to this instance.
  1182. *
  1183. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  1184. * @return {number} The Manhattan distance.
  1185. */
  1186. manhattanDistanceTo( v ) {
  1187. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1188. }
  1189. /**
  1190. * Sets this vector to a vector with the same direction as this one, but
  1191. * with the specified length.
  1192. *
  1193. * @param {number} length - The new length of this vector.
  1194. * @return {Vector2} A reference to this vector.
  1195. */
  1196. setLength( length ) {
  1197. return this.normalize().multiplyScalar( length );
  1198. }
  1199. /**
  1200. * Linearly interpolates between the given vector and this instance, where
  1201. * alpha is the percent distance along the line - alpha = 0 will be this
  1202. * vector, and alpha = 1 will be the given one.
  1203. *
  1204. * @param {Vector2} v - The vector to interpolate towards.
  1205. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1206. * @return {Vector2} A reference to this vector.
  1207. */
  1208. lerp( v, alpha ) {
  1209. this.x += ( v.x - this.x ) * alpha;
  1210. this.y += ( v.y - this.y ) * alpha;
  1211. return this;
  1212. }
  1213. /**
  1214. * Linearly interpolates between the given vectors, where alpha is the percent
  1215. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  1216. * be the second one. The result is stored in this instance.
  1217. *
  1218. * @param {Vector2} v1 - The first vector.
  1219. * @param {Vector2} v2 - The second vector.
  1220. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1221. * @return {Vector2} A reference to this vector.
  1222. */
  1223. lerpVectors( v1, v2, alpha ) {
  1224. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1225. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1226. return this;
  1227. }
  1228. /**
  1229. * Returns `true` if this vector is equal with the given one.
  1230. *
  1231. * @param {Vector2} v - The vector to test for equality.
  1232. * @return {boolean} Whether this vector is equal with the given one.
  1233. */
  1234. equals( v ) {
  1235. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1236. }
  1237. /**
  1238. * Sets this vector's x value to be `array[ offset ]` and y
  1239. * value to be `array[ offset + 1 ]`.
  1240. *
  1241. * @param {Array<number>} array - An array holding the vector component values.
  1242. * @param {number} [offset=0] - The offset into the array.
  1243. * @return {Vector2} A reference to this vector.
  1244. */
  1245. fromArray( array, offset = 0 ) {
  1246. this.x = array[ offset ];
  1247. this.y = array[ offset + 1 ];
  1248. return this;
  1249. }
  1250. /**
  1251. * Writes the components of this vector to the given array. If no array is provided,
  1252. * the method returns a new instance.
  1253. *
  1254. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  1255. * @param {number} [offset=0] - Index of the first element in the array.
  1256. * @return {Array<number>} The vector components.
  1257. */
  1258. toArray( array = [], offset = 0 ) {
  1259. array[ offset ] = this.x;
  1260. array[ offset + 1 ] = this.y;
  1261. return array;
  1262. }
  1263. /**
  1264. * Sets the components of this vector from the given buffer attribute.
  1265. *
  1266. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  1267. * @param {number} index - The index into the attribute.
  1268. * @return {Vector2} A reference to this vector.
  1269. */
  1270. fromBufferAttribute( attribute, index ) {
  1271. this.x = attribute.getX( index );
  1272. this.y = attribute.getY( index );
  1273. return this;
  1274. }
  1275. /**
  1276. * Rotates this vector around the given center by the given angle.
  1277. *
  1278. * @param {Vector2} center - The point around which to rotate.
  1279. * @param {number} angle - The angle to rotate, in radians.
  1280. * @return {Vector2} A reference to this vector.
  1281. */
  1282. rotateAround( center, angle ) {
  1283. const c = Math.cos( angle ), s = Math.sin( angle );
  1284. const x = this.x - center.x;
  1285. const y = this.y - center.y;
  1286. this.x = x * c - y * s + center.x;
  1287. this.y = x * s + y * c + center.y;
  1288. return this;
  1289. }
  1290. /**
  1291. * Sets each component of this vector to a pseudo-random value between `0` and
  1292. * `1`, excluding `1`.
  1293. *
  1294. * @return {Vector2} A reference to this vector.
  1295. */
  1296. random() {
  1297. this.x = Math.random();
  1298. this.y = Math.random();
  1299. return this;
  1300. }
  1301. *[ Symbol.iterator ]() {
  1302. yield this.x;
  1303. yield this.y;
  1304. }
  1305. }
  1306. /**
  1307. * Represents a 3x3 matrix.
  1308. *
  1309. * A Note on Row-Major and Column-Major Ordering:
  1310. *
  1311. * The constructor and {@link Matrix3#set} method take arguments in
  1312. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  1313. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  1314. * This means that calling:
  1315. * ```js
  1316. * const m = new THREE.Matrix();
  1317. * m.set( 11, 12, 13,
  1318. * 21, 22, 23,
  1319. * 31, 32, 33 );
  1320. * ```
  1321. * will result in the elements array containing:
  1322. * ```js
  1323. * m.elements = [ 11, 21, 31,
  1324. * 12, 22, 32,
  1325. * 13, 23, 33 ];
  1326. * ```
  1327. * and internally all calculations are performed using column-major ordering.
  1328. * However, as the actual ordering makes no difference mathematically and
  1329. * most people are used to thinking about matrices in row-major order, the
  1330. * three.js documentation shows matrices in row-major order. Just bear in
  1331. * mind that if you are reading the source code, you'll have to take the
  1332. * transpose of any matrices outlined here to make sense of the calculations.
  1333. */
  1334. class Matrix3 {
  1335. /**
  1336. * Constructs a new 3x3 matrix. The arguments are supposed to be
  1337. * in row-major order. If no arguments are provided, the constructor
  1338. * initializes the matrix as an identity matrix.
  1339. *
  1340. * @param {number} [n11] - 1-1 matrix element.
  1341. * @param {number} [n12] - 1-2 matrix element.
  1342. * @param {number} [n13] - 1-3 matrix element.
  1343. * @param {number} [n21] - 2-1 matrix element.
  1344. * @param {number} [n22] - 2-2 matrix element.
  1345. * @param {number} [n23] - 2-3 matrix element.
  1346. * @param {number} [n31] - 3-1 matrix element.
  1347. * @param {number} [n32] - 3-2 matrix element.
  1348. * @param {number} [n33] - 3-3 matrix element.
  1349. */
  1350. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1351. /**
  1352. * This flag can be used for type testing.
  1353. *
  1354. * @type {boolean}
  1355. * @readonly
  1356. * @default true
  1357. */
  1358. Matrix3.prototype.isMatrix3 = true;
  1359. /**
  1360. * A column-major list of matrix values.
  1361. *
  1362. * @type {Array<number>}
  1363. */
  1364. this.elements = [
  1365. 1, 0, 0,
  1366. 0, 1, 0,
  1367. 0, 0, 1
  1368. ];
  1369. if ( n11 !== undefined ) {
  1370. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  1371. }
  1372. }
  1373. /**
  1374. * Sets the elements of the matrix.The arguments are supposed to be
  1375. * in row-major order.
  1376. *
  1377. * @param {number} [n11] - 1-1 matrix element.
  1378. * @param {number} [n12] - 1-2 matrix element.
  1379. * @param {number} [n13] - 1-3 matrix element.
  1380. * @param {number} [n21] - 2-1 matrix element.
  1381. * @param {number} [n22] - 2-2 matrix element.
  1382. * @param {number} [n23] - 2-3 matrix element.
  1383. * @param {number} [n31] - 3-1 matrix element.
  1384. * @param {number} [n32] - 3-2 matrix element.
  1385. * @param {number} [n33] - 3-3 matrix element.
  1386. * @return {Matrix3} A reference to this matrix.
  1387. */
  1388. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1389. const te = this.elements;
  1390. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1391. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1392. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1393. return this;
  1394. }
  1395. /**
  1396. * Sets this matrix to the 3x3 identity matrix.
  1397. *
  1398. * @return {Matrix3} A reference to this matrix.
  1399. */
  1400. identity() {
  1401. this.set(
  1402. 1, 0, 0,
  1403. 0, 1, 0,
  1404. 0, 0, 1
  1405. );
  1406. return this;
  1407. }
  1408. /**
  1409. * Copies the values of the given matrix to this instance.
  1410. *
  1411. * @param {Matrix3} m - The matrix to copy.
  1412. * @return {Matrix3} A reference to this matrix.
  1413. */
  1414. copy( m ) {
  1415. const te = this.elements;
  1416. const me = m.elements;
  1417. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1418. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1419. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1420. return this;
  1421. }
  1422. /**
  1423. * Extracts the basis of this matrix into the three axis vectors provided.
  1424. *
  1425. * @param {Vector3} xAxis - The basis's x axis.
  1426. * @param {Vector3} yAxis - The basis's y axis.
  1427. * @param {Vector3} zAxis - The basis's z axis.
  1428. * @return {Matrix3} A reference to this matrix.
  1429. */
  1430. extractBasis( xAxis, yAxis, zAxis ) {
  1431. xAxis.setFromMatrix3Column( this, 0 );
  1432. yAxis.setFromMatrix3Column( this, 1 );
  1433. zAxis.setFromMatrix3Column( this, 2 );
  1434. return this;
  1435. }
  1436. /**
  1437. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  1438. *
  1439. * @param {Matrix4} m - The 4x4 matrix.
  1440. * @return {Matrix3} A reference to this matrix.
  1441. */
  1442. setFromMatrix4( m ) {
  1443. const me = m.elements;
  1444. this.set(
  1445. me[ 0 ], me[ 4 ], me[ 8 ],
  1446. me[ 1 ], me[ 5 ], me[ 9 ],
  1447. me[ 2 ], me[ 6 ], me[ 10 ]
  1448. );
  1449. return this;
  1450. }
  1451. /**
  1452. * Post-multiplies this matrix by the given 3x3 matrix.
  1453. *
  1454. * @param {Matrix3} m - The matrix to multiply with.
  1455. * @return {Matrix3} A reference to this matrix.
  1456. */
  1457. multiply( m ) {
  1458. return this.multiplyMatrices( this, m );
  1459. }
  1460. /**
  1461. * Pre-multiplies this matrix by the given 3x3 matrix.
  1462. *
  1463. * @param {Matrix3} m - The matrix to multiply with.
  1464. * @return {Matrix3} A reference to this matrix.
  1465. */
  1466. premultiply( m ) {
  1467. return this.multiplyMatrices( m, this );
  1468. }
  1469. /**
  1470. * Multiples the given 3x3 matrices and stores the result
  1471. * in this matrix.
  1472. *
  1473. * @param {Matrix3} a - The first matrix.
  1474. * @param {Matrix3} b - The second matrix.
  1475. * @return {Matrix3} A reference to this matrix.
  1476. */
  1477. multiplyMatrices( a, b ) {
  1478. const ae = a.elements;
  1479. const be = b.elements;
  1480. const te = this.elements;
  1481. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1482. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1483. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1484. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1485. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1486. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1487. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1488. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1489. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1490. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1491. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1492. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1493. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1494. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1495. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1496. return this;
  1497. }
  1498. /**
  1499. * Multiplies every component of the matrix by the given scalar.
  1500. *
  1501. * @param {number} s - The scalar.
  1502. * @return {Matrix3} A reference to this matrix.
  1503. */
  1504. multiplyScalar( s ) {
  1505. const te = this.elements;
  1506. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1507. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1508. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1509. return this;
  1510. }
  1511. /**
  1512. * Computes and returns the determinant of this matrix.
  1513. *
  1514. * @return {number} The determinant.
  1515. */
  1516. determinant() {
  1517. const te = this.elements;
  1518. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1519. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1520. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1521. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1522. }
  1523. /**
  1524. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  1525. * You can not invert with a determinant of zero. If you attempt this, the method produces
  1526. * a zero matrix instead.
  1527. *
  1528. * @return {Matrix3} A reference to this matrix.
  1529. */
  1530. invert() {
  1531. const te = this.elements,
  1532. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1533. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1534. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1535. t11 = n33 * n22 - n32 * n23,
  1536. t12 = n32 * n13 - n33 * n12,
  1537. t13 = n23 * n12 - n22 * n13,
  1538. det = n11 * t11 + n21 * t12 + n31 * t13;
  1539. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1540. const detInv = 1 / det;
  1541. te[ 0 ] = t11 * detInv;
  1542. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1543. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1544. te[ 3 ] = t12 * detInv;
  1545. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1546. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1547. te[ 6 ] = t13 * detInv;
  1548. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1549. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1550. return this;
  1551. }
  1552. /**
  1553. * Transposes this matrix in place.
  1554. *
  1555. * @return {Matrix3} A reference to this matrix.
  1556. */
  1557. transpose() {
  1558. let tmp;
  1559. const m = this.elements;
  1560. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1561. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1562. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1563. return this;
  1564. }
  1565. /**
  1566. * Computes the normal matrix which is the inverse transpose of the upper
  1567. * left 3x3 portion of the given 4x4 matrix.
  1568. *
  1569. * @param {Matrix4} matrix4 - The 4x4 matrix.
  1570. * @return {Matrix3} A reference to this matrix.
  1571. */
  1572. getNormalMatrix( matrix4 ) {
  1573. return this.setFromMatrix4( matrix4 ).invert().transpose();
  1574. }
  1575. /**
  1576. * Transposes this matrix into the supplied array, and returns itself unchanged.
  1577. *
  1578. * @param {Array<number>} r - An arry to store the transposed matrix elements.
  1579. * @return {Matrix3} A reference to this matrix.
  1580. */
  1581. transposeIntoArray( r ) {
  1582. const m = this.elements;
  1583. r[ 0 ] = m[ 0 ];
  1584. r[ 1 ] = m[ 3 ];
  1585. r[ 2 ] = m[ 6 ];
  1586. r[ 3 ] = m[ 1 ];
  1587. r[ 4 ] = m[ 4 ];
  1588. r[ 5 ] = m[ 7 ];
  1589. r[ 6 ] = m[ 2 ];
  1590. r[ 7 ] = m[ 5 ];
  1591. r[ 8 ] = m[ 8 ];
  1592. return this;
  1593. }
  1594. /**
  1595. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  1596. *
  1597. * @param {number} tx - Offset x.
  1598. * @param {number} ty - Offset y.
  1599. * @param {number} sx - Repeat x.
  1600. * @param {number} sy - Repeat y.
  1601. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  1602. * @param {number} cx - Center x of rotation.
  1603. * @param {number} cy - Center y of rotation
  1604. * @return {Matrix3} A reference to this matrix.
  1605. */
  1606. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1607. const c = Math.cos( rotation );
  1608. const s = Math.sin( rotation );
  1609. this.set(
  1610. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1611. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1612. 0, 0, 1
  1613. );
  1614. return this;
  1615. }
  1616. /**
  1617. * Scales this matrix with the given scalar values.
  1618. *
  1619. * @param {number} sx - The amount to scale in the X axis.
  1620. * @param {number} sy - The amount to scale in the Y axis.
  1621. * @return {Matrix3} A reference to this matrix.
  1622. */
  1623. scale( sx, sy ) {
  1624. this.premultiply( _m3.makeScale( sx, sy ) );
  1625. return this;
  1626. }
  1627. /**
  1628. * Rotates this matrix by the given angle.
  1629. *
  1630. * @param {number} theta - The rotation in radians.
  1631. * @return {Matrix3} A reference to this matrix.
  1632. */
  1633. rotate( theta ) {
  1634. this.premultiply( _m3.makeRotation( - theta ) );
  1635. return this;
  1636. }
  1637. /**
  1638. * Translates this matrix by the given scalar values.
  1639. *
  1640. * @param {number} tx - The amount to translate in the X axis.
  1641. * @param {number} ty - The amount to translate in the Y axis.
  1642. * @return {Matrix3} A reference to this matrix.
  1643. */
  1644. translate( tx, ty ) {
  1645. this.premultiply( _m3.makeTranslation( tx, ty ) );
  1646. return this;
  1647. }
  1648. // for 2D Transforms
  1649. /**
  1650. * Sets this matrix as a 2D translation transform.
  1651. *
  1652. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  1653. * @param {number} y - The amount to translate in the Y axis.
  1654. * @return {Matrix3} A reference to this matrix.
  1655. */
  1656. makeTranslation( x, y ) {
  1657. if ( x.isVector2 ) {
  1658. this.set(
  1659. 1, 0, x.x,
  1660. 0, 1, x.y,
  1661. 0, 0, 1
  1662. );
  1663. } else {
  1664. this.set(
  1665. 1, 0, x,
  1666. 0, 1, y,
  1667. 0, 0, 1
  1668. );
  1669. }
  1670. return this;
  1671. }
  1672. /**
  1673. * Sets this matrix as a 2D rotational transformation.
  1674. *
  1675. * @param {number} theta - The rotation in radians.
  1676. * @return {Matrix3} A reference to this matrix.
  1677. */
  1678. makeRotation( theta ) {
  1679. // counterclockwise
  1680. const c = Math.cos( theta );
  1681. const s = Math.sin( theta );
  1682. this.set(
  1683. c, - s, 0,
  1684. s, c, 0,
  1685. 0, 0, 1
  1686. );
  1687. return this;
  1688. }
  1689. /**
  1690. * Sets this matrix as a 2D scale transform.
  1691. *
  1692. * @param {number} x - The amount to scale in the X axis.
  1693. * @param {number} y - The amount to scale in the Y axis.
  1694. * @return {Matrix3} A reference to this matrix.
  1695. */
  1696. makeScale( x, y ) {
  1697. this.set(
  1698. x, 0, 0,
  1699. 0, y, 0,
  1700. 0, 0, 1
  1701. );
  1702. return this;
  1703. }
  1704. /**
  1705. * Returns `true` if this matrix is equal with the given one.
  1706. *
  1707. * @param {Matrix3} matrix - The matrix to test for equality.
  1708. * @return {boolean} Whether this matrix is equal with the given one.
  1709. */
  1710. equals( matrix ) {
  1711. const te = this.elements;
  1712. const me = matrix.elements;
  1713. for ( let i = 0; i < 9; i ++ ) {
  1714. if ( te[ i ] !== me[ i ] ) return false;
  1715. }
  1716. return true;
  1717. }
  1718. /**
  1719. * Sets the elements of the matrix from the given array.
  1720. *
  1721. * @param {Array<number>} array - The matrix elements in column-major order.
  1722. * @param {number} [offset=0] - Index of the first element in the array.
  1723. * @return {Matrix3} A reference to this matrix.
  1724. */
  1725. fromArray( array, offset = 0 ) {
  1726. for ( let i = 0; i < 9; i ++ ) {
  1727. this.elements[ i ] = array[ i + offset ];
  1728. }
  1729. return this;
  1730. }
  1731. /**
  1732. * Writes the elements of this matrix to the given array. If no array is provided,
  1733. * the method returns a new instance.
  1734. *
  1735. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  1736. * @param {number} [offset=0] - Index of the first element in the array.
  1737. * @return {Array<number>} The matrix elements in column-major order.
  1738. */
  1739. toArray( array = [], offset = 0 ) {
  1740. const te = this.elements;
  1741. array[ offset ] = te[ 0 ];
  1742. array[ offset + 1 ] = te[ 1 ];
  1743. array[ offset + 2 ] = te[ 2 ];
  1744. array[ offset + 3 ] = te[ 3 ];
  1745. array[ offset + 4 ] = te[ 4 ];
  1746. array[ offset + 5 ] = te[ 5 ];
  1747. array[ offset + 6 ] = te[ 6 ];
  1748. array[ offset + 7 ] = te[ 7 ];
  1749. array[ offset + 8 ] = te[ 8 ];
  1750. return array;
  1751. }
  1752. /**
  1753. * Returns a matrix with copied values from this instance.
  1754. *
  1755. * @return {Matrix3} A clone of this instance.
  1756. */
  1757. clone() {
  1758. return new this.constructor().fromArray( this.elements );
  1759. }
  1760. }
  1761. const _m3 = /*@__PURE__*/ new Matrix3();
  1762. function arrayNeedsUint32( array ) {
  1763. // assumes larger values usually on last
  1764. for ( let i = array.length - 1; i >= 0; -- i ) {
  1765. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1766. }
  1767. return false;
  1768. }
  1769. const TYPED_ARRAYS = {
  1770. Int8Array: Int8Array,
  1771. Uint8Array: Uint8Array,
  1772. Uint8ClampedArray: Uint8ClampedArray,
  1773. Int16Array: Int16Array,
  1774. Uint16Array: Uint16Array,
  1775. Int32Array: Int32Array,
  1776. Uint32Array: Uint32Array,
  1777. Float32Array: Float32Array,
  1778. Float64Array: Float64Array
  1779. };
  1780. function getTypedArray( type, buffer ) {
  1781. return new TYPED_ARRAYS[ type ]( buffer );
  1782. }
  1783. function createElementNS( name ) {
  1784. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1785. }
  1786. function createCanvasElement() {
  1787. const canvas = createElementNS( 'canvas' );
  1788. canvas.style.display = 'block';
  1789. return canvas;
  1790. }
  1791. const _cache = {};
  1792. function warnOnce( message ) {
  1793. if ( message in _cache ) return;
  1794. _cache[ message ] = true;
  1795. console.warn( message );
  1796. }
  1797. function probeAsync( gl, sync, interval ) {
  1798. return new Promise( function ( resolve, reject ) {
  1799. function probe() {
  1800. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1801. case gl.WAIT_FAILED:
  1802. reject();
  1803. break;
  1804. case gl.TIMEOUT_EXPIRED:
  1805. setTimeout( probe, interval );
  1806. break;
  1807. default:
  1808. resolve();
  1809. }
  1810. }
  1811. setTimeout( probe, interval );
  1812. } );
  1813. }
  1814. function toNormalizedProjectionMatrix( projectionMatrix ) {
  1815. const m = projectionMatrix.elements;
  1816. // Convert [-1, 1] to [0, 1] projection matrix
  1817. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  1818. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  1819. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  1820. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1821. }
  1822. function toReversedProjectionMatrix( projectionMatrix ) {
  1823. const m = projectionMatrix.elements;
  1824. const isPerspectiveMatrix = m[ 11 ] === -1;
  1825. // Reverse [0, 1] projection matrix
  1826. if ( isPerspectiveMatrix ) {
  1827. m[ 10 ] = - m[ 10 ] - 1;
  1828. m[ 14 ] = - m[ 14 ];
  1829. } else {
  1830. m[ 10 ] = - m[ 10 ];
  1831. m[ 14 ] = - m[ 14 ] + 1;
  1832. }
  1833. }
  1834. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1835. 0.4123908, 0.3575843, 0.1804808,
  1836. 0.2126390, 0.7151687, 0.0721923,
  1837. 0.0193308, 0.1191948, 0.9505322
  1838. );
  1839. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1840. 3.2409699, -1.5373832, -0.4986108,
  1841. -0.9692436, 1.8759675, 0.0415551,
  1842. 0.0556301, -0.203977, 1.0569715
  1843. );
  1844. function createColorManagement() {
  1845. const ColorManagement = {
  1846. enabled: true,
  1847. workingColorSpace: LinearSRGBColorSpace,
  1848. /**
  1849. * Implementations of supported color spaces.
  1850. *
  1851. * Required:
  1852. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1853. * - whitePoint: reference white [ x y ]
  1854. * - transfer: transfer function (pre-defined)
  1855. * - toXYZ: Matrix3 RGB to XYZ transform
  1856. * - fromXYZ: Matrix3 XYZ to RGB transform
  1857. * - luminanceCoefficients: RGB luminance coefficients
  1858. *
  1859. * Optional:
  1860. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1861. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1862. *
  1863. * Reference:
  1864. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1865. */
  1866. spaces: {},
  1867. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1868. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1869. return color;
  1870. }
  1871. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1872. color.r = SRGBToLinear( color.r );
  1873. color.g = SRGBToLinear( color.g );
  1874. color.b = SRGBToLinear( color.b );
  1875. }
  1876. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1877. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1878. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1879. }
  1880. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1881. color.r = LinearToSRGB( color.r );
  1882. color.g = LinearToSRGB( color.g );
  1883. color.b = LinearToSRGB( color.b );
  1884. }
  1885. return color;
  1886. },
  1887. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1888. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1889. },
  1890. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1891. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1892. },
  1893. getPrimaries: function ( colorSpace ) {
  1894. return this.spaces[ colorSpace ].primaries;
  1895. },
  1896. getTransfer: function ( colorSpace ) {
  1897. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1898. return this.spaces[ colorSpace ].transfer;
  1899. },
  1900. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1901. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1902. },
  1903. define: function ( colorSpaces ) {
  1904. Object.assign( this.spaces, colorSpaces );
  1905. },
  1906. // Internal APIs
  1907. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1908. return targetMatrix
  1909. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1910. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1911. },
  1912. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1913. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1914. },
  1915. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1916. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1917. }
  1918. };
  1919. /******************************************************************************
  1920. * sRGB definitions
  1921. */
  1922. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1923. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1924. const D65 = [ 0.3127, 0.3290 ];
  1925. ColorManagement.define( {
  1926. [ LinearSRGBColorSpace ]: {
  1927. primaries: REC709_PRIMARIES,
  1928. whitePoint: D65,
  1929. transfer: LinearTransfer,
  1930. toXYZ: LINEAR_REC709_TO_XYZ,
  1931. fromXYZ: XYZ_TO_LINEAR_REC709,
  1932. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1933. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1934. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1935. },
  1936. [ SRGBColorSpace ]: {
  1937. primaries: REC709_PRIMARIES,
  1938. whitePoint: D65,
  1939. transfer: SRGBTransfer,
  1940. toXYZ: LINEAR_REC709_TO_XYZ,
  1941. fromXYZ: XYZ_TO_LINEAR_REC709,
  1942. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1943. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1944. },
  1945. } );
  1946. return ColorManagement;
  1947. }
  1948. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1949. function SRGBToLinear( c ) {
  1950. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1951. }
  1952. function LinearToSRGB( c ) {
  1953. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1954. }
  1955. let _canvas;
  1956. /**
  1957. * A class containing utility functions for images.
  1958. *
  1959. * @hideconstructor
  1960. */
  1961. class ImageUtils {
  1962. /**
  1963. * Returns a data URI containing a representation of the given image.
  1964. *
  1965. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  1966. * @return {string} The data URI.
  1967. */
  1968. static getDataURL( image ) {
  1969. if ( /^data:/i.test( image.src ) ) {
  1970. return image.src;
  1971. }
  1972. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1973. return image.src;
  1974. }
  1975. let canvas;
  1976. if ( image instanceof HTMLCanvasElement ) {
  1977. canvas = image;
  1978. } else {
  1979. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1980. _canvas.width = image.width;
  1981. _canvas.height = image.height;
  1982. const context = _canvas.getContext( '2d' );
  1983. if ( image instanceof ImageData ) {
  1984. context.putImageData( image, 0, 0 );
  1985. } else {
  1986. context.drawImage( image, 0, 0, image.width, image.height );
  1987. }
  1988. canvas = _canvas;
  1989. }
  1990. return canvas.toDataURL( 'image/png' );
  1991. }
  1992. /**
  1993. * Converts the given sRGB image data to linear color space.
  1994. *
  1995. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  1996. * @return {HTMLCanvasElement|Object} The converted image.
  1997. */
  1998. static sRGBToLinear( image ) {
  1999. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2000. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2001. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2002. const canvas = createElementNS( 'canvas' );
  2003. canvas.width = image.width;
  2004. canvas.height = image.height;
  2005. const context = canvas.getContext( '2d' );
  2006. context.drawImage( image, 0, 0, image.width, image.height );
  2007. const imageData = context.getImageData( 0, 0, image.width, image.height );
  2008. const data = imageData.data;
  2009. for ( let i = 0; i < data.length; i ++ ) {
  2010. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  2011. }
  2012. context.putImageData( imageData, 0, 0 );
  2013. return canvas;
  2014. } else if ( image.data ) {
  2015. const data = image.data.slice( 0 );
  2016. for ( let i = 0; i < data.length; i ++ ) {
  2017. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  2018. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  2019. } else {
  2020. // assuming float
  2021. data[ i ] = SRGBToLinear( data[ i ] );
  2022. }
  2023. }
  2024. return {
  2025. data: data,
  2026. width: image.width,
  2027. height: image.height
  2028. };
  2029. } else {
  2030. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  2031. return image;
  2032. }
  2033. }
  2034. }
  2035. let _sourceId = 0;
  2036. class Source {
  2037. constructor( data = null ) {
  2038. this.isSource = true;
  2039. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  2040. this.uuid = generateUUID();
  2041. this.data = data;
  2042. this.dataReady = true;
  2043. this.version = 0;
  2044. }
  2045. set needsUpdate( value ) {
  2046. if ( value === true ) this.version ++;
  2047. }
  2048. toJSON( meta ) {
  2049. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2050. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  2051. return meta.images[ this.uuid ];
  2052. }
  2053. const output = {
  2054. uuid: this.uuid,
  2055. url: ''
  2056. };
  2057. const data = this.data;
  2058. if ( data !== null ) {
  2059. let url;
  2060. if ( Array.isArray( data ) ) {
  2061. // cube texture
  2062. url = [];
  2063. for ( let i = 0, l = data.length; i < l; i ++ ) {
  2064. if ( data[ i ].isDataTexture ) {
  2065. url.push( serializeImage( data[ i ].image ) );
  2066. } else {
  2067. url.push( serializeImage( data[ i ] ) );
  2068. }
  2069. }
  2070. } else {
  2071. // texture
  2072. url = serializeImage( data );
  2073. }
  2074. output.url = url;
  2075. }
  2076. if ( ! isRootObject ) {
  2077. meta.images[ this.uuid ] = output;
  2078. }
  2079. return output;
  2080. }
  2081. }
  2082. function serializeImage( image ) {
  2083. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2084. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2085. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2086. // default images
  2087. return ImageUtils.getDataURL( image );
  2088. } else {
  2089. if ( image.data ) {
  2090. // images of DataTexture
  2091. return {
  2092. data: Array.from( image.data ),
  2093. width: image.width,
  2094. height: image.height,
  2095. type: image.data.constructor.name
  2096. };
  2097. } else {
  2098. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  2099. return {};
  2100. }
  2101. }
  2102. }
  2103. let _textureId = 0;
  2104. /**
  2105. * Base class for all textures.
  2106. *
  2107. * Note: After the initial use of a texture, its dimensions, format, and type
  2108. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  2109. *
  2110. * @augments EventDispatcher
  2111. */
  2112. class Texture extends EventDispatcher {
  2113. /**
  2114. * Constructs a new texture.
  2115. *
  2116. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  2117. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  2118. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  2119. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  2120. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  2121. * @param {number} [minFilter=LinearFilter] - The min filter value.
  2122. * @param {number} [format=RGABFormat] - The min filter value.
  2123. * @param {number} [type=UnsignedByteType] - The min filter value.
  2124. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The min filter value.
  2125. * @param {string} [colorSpace=NoColorSpace] - The min filter value.
  2126. */
  2127. 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 ) {
  2128. super();
  2129. /**
  2130. * This flag can be used for type testing.
  2131. *
  2132. * @type {boolean}
  2133. * @readonly
  2134. * @default true
  2135. */
  2136. this.isTexture = true;
  2137. /**
  2138. * The ID of the texture.
  2139. *
  2140. * @name Texture#id
  2141. * @type {number}
  2142. * @readonly
  2143. */
  2144. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  2145. /**
  2146. * The UUID of the material.
  2147. *
  2148. * @type {string}
  2149. * @readonly
  2150. */
  2151. this.uuid = generateUUID();
  2152. /**
  2153. * The name of the material.
  2154. *
  2155. * @type {string}
  2156. */
  2157. this.name = '';
  2158. /**
  2159. * The data definition of a texture. A reference to the data source can be
  2160. * shared across textures. This is often useful in context of spritesheets
  2161. * where multiple textures render the same data but with different texture
  2162. * transformations.
  2163. *
  2164. * @type {Source}
  2165. */
  2166. this.source = new Source( image );
  2167. /**
  2168. * An array holding user-defined mipmaps.
  2169. *
  2170. * @type {Array<Object>}
  2171. */
  2172. this.mipmaps = [];
  2173. /**
  2174. * How the texture is applied to the object. The value `UVMapping`
  2175. * is the default, where texture or uv coordinates are used to apply the map.
  2176. *
  2177. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  2178. * @default UVMapping
  2179. */
  2180. this.mapping = mapping;
  2181. /**
  2182. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  2183. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  2184. *
  2185. * @type {number}
  2186. * @default 0
  2187. */
  2188. this.channel = 0;
  2189. /**
  2190. * This defines how the texture is wrapped horizontally and corresponds to
  2191. * *U* in UV mapping.
  2192. *
  2193. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2194. * @default ClampToEdgeWrapping
  2195. */
  2196. this.wrapS = wrapS;
  2197. /**
  2198. * This defines how the texture is wrapped horizontally and corresponds to
  2199. * *V* in UV mapping.
  2200. *
  2201. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2202. * @default ClampToEdgeWrapping
  2203. */
  2204. this.wrapT = wrapT;
  2205. /**
  2206. * How the texture is sampled when a texel covers more than one pixel.
  2207. *
  2208. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2209. * @default LinearFilter
  2210. */
  2211. this.magFilter = magFilter;
  2212. /**
  2213. * How the texture is sampled when a texel covers less than one pixel.
  2214. *
  2215. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2216. * @default LinearMipmapLinearFilter
  2217. */
  2218. this.minFilter = minFilter;
  2219. /**
  2220. * The number of samples taken along the axis through the pixel that has the
  2221. * highest density of texels. By default, this value is `1`. A higher value
  2222. * gives a less blurry result than a basic mipmap, at the cost of more
  2223. * texture samples being used.
  2224. *
  2225. * @type {number}
  2226. * @default 0
  2227. */
  2228. this.anisotropy = anisotropy;
  2229. /**
  2230. * The format of the texture.
  2231. *
  2232. * @type {number}
  2233. * @default RGBAFormat
  2234. */
  2235. this.format = format;
  2236. /**
  2237. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  2238. * defines how the texture data is going to be stored on the GPU.
  2239. *
  2240. * This property allows to overwrite the default format.
  2241. *
  2242. * @type {?string}
  2243. * @default null
  2244. */
  2245. this.internalFormat = null;
  2246. /**
  2247. * The data type of the texture.
  2248. *
  2249. * @type {number}
  2250. * @default UnsignedByteType
  2251. */
  2252. this.type = type;
  2253. /**
  2254. * How much a single repetition of the texture is offset from the beginning,
  2255. * in each direction U and V. Typical range is `0.0` to `1.0`.
  2256. *
  2257. * @type {Vector2}
  2258. * @default (0,0)
  2259. */
  2260. this.offset = new Vector2( 0, 0 );
  2261. /**
  2262. * How many times the texture is repeated across the surface, in each
  2263. * direction U and V. If repeat is set greater than `1` in either direction,
  2264. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  2265. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  2266. *
  2267. * @type {Vector2}
  2268. * @default (1,1)
  2269. */
  2270. this.repeat = new Vector2( 1, 1 );
  2271. /**
  2272. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  2273. * to the center of the texture. Default is `(0, 0)`, the lower left.
  2274. *
  2275. * @type {Vector2}
  2276. * @default (0,0)
  2277. */
  2278. this.center = new Vector2( 0, 0 );
  2279. /**
  2280. * How much the texture is rotated around the center point, in radians.
  2281. * Positive values are counter-clockwise.
  2282. *
  2283. * @type {number}
  2284. * @default 0
  2285. */
  2286. this.rotation = 0;
  2287. /**
  2288. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  2289. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  2290. * {@link Texture#rotation}, and {@link Texture#center}.
  2291. *
  2292. * Set this to `false` if you are specifying the uv-transform matrix directly.
  2293. *
  2294. * @type {boolean}
  2295. * @default true
  2296. */
  2297. this.matrixAutoUpdate = true;
  2298. /**
  2299. * The uv-transformation matrix of the texture.
  2300. *
  2301. * @type {Matrix3}
  2302. */
  2303. this.matrix = new Matrix3();
  2304. /**
  2305. * Whether to generate mipmaps (if possible) for a texture.
  2306. *
  2307. * Set this to `false` if you are creating mipmaps manually.
  2308. *
  2309. * @type {boolean}
  2310. * @default true
  2311. */
  2312. this.generateMipmaps = true;
  2313. /**
  2314. * If set to `true`, the alpha channel, if present, is multiplied into the
  2315. * color channels when the texture is uploaded to the GPU.
  2316. *
  2317. * Note that this property has no effect when using `ImageBitmap`. You need to
  2318. * configure premultiply alpha on bitmap creation instead.
  2319. *
  2320. * @type {boolean}
  2321. * @default false
  2322. */
  2323. this.premultiplyAlpha = false;
  2324. /**
  2325. * If set to `true`, the texture is flipped along the vertical axis when
  2326. * uploaded to the GPU.
  2327. *
  2328. * Note that this property has no effect when using `ImageBitmap`. You need to
  2329. * configure the flip on bitmap creation instead.
  2330. *
  2331. * @type {boolean}
  2332. * @default true
  2333. */
  2334. this.flipY = true;
  2335. /**
  2336. * Specifies the alignment requirements for the start of each pixel row in memory.
  2337. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  2338. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  2339. *
  2340. * @type {number}
  2341. * @default 4
  2342. */
  2343. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2344. /**
  2345. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  2346. *
  2347. * @type {string}
  2348. * @default NoColorSpace
  2349. */
  2350. this.colorSpace = colorSpace;
  2351. /**
  2352. * An object that can be used to store custom data about the texture. It
  2353. * should not hold references to functions as these will not be cloned.
  2354. *
  2355. * @type {Object}
  2356. */
  2357. this.userData = {};
  2358. /**
  2359. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  2360. *
  2361. * @type {number}
  2362. * @readonly
  2363. * @default 0
  2364. */
  2365. this.version = 0;
  2366. /**
  2367. * A callback function, called when the texture is updated (e.g., when
  2368. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  2369. *
  2370. * @type {?Function}
  2371. * @default null
  2372. */
  2373. this.onUpdate = null;
  2374. /**
  2375. * An optional back reference to the textures render target.
  2376. *
  2377. * @type {?(RenderTarget|WebGLRenderTarget)}
  2378. * @default null
  2379. */
  2380. this.renderTarget = null;
  2381. /**
  2382. * Indicates whether a texture belongs to a render target or not.
  2383. *
  2384. * @type {boolean}
  2385. * @readonly
  2386. * @default false
  2387. */
  2388. this.isRenderTargetTexture = false;
  2389. /**
  2390. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  2391. * (only relevant for render target textures).
  2392. *
  2393. * @type {number}
  2394. * @readonly
  2395. * @default 0
  2396. */
  2397. this.pmremVersion = 0;
  2398. }
  2399. /**
  2400. * The image object holding the texture data.
  2401. *
  2402. * @type {?Object}
  2403. */
  2404. get image() {
  2405. return this.source.data;
  2406. }
  2407. set image( value = null ) {
  2408. this.source.data = value;
  2409. }
  2410. /**
  2411. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  2412. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  2413. */
  2414. updateMatrix() {
  2415. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2416. }
  2417. /**
  2418. * Returns a new texture with copied values from this instance.
  2419. *
  2420. * @return {Texture} A clone of this instance.
  2421. */
  2422. clone() {
  2423. return new this.constructor().copy( this );
  2424. }
  2425. /**
  2426. * Copies the values of the given texture to this instance.
  2427. *
  2428. * @param {Texture} source - The texture to copy.
  2429. * @return {Texture} A reference to this instance.
  2430. */
  2431. copy( source ) {
  2432. this.name = source.name;
  2433. this.source = source.source;
  2434. this.mipmaps = source.mipmaps.slice( 0 );
  2435. this.mapping = source.mapping;
  2436. this.channel = source.channel;
  2437. this.wrapS = source.wrapS;
  2438. this.wrapT = source.wrapT;
  2439. this.magFilter = source.magFilter;
  2440. this.minFilter = source.minFilter;
  2441. this.anisotropy = source.anisotropy;
  2442. this.format = source.format;
  2443. this.internalFormat = source.internalFormat;
  2444. this.type = source.type;
  2445. this.offset.copy( source.offset );
  2446. this.repeat.copy( source.repeat );
  2447. this.center.copy( source.center );
  2448. this.rotation = source.rotation;
  2449. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2450. this.matrix.copy( source.matrix );
  2451. this.generateMipmaps = source.generateMipmaps;
  2452. this.premultiplyAlpha = source.premultiplyAlpha;
  2453. this.flipY = source.flipY;
  2454. this.unpackAlignment = source.unpackAlignment;
  2455. this.colorSpace = source.colorSpace;
  2456. this.renderTarget = source.renderTarget;
  2457. this.isRenderTargetTexture = source.isRenderTargetTexture;
  2458. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2459. this.needsUpdate = true;
  2460. return this;
  2461. }
  2462. /**
  2463. * Serializes the texture into JSON.
  2464. *
  2465. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  2466. * @return {Object} A JSON object representing the serialized texture.
  2467. * @see {@link ObjectLoader#parse}
  2468. */
  2469. toJSON( meta ) {
  2470. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2471. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2472. return meta.textures[ this.uuid ];
  2473. }
  2474. const output = {
  2475. metadata: {
  2476. version: 4.6,
  2477. type: 'Texture',
  2478. generator: 'Texture.toJSON'
  2479. },
  2480. uuid: this.uuid,
  2481. name: this.name,
  2482. image: this.source.toJSON( meta ).uuid,
  2483. mapping: this.mapping,
  2484. channel: this.channel,
  2485. repeat: [ this.repeat.x, this.repeat.y ],
  2486. offset: [ this.offset.x, this.offset.y ],
  2487. center: [ this.center.x, this.center.y ],
  2488. rotation: this.rotation,
  2489. wrap: [ this.wrapS, this.wrapT ],
  2490. format: this.format,
  2491. internalFormat: this.internalFormat,
  2492. type: this.type,
  2493. colorSpace: this.colorSpace,
  2494. minFilter: this.minFilter,
  2495. magFilter: this.magFilter,
  2496. anisotropy: this.anisotropy,
  2497. flipY: this.flipY,
  2498. generateMipmaps: this.generateMipmaps,
  2499. premultiplyAlpha: this.premultiplyAlpha,
  2500. unpackAlignment: this.unpackAlignment
  2501. };
  2502. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2503. if ( ! isRootObject ) {
  2504. meta.textures[ this.uuid ] = output;
  2505. }
  2506. return output;
  2507. }
  2508. /**
  2509. * Frees the GPU-related resources allocated by this instance. Call this
  2510. * method whenever this instance is no longer used in your app.
  2511. *
  2512. * @fires Texture#dispose
  2513. */
  2514. dispose() {
  2515. /**
  2516. * Fires when the texture has been disposed of.
  2517. *
  2518. * @event Texture#dispose
  2519. * @type {Object}
  2520. */
  2521. this.dispatchEvent( { type: 'dispose' } );
  2522. }
  2523. /**
  2524. * Transforms the given uv vector with the textures uv transformation matrix.
  2525. *
  2526. * @param {Vector2} uv - The uv vector.
  2527. * @return {Vector2} The transformed uv vector.
  2528. */
  2529. transformUv( uv ) {
  2530. if ( this.mapping !== UVMapping ) return uv;
  2531. uv.applyMatrix3( this.matrix );
  2532. if ( uv.x < 0 || uv.x > 1 ) {
  2533. switch ( this.wrapS ) {
  2534. case RepeatWrapping:
  2535. uv.x = uv.x - Math.floor( uv.x );
  2536. break;
  2537. case ClampToEdgeWrapping:
  2538. uv.x = uv.x < 0 ? 0 : 1;
  2539. break;
  2540. case MirroredRepeatWrapping:
  2541. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2542. uv.x = Math.ceil( uv.x ) - uv.x;
  2543. } else {
  2544. uv.x = uv.x - Math.floor( uv.x );
  2545. }
  2546. break;
  2547. }
  2548. }
  2549. if ( uv.y < 0 || uv.y > 1 ) {
  2550. switch ( this.wrapT ) {
  2551. case RepeatWrapping:
  2552. uv.y = uv.y - Math.floor( uv.y );
  2553. break;
  2554. case ClampToEdgeWrapping:
  2555. uv.y = uv.y < 0 ? 0 : 1;
  2556. break;
  2557. case MirroredRepeatWrapping:
  2558. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2559. uv.y = Math.ceil( uv.y ) - uv.y;
  2560. } else {
  2561. uv.y = uv.y - Math.floor( uv.y );
  2562. }
  2563. break;
  2564. }
  2565. }
  2566. if ( this.flipY ) {
  2567. uv.y = 1 - uv.y;
  2568. }
  2569. return uv;
  2570. }
  2571. /**
  2572. * Setting this property to `true` indicates the engine the texture
  2573. * must be updated in the next render. This triggers a texture upload
  2574. * to the GPU and ensures correct texture parameter configuration.
  2575. *
  2576. * @type {boolean}
  2577. * @default false
  2578. * @param {boolean} value
  2579. */
  2580. set needsUpdate( value ) {
  2581. if ( value === true ) {
  2582. this.version ++;
  2583. this.source.needsUpdate = true;
  2584. }
  2585. }
  2586. /**
  2587. * Setting this property to `true` indicates the engine the PMREM
  2588. * must be regenerated.
  2589. *
  2590. * @type {boolean}
  2591. * @default false
  2592. * @param {boolean} value
  2593. */
  2594. set needsPMREMUpdate( value ) {
  2595. if ( value === true ) {
  2596. this.pmremVersion ++;
  2597. }
  2598. }
  2599. }
  2600. /**
  2601. * The default image for all textures.
  2602. *
  2603. * @static
  2604. * @type {?Image}
  2605. * @default null
  2606. */
  2607. Texture.DEFAULT_IMAGE = null;
  2608. /**
  2609. * The default mapping for all textures.
  2610. *
  2611. * @static
  2612. * @type {number}
  2613. * @default UVMapping
  2614. */
  2615. Texture.DEFAULT_MAPPING = UVMapping;
  2616. /**
  2617. * The default anisotropy value for all textures.
  2618. *
  2619. * @static
  2620. * @type {number}
  2621. * @default 1
  2622. */
  2623. Texture.DEFAULT_ANISOTROPY = 1;
  2624. /**
  2625. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  2626. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  2627. *
  2628. * - A point in 4D space.
  2629. * - A direction and length in 4D space. In three.js the length will
  2630. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  2631. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  2632. * - Any arbitrary ordered quadruplet of numbers.
  2633. *
  2634. * There are other things a 4D vector can be used to represent, however these
  2635. * are the most common uses in *three.js*.
  2636. *
  2637. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2638. * the corresponding order.
  2639. * ```js
  2640. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  2641. *
  2642. * //no arguments; will be initialised to (0, 0, 0, 1)
  2643. * const b = new THREE.Vector4( );
  2644. *
  2645. * const d = a.dot( b );
  2646. * ```
  2647. */
  2648. class Vector4 {
  2649. /**
  2650. * Constructs a new 4D vector.
  2651. *
  2652. * @param {number} [x=0] - The x value of this vector.
  2653. * @param {number} [y=0] - The y value of this vector.
  2654. * @param {number} [z=0] - The z value of this vector.
  2655. * @param {number} [w=1] - The w value of this vector.
  2656. */
  2657. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2658. /**
  2659. * This flag can be used for type testing.
  2660. *
  2661. * @type {boolean}
  2662. * @readonly
  2663. * @default true
  2664. */
  2665. Vector4.prototype.isVector4 = true;
  2666. /**
  2667. * The x value of this vector.
  2668. *
  2669. * @type {number}
  2670. */
  2671. this.x = x;
  2672. /**
  2673. * The y value of this vector.
  2674. *
  2675. * @type {number}
  2676. */
  2677. this.y = y;
  2678. /**
  2679. * The z value of this vector.
  2680. *
  2681. * @type {number}
  2682. */
  2683. this.z = z;
  2684. /**
  2685. * The w value of this vector.
  2686. *
  2687. * @type {number}
  2688. */
  2689. this.w = w;
  2690. }
  2691. /**
  2692. * Alias for {@link Vector4#z}.
  2693. *
  2694. * @type {number}
  2695. */
  2696. get width() {
  2697. return this.z;
  2698. }
  2699. set width( value ) {
  2700. this.z = value;
  2701. }
  2702. /**
  2703. * Alias for {@link Vector4#w}.
  2704. *
  2705. * @type {number}
  2706. */
  2707. get height() {
  2708. return this.w;
  2709. }
  2710. set height( value ) {
  2711. this.w = value;
  2712. }
  2713. /**
  2714. * Sets the vector components.
  2715. *
  2716. * @param {number} x - The value of the x component.
  2717. * @param {number} y - The value of the y component.
  2718. * @param {number} z - The value of the z component.
  2719. * @param {number} w - The value of the w component.
  2720. * @return {Vector4} A reference to this vector.
  2721. */
  2722. set( x, y, z, w ) {
  2723. this.x = x;
  2724. this.y = y;
  2725. this.z = z;
  2726. this.w = w;
  2727. return this;
  2728. }
  2729. /**
  2730. * Sets the vector components to the same value.
  2731. *
  2732. * @param {number} scalar - The value to set for all vector components.
  2733. * @return {Vector4} A reference to this vector.
  2734. */
  2735. setScalar( scalar ) {
  2736. this.x = scalar;
  2737. this.y = scalar;
  2738. this.z = scalar;
  2739. this.w = scalar;
  2740. return this;
  2741. }
  2742. /**
  2743. * Sets the vector's x component to the given value
  2744. *
  2745. * @param {number} x - The value to set.
  2746. * @return {Vector4} A reference to this vector.
  2747. */
  2748. setX( x ) {
  2749. this.x = x;
  2750. return this;
  2751. }
  2752. /**
  2753. * Sets the vector's y component to the given value
  2754. *
  2755. * @param {number} y - The value to set.
  2756. * @return {Vector4} A reference to this vector.
  2757. */
  2758. setY( y ) {
  2759. this.y = y;
  2760. return this;
  2761. }
  2762. /**
  2763. * Sets the vector's z component to the given value
  2764. *
  2765. * @param {number} z - The value to set.
  2766. * @return {Vector4} A reference to this vector.
  2767. */
  2768. setZ( z ) {
  2769. this.z = z;
  2770. return this;
  2771. }
  2772. /**
  2773. * Sets the vector's w component to the given value
  2774. *
  2775. * @param {number} w - The value to set.
  2776. * @return {Vector4} A reference to this vector.
  2777. */
  2778. setW( w ) {
  2779. this.w = w;
  2780. return this;
  2781. }
  2782. /**
  2783. * Allows to set a vector component with an index.
  2784. *
  2785. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2786. * `2` equals to z, `3` equals to w.
  2787. * @param {number} value - The value to set.
  2788. * @return {Vector4} A reference to this vector.
  2789. */
  2790. setComponent( index, value ) {
  2791. switch ( index ) {
  2792. case 0: this.x = value; break;
  2793. case 1: this.y = value; break;
  2794. case 2: this.z = value; break;
  2795. case 3: this.w = value; break;
  2796. default: throw new Error( 'index is out of range: ' + index );
  2797. }
  2798. return this;
  2799. }
  2800. /**
  2801. * Returns the value of the vector component which matches the given index.
  2802. *
  2803. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2804. * `2` equals to z, `3` equals to w.
  2805. * @return {number} A vector component value.
  2806. */
  2807. getComponent( index ) {
  2808. switch ( index ) {
  2809. case 0: return this.x;
  2810. case 1: return this.y;
  2811. case 2: return this.z;
  2812. case 3: return this.w;
  2813. default: throw new Error( 'index is out of range: ' + index );
  2814. }
  2815. }
  2816. /**
  2817. * Returns a new vector with copied values from this instance.
  2818. *
  2819. * @return {Vector4} A clone of this instance.
  2820. */
  2821. clone() {
  2822. return new this.constructor( this.x, this.y, this.z, this.w );
  2823. }
  2824. /**
  2825. * Copies the values of the given vector to this instance.
  2826. *
  2827. * @param {Vector3|Vector4} v - The vector to copy.
  2828. * @return {Vector4} A reference to this vector.
  2829. */
  2830. copy( v ) {
  2831. this.x = v.x;
  2832. this.y = v.y;
  2833. this.z = v.z;
  2834. this.w = ( v.w !== undefined ) ? v.w : 1;
  2835. return this;
  2836. }
  2837. /**
  2838. * Adds the given vector to this instance.
  2839. *
  2840. * @param {Vector4} v - The vector to add.
  2841. * @return {Vector4} A reference to this vector.
  2842. */
  2843. add( v ) {
  2844. this.x += v.x;
  2845. this.y += v.y;
  2846. this.z += v.z;
  2847. this.w += v.w;
  2848. return this;
  2849. }
  2850. /**
  2851. * Adds the given scalar value to all components of this instance.
  2852. *
  2853. * @param {number} s - The scalar to add.
  2854. * @return {Vector4} A reference to this vector.
  2855. */
  2856. addScalar( s ) {
  2857. this.x += s;
  2858. this.y += s;
  2859. this.z += s;
  2860. this.w += s;
  2861. return this;
  2862. }
  2863. /**
  2864. * Adds the given vectors and stores the result in this instance.
  2865. *
  2866. * @param {Vector4} a - The first vector.
  2867. * @param {Vector4} b - The second vector.
  2868. * @return {Vector4} A reference to this vector.
  2869. */
  2870. addVectors( a, b ) {
  2871. this.x = a.x + b.x;
  2872. this.y = a.y + b.y;
  2873. this.z = a.z + b.z;
  2874. this.w = a.w + b.w;
  2875. return this;
  2876. }
  2877. /**
  2878. * Adds the given vector scaled by the given factor to this instance.
  2879. *
  2880. * @param {Vector4} v - The vector.
  2881. * @param {number} s - The factor that scales `v`.
  2882. * @return {Vector4} A reference to this vector.
  2883. */
  2884. addScaledVector( v, s ) {
  2885. this.x += v.x * s;
  2886. this.y += v.y * s;
  2887. this.z += v.z * s;
  2888. this.w += v.w * s;
  2889. return this;
  2890. }
  2891. /**
  2892. * Subtracts the given vector from this instance.
  2893. *
  2894. * @param {Vector4} v - The vector to subtract.
  2895. * @return {Vector4} A reference to this vector.
  2896. */
  2897. sub( v ) {
  2898. this.x -= v.x;
  2899. this.y -= v.y;
  2900. this.z -= v.z;
  2901. this.w -= v.w;
  2902. return this;
  2903. }
  2904. /**
  2905. * Subtracts the given scalar value from all components of this instance.
  2906. *
  2907. * @param {number} s - The scalar to subtract.
  2908. * @return {Vector4} A reference to this vector.
  2909. */
  2910. subScalar( s ) {
  2911. this.x -= s;
  2912. this.y -= s;
  2913. this.z -= s;
  2914. this.w -= s;
  2915. return this;
  2916. }
  2917. /**
  2918. * Subtracts the given vectors and stores the result in this instance.
  2919. *
  2920. * @param {Vector4} a - The first vector.
  2921. * @param {Vector4} b - The second vector.
  2922. * @return {Vector4} A reference to this vector.
  2923. */
  2924. subVectors( a, b ) {
  2925. this.x = a.x - b.x;
  2926. this.y = a.y - b.y;
  2927. this.z = a.z - b.z;
  2928. this.w = a.w - b.w;
  2929. return this;
  2930. }
  2931. /**
  2932. * Multiplies the given vector with this instance.
  2933. *
  2934. * @param {Vector4} v - The vector to multiply.
  2935. * @return {Vector4} A reference to this vector.
  2936. */
  2937. multiply( v ) {
  2938. this.x *= v.x;
  2939. this.y *= v.y;
  2940. this.z *= v.z;
  2941. this.w *= v.w;
  2942. return this;
  2943. }
  2944. /**
  2945. * Multiplies the given scalar value with all components of this instance.
  2946. *
  2947. * @param {number} scalar - The scalar to multiply.
  2948. * @return {Vector4} A reference to this vector.
  2949. */
  2950. multiplyScalar( scalar ) {
  2951. this.x *= scalar;
  2952. this.y *= scalar;
  2953. this.z *= scalar;
  2954. this.w *= scalar;
  2955. return this;
  2956. }
  2957. /**
  2958. * Multiplies this vector with the given 4x4 matrix.
  2959. *
  2960. * @param {Matrix4} m - The 4x4 matrix.
  2961. * @return {Vector4} A reference to this vector.
  2962. */
  2963. applyMatrix4( m ) {
  2964. const x = this.x, y = this.y, z = this.z, w = this.w;
  2965. const e = m.elements;
  2966. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2967. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2968. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2969. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2970. return this;
  2971. }
  2972. /**
  2973. * Divides this instance by the given vector.
  2974. *
  2975. * @param {Vector4} v - The vector to divide.
  2976. * @return {Vector4} A reference to this vector.
  2977. */
  2978. divide( v ) {
  2979. this.x /= v.x;
  2980. this.y /= v.y;
  2981. this.z /= v.z;
  2982. this.w /= v.w;
  2983. return this;
  2984. }
  2985. /**
  2986. * Divides this vector by the given scalar.
  2987. *
  2988. * @param {number} scalar - The scalar to divide.
  2989. * @return {Vector4} A reference to this vector.
  2990. */
  2991. divideScalar( scalar ) {
  2992. return this.multiplyScalar( 1 / scalar );
  2993. }
  2994. /**
  2995. * Sets the x, y and z components of this
  2996. * vector to the quaternion's axis and w to the angle.
  2997. *
  2998. * @param {Quaternion} q - The Quaternion to set.
  2999. * @return {Vector4} A reference to this vector.
  3000. */
  3001. setAxisAngleFromQuaternion( q ) {
  3002. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3003. // q is assumed to be normalized
  3004. this.w = 2 * Math.acos( q.w );
  3005. const s = Math.sqrt( 1 - q.w * q.w );
  3006. if ( s < 0.0001 ) {
  3007. this.x = 1;
  3008. this.y = 0;
  3009. this.z = 0;
  3010. } else {
  3011. this.x = q.x / s;
  3012. this.y = q.y / s;
  3013. this.z = q.z / s;
  3014. }
  3015. return this;
  3016. }
  3017. /**
  3018. * Sets the x, y and z components of this
  3019. * vector to the axis of rotation and w to the angle.
  3020. *
  3021. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  3022. * @return {Vector4} A reference to this vector.
  3023. */
  3024. setAxisAngleFromRotationMatrix( m ) {
  3025. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3026. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3027. let angle, x, y, z; // variables for result
  3028. const epsilon = 0.01, // margin to allow for rounding errors
  3029. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3030. te = m.elements,
  3031. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3032. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3033. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3034. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3035. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3036. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3037. // singularity found
  3038. // first check for identity matrix which must have +1 for all terms
  3039. // in leading diagonal and zero in other terms
  3040. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3041. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3042. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3043. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3044. // this singularity is identity matrix so angle = 0
  3045. this.set( 1, 0, 0, 0 );
  3046. return this; // zero angle, arbitrary axis
  3047. }
  3048. // otherwise this singularity is angle = 180
  3049. angle = Math.PI;
  3050. const xx = ( m11 + 1 ) / 2;
  3051. const yy = ( m22 + 1 ) / 2;
  3052. const zz = ( m33 + 1 ) / 2;
  3053. const xy = ( m12 + m21 ) / 4;
  3054. const xz = ( m13 + m31 ) / 4;
  3055. const yz = ( m23 + m32 ) / 4;
  3056. if ( ( xx > yy ) && ( xx > zz ) ) {
  3057. // m11 is the largest diagonal term
  3058. if ( xx < epsilon ) {
  3059. x = 0;
  3060. y = 0.707106781;
  3061. z = 0.707106781;
  3062. } else {
  3063. x = Math.sqrt( xx );
  3064. y = xy / x;
  3065. z = xz / x;
  3066. }
  3067. } else if ( yy > zz ) {
  3068. // m22 is the largest diagonal term
  3069. if ( yy < epsilon ) {
  3070. x = 0.707106781;
  3071. y = 0;
  3072. z = 0.707106781;
  3073. } else {
  3074. y = Math.sqrt( yy );
  3075. x = xy / y;
  3076. z = yz / y;
  3077. }
  3078. } else {
  3079. // m33 is the largest diagonal term so base result on this
  3080. if ( zz < epsilon ) {
  3081. x = 0.707106781;
  3082. y = 0.707106781;
  3083. z = 0;
  3084. } else {
  3085. z = Math.sqrt( zz );
  3086. x = xz / z;
  3087. y = yz / z;
  3088. }
  3089. }
  3090. this.set( x, y, z, angle );
  3091. return this; // return 180 deg rotation
  3092. }
  3093. // as we have reached here there are no singularities so we can handle normally
  3094. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3095. ( m13 - m31 ) * ( m13 - m31 ) +
  3096. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3097. if ( Math.abs( s ) < 0.001 ) s = 1;
  3098. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3099. // caught by singularity test above, but I've left it in just in case
  3100. this.x = ( m32 - m23 ) / s;
  3101. this.y = ( m13 - m31 ) / s;
  3102. this.z = ( m21 - m12 ) / s;
  3103. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3104. return this;
  3105. }
  3106. /**
  3107. * Sets the vector components to the position elements of the
  3108. * given transformation matrix.
  3109. *
  3110. * @param {Matrix4} m - The 4x4 matrix.
  3111. * @return {Vector4} A reference to this vector.
  3112. */
  3113. setFromMatrixPosition( m ) {
  3114. const e = m.elements;
  3115. this.x = e[ 12 ];
  3116. this.y = e[ 13 ];
  3117. this.z = e[ 14 ];
  3118. this.w = e[ 15 ];
  3119. return this;
  3120. }
  3121. /**
  3122. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  3123. * value, replace that value with the corresponding min value.
  3124. *
  3125. * @param {Vector4} v - The vector.
  3126. * @return {Vector4} A reference to this vector.
  3127. */
  3128. min( v ) {
  3129. this.x = Math.min( this.x, v.x );
  3130. this.y = Math.min( this.y, v.y );
  3131. this.z = Math.min( this.z, v.z );
  3132. this.w = Math.min( this.w, v.w );
  3133. return this;
  3134. }
  3135. /**
  3136. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  3137. * value, replace that value with the corresponding max value.
  3138. *
  3139. * @param {Vector4} v - The vector.
  3140. * @return {Vector4} A reference to this vector.
  3141. */
  3142. max( v ) {
  3143. this.x = Math.max( this.x, v.x );
  3144. this.y = Math.max( this.y, v.y );
  3145. this.z = Math.max( this.z, v.z );
  3146. this.w = Math.max( this.w, v.w );
  3147. return this;
  3148. }
  3149. /**
  3150. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  3151. * value, it is replaced by the corresponding value.
  3152. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  3153. * it is replaced by the corresponding value.
  3154. *
  3155. * @param {Vector4} min - The minimum x, y and z values.
  3156. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  3157. * @return {Vector4} A reference to this vector.
  3158. */
  3159. clamp( min, max ) {
  3160. // assumes min < max, componentwise
  3161. this.x = clamp( this.x, min.x, max.x );
  3162. this.y = clamp( this.y, min.y, max.y );
  3163. this.z = clamp( this.z, min.z, max.z );
  3164. this.w = clamp( this.w, min.w, max.w );
  3165. return this;
  3166. }
  3167. /**
  3168. * If this vector's x, y, z or w values are greater than the max value, they are
  3169. * replaced by the max value.
  3170. * If this vector's x, y, z or w values are less than the min value, they are
  3171. * replaced by the min value.
  3172. *
  3173. * @param {number} minVal - The minimum value the components will be clamped to.
  3174. * @param {number} maxVal - The maximum value the components will be clamped to.
  3175. * @return {Vector4} A reference to this vector.
  3176. */
  3177. clampScalar( minVal, maxVal ) {
  3178. this.x = clamp( this.x, minVal, maxVal );
  3179. this.y = clamp( this.y, minVal, maxVal );
  3180. this.z = clamp( this.z, minVal, maxVal );
  3181. this.w = clamp( this.w, minVal, maxVal );
  3182. return this;
  3183. }
  3184. /**
  3185. * If this vector's length is greater than the max value, it is replaced by
  3186. * the max value.
  3187. * If this vector's length is less than the min value, it is replaced by the
  3188. * min value.
  3189. *
  3190. * @param {number} min - The minimum value the vector length will be clamped to.
  3191. * @param {number} max - The maximum value the vector length will be clamped to.
  3192. * @return {Vector4} A reference to this vector.
  3193. */
  3194. clampLength( min, max ) {
  3195. const length = this.length();
  3196. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3197. }
  3198. /**
  3199. * The components of this vector are rounded down to the nearest integer value.
  3200. *
  3201. * @return {Vector4} A reference to this vector.
  3202. */
  3203. floor() {
  3204. this.x = Math.floor( this.x );
  3205. this.y = Math.floor( this.y );
  3206. this.z = Math.floor( this.z );
  3207. this.w = Math.floor( this.w );
  3208. return this;
  3209. }
  3210. /**
  3211. * The components of this vector are rounded up to the nearest integer value.
  3212. *
  3213. * @return {Vector4} A reference to this vector.
  3214. */
  3215. ceil() {
  3216. this.x = Math.ceil( this.x );
  3217. this.y = Math.ceil( this.y );
  3218. this.z = Math.ceil( this.z );
  3219. this.w = Math.ceil( this.w );
  3220. return this;
  3221. }
  3222. /**
  3223. * The components of this vector are rounded to the nearest integer value
  3224. *
  3225. * @return {Vector4} A reference to this vector.
  3226. */
  3227. round() {
  3228. this.x = Math.round( this.x );
  3229. this.y = Math.round( this.y );
  3230. this.z = Math.round( this.z );
  3231. this.w = Math.round( this.w );
  3232. return this;
  3233. }
  3234. /**
  3235. * The components of this vector are rounded towards zero (up if negative,
  3236. * down if positive) to an integer value.
  3237. *
  3238. * @return {Vector4} A reference to this vector.
  3239. */
  3240. roundToZero() {
  3241. this.x = Math.trunc( this.x );
  3242. this.y = Math.trunc( this.y );
  3243. this.z = Math.trunc( this.z );
  3244. this.w = Math.trunc( this.w );
  3245. return this;
  3246. }
  3247. /**
  3248. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  3249. *
  3250. * @return {Vector4} A reference to this vector.
  3251. */
  3252. negate() {
  3253. this.x = - this.x;
  3254. this.y = - this.y;
  3255. this.z = - this.z;
  3256. this.w = - this.w;
  3257. return this;
  3258. }
  3259. /**
  3260. * Calculates the dot product of the given vector with this instance.
  3261. *
  3262. * @param {Vector4} v - The vector to compute the dot product with.
  3263. * @return {number} The result of the dot product.
  3264. */
  3265. dot( v ) {
  3266. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3267. }
  3268. /**
  3269. * Computes the square of the Euclidean length (straight-line length) from
  3270. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  3271. * compare the length squared instead as it is slightly more efficient to calculate.
  3272. *
  3273. * @return {number} The square length of this vector.
  3274. */
  3275. lengthSq() {
  3276. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3277. }
  3278. /**
  3279. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  3280. *
  3281. * @return {number} The length of this vector.
  3282. */
  3283. length() {
  3284. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3285. }
  3286. /**
  3287. * Computes the Manhattan length of this vector.
  3288. *
  3289. * @return {number} The length of this vector.
  3290. */
  3291. manhattanLength() {
  3292. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3293. }
  3294. /**
  3295. * Converts this vector to a unit vector - that is, sets it equal to a vector
  3296. * with the same direction as this one, but with a vector length of `1`.
  3297. *
  3298. * @return {Vector4} A reference to this vector.
  3299. */
  3300. normalize() {
  3301. return this.divideScalar( this.length() || 1 );
  3302. }
  3303. /**
  3304. * Sets this vector to a vector with the same direction as this one, but
  3305. * with the specified length.
  3306. *
  3307. * @param {number} length - The new length of this vector.
  3308. * @return {Vector4} A reference to this vector.
  3309. */
  3310. setLength( length ) {
  3311. return this.normalize().multiplyScalar( length );
  3312. }
  3313. /**
  3314. * Linearly interpolates between the given vector and this instance, where
  3315. * alpha is the percent distance along the line - alpha = 0 will be this
  3316. * vector, and alpha = 1 will be the given one.
  3317. *
  3318. * @param {Vector4} v - The vector to interpolate towards.
  3319. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3320. * @return {Vector4} A reference to this vector.
  3321. */
  3322. lerp( v, alpha ) {
  3323. this.x += ( v.x - this.x ) * alpha;
  3324. this.y += ( v.y - this.y ) * alpha;
  3325. this.z += ( v.z - this.z ) * alpha;
  3326. this.w += ( v.w - this.w ) * alpha;
  3327. return this;
  3328. }
  3329. /**
  3330. * Linearly interpolates between the given vectors, where alpha is the percent
  3331. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3332. * be the second one. The result is stored in this instance.
  3333. *
  3334. * @param {Vector4} v1 - The first vector.
  3335. * @param {Vector4} v2 - The second vector.
  3336. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3337. * @return {Vector4} A reference to this vector.
  3338. */
  3339. lerpVectors( v1, v2, alpha ) {
  3340. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3341. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3342. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3343. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  3344. return this;
  3345. }
  3346. /**
  3347. * Returns `true` if this vector is equal with the given one.
  3348. *
  3349. * @param {Vector4} v - The vector to test for equality.
  3350. * @return {boolean} Whether this vector is equal with the given one.
  3351. */
  3352. equals( v ) {
  3353. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3354. }
  3355. /**
  3356. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  3357. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  3358. *
  3359. * @param {Array<number>} array - An array holding the vector component values.
  3360. * @param {number} [offset=0] - The offset into the array.
  3361. * @return {Vector4} A reference to this vector.
  3362. */
  3363. fromArray( array, offset = 0 ) {
  3364. this.x = array[ offset ];
  3365. this.y = array[ offset + 1 ];
  3366. this.z = array[ offset + 2 ];
  3367. this.w = array[ offset + 3 ];
  3368. return this;
  3369. }
  3370. /**
  3371. * Writes the components of this vector to the given array. If no array is provided,
  3372. * the method returns a new instance.
  3373. *
  3374. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3375. * @param {number} [offset=0] - Index of the first element in the array.
  3376. * @return {Array<number>} The vector components.
  3377. */
  3378. toArray( array = [], offset = 0 ) {
  3379. array[ offset ] = this.x;
  3380. array[ offset + 1 ] = this.y;
  3381. array[ offset + 2 ] = this.z;
  3382. array[ offset + 3 ] = this.w;
  3383. return array;
  3384. }
  3385. /**
  3386. * Sets the components of this vector from the given buffer attribute.
  3387. *
  3388. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3389. * @param {number} index - The index into the attribute.
  3390. * @return {Vector4} A reference to this vector.
  3391. */
  3392. fromBufferAttribute( attribute, index ) {
  3393. this.x = attribute.getX( index );
  3394. this.y = attribute.getY( index );
  3395. this.z = attribute.getZ( index );
  3396. this.w = attribute.getW( index );
  3397. return this;
  3398. }
  3399. /**
  3400. * Sets each component of this vector to a pseudo-random value between `0` and
  3401. * `1`, excluding `1`.
  3402. *
  3403. * @return {Vector4} A reference to this vector.
  3404. */
  3405. random() {
  3406. this.x = Math.random();
  3407. this.y = Math.random();
  3408. this.z = Math.random();
  3409. this.w = Math.random();
  3410. return this;
  3411. }
  3412. *[ Symbol.iterator ]() {
  3413. yield this.x;
  3414. yield this.y;
  3415. yield this.z;
  3416. yield this.w;
  3417. }
  3418. }
  3419. /*
  3420. In options, we can specify:
  3421. * Texture parameters for an auto-generated target texture
  3422. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3423. */
  3424. class RenderTarget extends EventDispatcher {
  3425. constructor( width = 1, height = 1, options = {} ) {
  3426. super();
  3427. this.isRenderTarget = true;
  3428. this.width = width;
  3429. this.height = height;
  3430. this.depth = 1;
  3431. this.scissor = new Vector4( 0, 0, width, height );
  3432. this.scissorTest = false;
  3433. this.viewport = new Vector4( 0, 0, width, height );
  3434. const image = { width: width, height: height, depth: 1 };
  3435. options = Object.assign( {
  3436. generateMipmaps: false,
  3437. internalFormat: null,
  3438. minFilter: LinearFilter,
  3439. depthBuffer: true,
  3440. stencilBuffer: false,
  3441. resolveDepthBuffer: true,
  3442. resolveStencilBuffer: true,
  3443. depthTexture: null,
  3444. samples: 0,
  3445. count: 1
  3446. }, options );
  3447. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  3448. texture.flipY = false;
  3449. texture.generateMipmaps = options.generateMipmaps;
  3450. texture.internalFormat = options.internalFormat;
  3451. this.textures = [];
  3452. const count = options.count;
  3453. for ( let i = 0; i < count; i ++ ) {
  3454. this.textures[ i ] = texture.clone();
  3455. this.textures[ i ].isRenderTargetTexture = true;
  3456. this.textures[ i ].renderTarget = this;
  3457. }
  3458. this.depthBuffer = options.depthBuffer;
  3459. this.stencilBuffer = options.stencilBuffer;
  3460. this.resolveDepthBuffer = options.resolveDepthBuffer;
  3461. this.resolveStencilBuffer = options.resolveStencilBuffer;
  3462. this._depthTexture = null;
  3463. this.depthTexture = options.depthTexture;
  3464. this.samples = options.samples;
  3465. }
  3466. get texture() {
  3467. return this.textures[ 0 ];
  3468. }
  3469. set texture( value ) {
  3470. this.textures[ 0 ] = value;
  3471. }
  3472. set depthTexture( current ) {
  3473. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  3474. if ( current !== null ) current.renderTarget = this;
  3475. this._depthTexture = current;
  3476. }
  3477. get depthTexture() {
  3478. return this._depthTexture;
  3479. }
  3480. setSize( width, height, depth = 1 ) {
  3481. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  3482. this.width = width;
  3483. this.height = height;
  3484. this.depth = depth;
  3485. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  3486. this.textures[ i ].image.width = width;
  3487. this.textures[ i ].image.height = height;
  3488. this.textures[ i ].image.depth = depth;
  3489. }
  3490. this.dispose();
  3491. }
  3492. this.viewport.set( 0, 0, width, height );
  3493. this.scissor.set( 0, 0, width, height );
  3494. }
  3495. clone() {
  3496. return new this.constructor().copy( this );
  3497. }
  3498. copy( source ) {
  3499. this.width = source.width;
  3500. this.height = source.height;
  3501. this.depth = source.depth;
  3502. this.scissor.copy( source.scissor );
  3503. this.scissorTest = source.scissorTest;
  3504. this.viewport.copy( source.viewport );
  3505. this.textures.length = 0;
  3506. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  3507. this.textures[ i ] = source.textures[ i ].clone();
  3508. this.textures[ i ].isRenderTargetTexture = true;
  3509. this.textures[ i ].renderTarget = this;
  3510. // ensure image object is not shared, see #20328
  3511. const image = Object.assign( {}, source.textures[ i ].image );
  3512. this.textures[ i ].source = new Source( image );
  3513. }
  3514. this.depthBuffer = source.depthBuffer;
  3515. this.stencilBuffer = source.stencilBuffer;
  3516. this.resolveDepthBuffer = source.resolveDepthBuffer;
  3517. this.resolveStencilBuffer = source.resolveStencilBuffer;
  3518. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  3519. this.samples = source.samples;
  3520. return this;
  3521. }
  3522. dispose() {
  3523. this.dispatchEvent( { type: 'dispose' } );
  3524. }
  3525. }
  3526. class WebGLRenderTarget extends RenderTarget {
  3527. constructor( width = 1, height = 1, options = {} ) {
  3528. super( width, height, options );
  3529. this.isWebGLRenderTarget = true;
  3530. }
  3531. }
  3532. class DataArrayTexture extends Texture {
  3533. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3534. super( null );
  3535. this.isDataArrayTexture = true;
  3536. this.image = { data, width, height, depth };
  3537. this.magFilter = NearestFilter;
  3538. this.minFilter = NearestFilter;
  3539. this.wrapR = ClampToEdgeWrapping;
  3540. this.generateMipmaps = false;
  3541. this.flipY = false;
  3542. this.unpackAlignment = 1;
  3543. this.layerUpdates = new Set();
  3544. }
  3545. addLayerUpdate( layerIndex ) {
  3546. this.layerUpdates.add( layerIndex );
  3547. }
  3548. clearLayerUpdates() {
  3549. this.layerUpdates.clear();
  3550. }
  3551. }
  3552. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  3553. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3554. super( width, height, options );
  3555. this.isWebGLArrayRenderTarget = true;
  3556. this.depth = depth;
  3557. this.texture = new DataArrayTexture( null, width, height, depth );
  3558. this.texture.isRenderTargetTexture = true;
  3559. }
  3560. }
  3561. class Data3DTexture extends Texture {
  3562. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3563. // We're going to add .setXXX() methods for setting properties later.
  3564. // Users can still set in Data3DTexture directly.
  3565. //
  3566. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  3567. // texture.anisotropy = 16;
  3568. //
  3569. // See #14839
  3570. super( null );
  3571. this.isData3DTexture = true;
  3572. this.image = { data, width, height, depth };
  3573. this.magFilter = NearestFilter;
  3574. this.minFilter = NearestFilter;
  3575. this.wrapR = ClampToEdgeWrapping;
  3576. this.generateMipmaps = false;
  3577. this.flipY = false;
  3578. this.unpackAlignment = 1;
  3579. }
  3580. }
  3581. class WebGL3DRenderTarget extends WebGLRenderTarget {
  3582. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3583. super( width, height, options );
  3584. this.isWebGL3DRenderTarget = true;
  3585. this.depth = depth;
  3586. this.texture = new Data3DTexture( null, width, height, depth );
  3587. this.texture.isRenderTargetTexture = true;
  3588. }
  3589. }
  3590. /**
  3591. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3592. *
  3593. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3594. * the corresponding order.
  3595. *
  3596. * Note that three.js expects Quaternions to be normalized.
  3597. * ```js
  3598. * const quaternion = new THREE.Quaternion();
  3599. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3600. *
  3601. * const vector = new THREE.Vector3( 1, 0, 0 );
  3602. * vector.applyQuaternion( quaternion );
  3603. * ```
  3604. */
  3605. class Quaternion {
  3606. /**
  3607. * Constructs a new quaternion.
  3608. *
  3609. * @param {number} [x=0] - The x value of this quaternion.
  3610. * @param {number} [y=0] - The y value of this quaternion.
  3611. * @param {number} [z=0] - The z value of this quaternion.
  3612. * @param {number} [w=1] - The w value of this quaternion.
  3613. */
  3614. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3615. /**
  3616. * This flag can be used for type testing.
  3617. *
  3618. * @type {boolean}
  3619. * @readonly
  3620. * @default true
  3621. */
  3622. this.isQuaternion = true;
  3623. this._x = x;
  3624. this._y = y;
  3625. this._z = z;
  3626. this._w = w;
  3627. }
  3628. /**
  3629. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3630. * quaternion data are managed in flat arrays.
  3631. *
  3632. * @param {Array<number>} dst - The destination array.
  3633. * @param {number} dstOffset - An offset into the destination array.
  3634. * @param {Array<number>} src0 - The source array of the first quaternion.
  3635. * @param {number} srcOffset0 - An offset into the first source array.
  3636. * @param {Array<number>} src1 - The source array of the second quaternion.
  3637. * @param {number} srcOffset1 - An offset into the second source array.
  3638. * @param {number} t - The interpolation factor in the range `[0,1]`.
  3639. * @see {@link Quaternion#slerp}
  3640. */
  3641. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3642. // fuzz-free, array-based Quaternion SLERP operation
  3643. let x0 = src0[ srcOffset0 + 0 ],
  3644. y0 = src0[ srcOffset0 + 1 ],
  3645. z0 = src0[ srcOffset0 + 2 ],
  3646. w0 = src0[ srcOffset0 + 3 ];
  3647. const x1 = src1[ srcOffset1 + 0 ],
  3648. y1 = src1[ srcOffset1 + 1 ],
  3649. z1 = src1[ srcOffset1 + 2 ],
  3650. w1 = src1[ srcOffset1 + 3 ];
  3651. if ( t === 0 ) {
  3652. dst[ dstOffset + 0 ] = x0;
  3653. dst[ dstOffset + 1 ] = y0;
  3654. dst[ dstOffset + 2 ] = z0;
  3655. dst[ dstOffset + 3 ] = w0;
  3656. return;
  3657. }
  3658. if ( t === 1 ) {
  3659. dst[ dstOffset + 0 ] = x1;
  3660. dst[ dstOffset + 1 ] = y1;
  3661. dst[ dstOffset + 2 ] = z1;
  3662. dst[ dstOffset + 3 ] = w1;
  3663. return;
  3664. }
  3665. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3666. let s = 1 - t;
  3667. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  3668. dir = ( cos >= 0 ? 1 : -1 ),
  3669. sqrSin = 1 - cos * cos;
  3670. // Skip the Slerp for tiny steps to avoid numeric problems:
  3671. if ( sqrSin > Number.EPSILON ) {
  3672. const sin = Math.sqrt( sqrSin ),
  3673. len = Math.atan2( sin, cos * dir );
  3674. s = Math.sin( s * len ) / sin;
  3675. t = Math.sin( t * len ) / sin;
  3676. }
  3677. const tDir = t * dir;
  3678. x0 = x0 * s + x1 * tDir;
  3679. y0 = y0 * s + y1 * tDir;
  3680. z0 = z0 * s + z1 * tDir;
  3681. w0 = w0 * s + w1 * tDir;
  3682. // Normalize in case we just did a lerp:
  3683. if ( s === 1 - t ) {
  3684. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3685. x0 *= f;
  3686. y0 *= f;
  3687. z0 *= f;
  3688. w0 *= f;
  3689. }
  3690. }
  3691. dst[ dstOffset ] = x0;
  3692. dst[ dstOffset + 1 ] = y0;
  3693. dst[ dstOffset + 2 ] = z0;
  3694. dst[ dstOffset + 3 ] = w0;
  3695. }
  3696. /**
  3697. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3698. * in flat arrays.
  3699. *
  3700. * @param {Array<number>} dst - The destination array.
  3701. * @param {number} dstOffset - An offset into the destination array.
  3702. * @param {Array<number>} src0 - The source array of the first quaternion.
  3703. * @param {number} srcOffset0 - An offset into the first source array.
  3704. * @param {Array<number>} src1 - The source array of the second quaternion.
  3705. * @param {number} srcOffset1 - An offset into the second source array.
  3706. * @return {Array<number>} The destination array.
  3707. * @see {@link Quaternion#multiplyQuaternions}.
  3708. */
  3709. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3710. const x0 = src0[ srcOffset0 ];
  3711. const y0 = src0[ srcOffset0 + 1 ];
  3712. const z0 = src0[ srcOffset0 + 2 ];
  3713. const w0 = src0[ srcOffset0 + 3 ];
  3714. const x1 = src1[ srcOffset1 ];
  3715. const y1 = src1[ srcOffset1 + 1 ];
  3716. const z1 = src1[ srcOffset1 + 2 ];
  3717. const w1 = src1[ srcOffset1 + 3 ];
  3718. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3719. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3720. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3721. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3722. return dst;
  3723. }
  3724. /**
  3725. * The x value of this quaternion.
  3726. *
  3727. * @type {number}
  3728. * @default 0
  3729. */
  3730. get x() {
  3731. return this._x;
  3732. }
  3733. set x( value ) {
  3734. this._x = value;
  3735. this._onChangeCallback();
  3736. }
  3737. /**
  3738. * The y value of this quaternion.
  3739. *
  3740. * @type {number}
  3741. * @default 0
  3742. */
  3743. get y() {
  3744. return this._y;
  3745. }
  3746. set y( value ) {
  3747. this._y = value;
  3748. this._onChangeCallback();
  3749. }
  3750. /**
  3751. * The z value of this quaternion.
  3752. *
  3753. * @type {number}
  3754. * @default 0
  3755. */
  3756. get z() {
  3757. return this._z;
  3758. }
  3759. set z( value ) {
  3760. this._z = value;
  3761. this._onChangeCallback();
  3762. }
  3763. /**
  3764. * The w value of this quaternion.
  3765. *
  3766. * @type {number}
  3767. * @default 1
  3768. */
  3769. get w() {
  3770. return this._w;
  3771. }
  3772. set w( value ) {
  3773. this._w = value;
  3774. this._onChangeCallback();
  3775. }
  3776. /**
  3777. * Sets the quaternion components.
  3778. *
  3779. * @param {number} x - The x value of this quaternion.
  3780. * @param {number} y - The y value of this quaternion.
  3781. * @param {number} z - The z value of this quaternion.
  3782. * @param {number} w - The w value of this quaternion.
  3783. * @return {Quaternion} A reference to this quaternion.
  3784. */
  3785. set( x, y, z, w ) {
  3786. this._x = x;
  3787. this._y = y;
  3788. this._z = z;
  3789. this._w = w;
  3790. this._onChangeCallback();
  3791. return this;
  3792. }
  3793. /**
  3794. * Returns a new quaternion with copied values from this instance.
  3795. *
  3796. * @return {Quaternion} A clone of this instance.
  3797. */
  3798. clone() {
  3799. return new this.constructor( this._x, this._y, this._z, this._w );
  3800. }
  3801. /**
  3802. * Copies the values of the given quaternion to this instance.
  3803. *
  3804. * @param {Quaternion} quaternion - The quaternion to copy.
  3805. * @return {Quaternion} A reference to this quaternion.
  3806. */
  3807. copy( quaternion ) {
  3808. this._x = quaternion.x;
  3809. this._y = quaternion.y;
  3810. this._z = quaternion.z;
  3811. this._w = quaternion.w;
  3812. this._onChangeCallback();
  3813. return this;
  3814. }
  3815. /**
  3816. * Sets this quaternion from the rotation specified by the given
  3817. * Euler angles.
  3818. *
  3819. * @param {Euler} euler - The Euler angles.
  3820. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3821. * @return {Quaternion} A reference to this quaternion.
  3822. */
  3823. setFromEuler( euler, update = true ) {
  3824. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3825. // http://www.mathworks.com/matlabcentral/fileexchange/
  3826. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3827. // content/SpinCalc.m
  3828. const cos = Math.cos;
  3829. const sin = Math.sin;
  3830. const c1 = cos( x / 2 );
  3831. const c2 = cos( y / 2 );
  3832. const c3 = cos( z / 2 );
  3833. const s1 = sin( x / 2 );
  3834. const s2 = sin( y / 2 );
  3835. const s3 = sin( z / 2 );
  3836. switch ( order ) {
  3837. case 'XYZ':
  3838. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3839. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3840. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3841. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3842. break;
  3843. case 'YXZ':
  3844. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3845. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3846. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3847. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3848. break;
  3849. case 'ZXY':
  3850. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3851. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3852. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3853. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3854. break;
  3855. case 'ZYX':
  3856. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3857. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3858. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3859. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3860. break;
  3861. case 'YZX':
  3862. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3863. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3864. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3865. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3866. break;
  3867. case 'XZY':
  3868. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3869. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3870. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3871. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3872. break;
  3873. default:
  3874. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3875. }
  3876. if ( update === true ) this._onChangeCallback();
  3877. return this;
  3878. }
  3879. /**
  3880. * Sets this quaternion from the given axis and angle.
  3881. *
  3882. * @param {Vector3} axis - The normalized axis.
  3883. * @param {number} angle - The angle in radians.
  3884. * @return {Quaternion} A reference to this quaternion.
  3885. */
  3886. setFromAxisAngle( axis, angle ) {
  3887. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3888. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3889. this._x = axis.x * s;
  3890. this._y = axis.y * s;
  3891. this._z = axis.z * s;
  3892. this._w = Math.cos( halfAngle );
  3893. this._onChangeCallback();
  3894. return this;
  3895. }
  3896. /**
  3897. * Sets this quaternion from the given rotation matrix.
  3898. *
  3899. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3900. * @return {Quaternion} A reference to this quaternion.
  3901. */
  3902. setFromRotationMatrix( m ) {
  3903. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3904. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3905. const te = m.elements,
  3906. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3907. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3908. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3909. trace = m11 + m22 + m33;
  3910. if ( trace > 0 ) {
  3911. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3912. this._w = 0.25 / s;
  3913. this._x = ( m32 - m23 ) * s;
  3914. this._y = ( m13 - m31 ) * s;
  3915. this._z = ( m21 - m12 ) * s;
  3916. } else if ( m11 > m22 && m11 > m33 ) {
  3917. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3918. this._w = ( m32 - m23 ) / s;
  3919. this._x = 0.25 * s;
  3920. this._y = ( m12 + m21 ) / s;
  3921. this._z = ( m13 + m31 ) / s;
  3922. } else if ( m22 > m33 ) {
  3923. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3924. this._w = ( m13 - m31 ) / s;
  3925. this._x = ( m12 + m21 ) / s;
  3926. this._y = 0.25 * s;
  3927. this._z = ( m23 + m32 ) / s;
  3928. } else {
  3929. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3930. this._w = ( m21 - m12 ) / s;
  3931. this._x = ( m13 + m31 ) / s;
  3932. this._y = ( m23 + m32 ) / s;
  3933. this._z = 0.25 * s;
  3934. }
  3935. this._onChangeCallback();
  3936. return this;
  3937. }
  3938. /**
  3939. * Sets this quaternion to the rotation required to rotate the direction vector
  3940. * `vFrom` to the direction vector `vTo`.
  3941. *
  3942. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3943. * @param {Vector3} vTo - The second (normalized) direction vector.
  3944. * @return {Quaternion} A reference to this quaternion.
  3945. */
  3946. setFromUnitVectors( vFrom, vTo ) {
  3947. // assumes direction vectors vFrom and vTo are normalized
  3948. let r = vFrom.dot( vTo ) + 1;
  3949. if ( r < Number.EPSILON ) {
  3950. // vFrom and vTo point in opposite directions
  3951. r = 0;
  3952. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3953. this._x = - vFrom.y;
  3954. this._y = vFrom.x;
  3955. this._z = 0;
  3956. this._w = r;
  3957. } else {
  3958. this._x = 0;
  3959. this._y = - vFrom.z;
  3960. this._z = vFrom.y;
  3961. this._w = r;
  3962. }
  3963. } else {
  3964. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3965. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3966. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3967. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3968. this._w = r;
  3969. }
  3970. return this.normalize();
  3971. }
  3972. /**
  3973. * Returns the angle between this quaternion and the given one in radians.
  3974. *
  3975. * @param {Quaternion} q - The quaternion to compute the angle with.
  3976. * @return {number} The angle in radians.
  3977. */
  3978. angleTo( q ) {
  3979. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3980. }
  3981. /**
  3982. * Rotates this quaternion by a given angular step to the given quaterion.
  3983. * The method ensures that the final quaternion will not overshoot `q`.
  3984. *
  3985. * @param {Quaternion} q - The target quaternion.
  3986. * @param {number} step - The angular step in radians.
  3987. * @return {Quaternion} A reference to this quaternion.
  3988. */
  3989. rotateTowards( q, step ) {
  3990. const angle = this.angleTo( q );
  3991. if ( angle === 0 ) return this;
  3992. const t = Math.min( 1, step / angle );
  3993. this.slerp( q, t );
  3994. return this;
  3995. }
  3996. /**
  3997. * Sets this quaternion to the identity quaternion; that is, to the
  3998. * quaternion that represents "no rotation".
  3999. *
  4000. * @return {Quaternion} A reference to this quaternion.
  4001. */
  4002. identity() {
  4003. return this.set( 0, 0, 0, 1 );
  4004. }
  4005. /**
  4006. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  4007. * quaternion is assumed to have unit length.
  4008. *
  4009. * @return {Quaternion} A reference to this quaternion.
  4010. */
  4011. invert() {
  4012. return this.conjugate();
  4013. }
  4014. /**
  4015. * Returns the rotational conjugate of this quaternion. The conjugate of a
  4016. * quaternion represents the same rotation in the opposite direction about
  4017. * the rotational axis.
  4018. *
  4019. * @return {Quaternion} A reference to this quaternion.
  4020. */
  4021. conjugate() {
  4022. this._x *= -1;
  4023. this._y *= -1;
  4024. this._z *= -1;
  4025. this._onChangeCallback();
  4026. return this;
  4027. }
  4028. /**
  4029. * Calculates the dot product of this quaternion and the given one.
  4030. *
  4031. * @param {Quaternion} v - The quaternion to compute the dot product with.
  4032. * @return {number} The result of the dot product.
  4033. */
  4034. dot( v ) {
  4035. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  4036. }
  4037. /**
  4038. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  4039. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  4040. * lengths of two quaternions, as this is a slightly more efficient calculation than
  4041. * {@link Quaternion#length}.
  4042. *
  4043. * @return {number} The squared Euclidean length.
  4044. */
  4045. lengthSq() {
  4046. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  4047. }
  4048. /**
  4049. * Computes the Euclidean length (straight-line length) of this quaternion,
  4050. * considered as a 4 dimensional vector.
  4051. *
  4052. * @return {number} The Euclidean length.
  4053. */
  4054. length() {
  4055. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  4056. }
  4057. /**
  4058. * Normalizes this quaternion - that is, calculated the quaternion that performs
  4059. * the same rotation as this one, but has a length equal to `1`.
  4060. *
  4061. * @return {Quaternion} A reference to this quaternion.
  4062. */
  4063. normalize() {
  4064. let l = this.length();
  4065. if ( l === 0 ) {
  4066. this._x = 0;
  4067. this._y = 0;
  4068. this._z = 0;
  4069. this._w = 1;
  4070. } else {
  4071. l = 1 / l;
  4072. this._x = this._x * l;
  4073. this._y = this._y * l;
  4074. this._z = this._z * l;
  4075. this._w = this._w * l;
  4076. }
  4077. this._onChangeCallback();
  4078. return this;
  4079. }
  4080. /**
  4081. * Multiplies this quaternion by the given one.
  4082. *
  4083. * @param {Quaternion} q - The quaternion.
  4084. * @return {Quaternion} A reference to this quaternion.
  4085. */
  4086. multiply( q ) {
  4087. return this.multiplyQuaternions( this, q );
  4088. }
  4089. /**
  4090. * Pre-multiplies this quaternion by the given one.
  4091. *
  4092. * @param {Quaternion} q - The quaternion.
  4093. * @return {Quaternion} A reference to this quaternion.
  4094. */
  4095. premultiply( q ) {
  4096. return this.multiplyQuaternions( q, this );
  4097. }
  4098. /**
  4099. * Multiplies the given quaternions and stores the result in this instance.
  4100. *
  4101. * @param {Quaternion} a - The first quaternion.
  4102. * @param {Quaternion} b - The second quaternion.
  4103. * @return {Quaternion} A reference to this quaternion.
  4104. */
  4105. multiplyQuaternions( a, b ) {
  4106. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  4107. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  4108. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  4109. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  4110. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  4111. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  4112. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  4113. this._onChangeCallback();
  4114. return this;
  4115. }
  4116. /**
  4117. * Performs a spherical linear interpolation between quaternions.
  4118. *
  4119. * @param {Quaternion} qb - The target quaternion.
  4120. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4121. * @return {Quaternion} A reference to this quaternion.
  4122. */
  4123. slerp( qb, t ) {
  4124. if ( t === 0 ) return this;
  4125. if ( t === 1 ) return this.copy( qb );
  4126. const x = this._x, y = this._y, z = this._z, w = this._w;
  4127. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  4128. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  4129. if ( cosHalfTheta < 0 ) {
  4130. this._w = - qb._w;
  4131. this._x = - qb._x;
  4132. this._y = - qb._y;
  4133. this._z = - qb._z;
  4134. cosHalfTheta = - cosHalfTheta;
  4135. } else {
  4136. this.copy( qb );
  4137. }
  4138. if ( cosHalfTheta >= 1.0 ) {
  4139. this._w = w;
  4140. this._x = x;
  4141. this._y = y;
  4142. this._z = z;
  4143. return this;
  4144. }
  4145. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  4146. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  4147. const s = 1 - t;
  4148. this._w = s * w + t * this._w;
  4149. this._x = s * x + t * this._x;
  4150. this._y = s * y + t * this._y;
  4151. this._z = s * z + t * this._z;
  4152. this.normalize(); // normalize calls _onChangeCallback()
  4153. return this;
  4154. }
  4155. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  4156. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  4157. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  4158. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  4159. this._w = ( w * ratioA + this._w * ratioB );
  4160. this._x = ( x * ratioA + this._x * ratioB );
  4161. this._y = ( y * ratioA + this._y * ratioB );
  4162. this._z = ( z * ratioA + this._z * ratioB );
  4163. this._onChangeCallback();
  4164. return this;
  4165. }
  4166. /**
  4167. * Performs a spherical linear interpolation between the given quaternions
  4168. * and stores the result in this quaternion.
  4169. *
  4170. * @param {Quaternion} qa - The source quaternion.
  4171. * @param {Quaternion} qb - The target quaternion.
  4172. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4173. * @return {Quaternion} A reference to this quaternion.
  4174. */
  4175. slerpQuaternions( qa, qb, t ) {
  4176. return this.copy( qa ).slerp( qb, t );
  4177. }
  4178. /**
  4179. * Sets this quaternion to a uniformly random, normalized quaternion.
  4180. *
  4181. * @return {Quaternion} A reference to this quaternion.
  4182. */
  4183. random() {
  4184. // Ken Shoemake
  4185. // Uniform random rotations
  4186. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  4187. const theta1 = 2 * Math.PI * Math.random();
  4188. const theta2 = 2 * Math.PI * Math.random();
  4189. const x0 = Math.random();
  4190. const r1 = Math.sqrt( 1 - x0 );
  4191. const r2 = Math.sqrt( x0 );
  4192. return this.set(
  4193. r1 * Math.sin( theta1 ),
  4194. r1 * Math.cos( theta1 ),
  4195. r2 * Math.sin( theta2 ),
  4196. r2 * Math.cos( theta2 ),
  4197. );
  4198. }
  4199. /**
  4200. * Returns `true` if this quaternion is equal with the given one.
  4201. *
  4202. * @param {Quaternion} quaternion - The quaternion to test for equality.
  4203. * @return {boolean} Whether this quaternion is equal with the given one.
  4204. */
  4205. equals( quaternion ) {
  4206. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  4207. }
  4208. /**
  4209. * Sets this quaternion's components from the given array.
  4210. *
  4211. * @param {Array<number>} array - An array holding the quaternion component values.
  4212. * @param {number} [offset=0] - The offset into the array.
  4213. * @return {Quaternion} A reference to this quaternion.
  4214. */
  4215. fromArray( array, offset = 0 ) {
  4216. this._x = array[ offset ];
  4217. this._y = array[ offset + 1 ];
  4218. this._z = array[ offset + 2 ];
  4219. this._w = array[ offset + 3 ];
  4220. this._onChangeCallback();
  4221. return this;
  4222. }
  4223. /**
  4224. * Writes the components of this quaternion to the given array. If no array is provided,
  4225. * the method returns a new instance.
  4226. *
  4227. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  4228. * @param {number} [offset=0] - Index of the first element in the array.
  4229. * @return {Array<number>} The quaternion components.
  4230. */
  4231. toArray( array = [], offset = 0 ) {
  4232. array[ offset ] = this._x;
  4233. array[ offset + 1 ] = this._y;
  4234. array[ offset + 2 ] = this._z;
  4235. array[ offset + 3 ] = this._w;
  4236. return array;
  4237. }
  4238. /**
  4239. * Sets the components of this quaternion from the given buffer attribute.
  4240. *
  4241. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  4242. * @param {number} index - The index into the attribute.
  4243. * @return {Quaternion} A reference to this quaternion.
  4244. */
  4245. fromBufferAttribute( attribute, index ) {
  4246. this._x = attribute.getX( index );
  4247. this._y = attribute.getY( index );
  4248. this._z = attribute.getZ( index );
  4249. this._w = attribute.getW( index );
  4250. this._onChangeCallback();
  4251. return this;
  4252. }
  4253. /**
  4254. * This methods defines the serialization result of this class. Returns the
  4255. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  4256. *
  4257. * @return {Array<number>} The serialized quaternion.
  4258. */
  4259. toJSON() {
  4260. return this.toArray();
  4261. }
  4262. _onChange( callback ) {
  4263. this._onChangeCallback = callback;
  4264. return this;
  4265. }
  4266. _onChangeCallback() {}
  4267. *[ Symbol.iterator ]() {
  4268. yield this._x;
  4269. yield this._y;
  4270. yield this._z;
  4271. yield this._w;
  4272. }
  4273. }
  4274. /**
  4275. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  4276. * (labeled x, y and z), which can be used to represent a number of things, such as:
  4277. *
  4278. * - A point in 3D space.
  4279. * - A direction and length in 3D space. In three.js the length will
  4280. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  4281. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  4282. * - Any arbitrary ordered triplet of numbers.
  4283. *
  4284. * There are other things a 3D vector can be used to represent, such as
  4285. * momentum vectors and so on, however these are the most
  4286. * common uses in three.js.
  4287. *
  4288. * Iterating through a vector instance will yield its components `(x, y, z)` in
  4289. * the corresponding order.
  4290. * ```js
  4291. * const a = new THREE.Vector3( 0, 1, 0 );
  4292. *
  4293. * //no arguments; will be initialised to (0, 0, 0)
  4294. * const b = new THREE.Vector3( );
  4295. *
  4296. * const d = a.distanceTo( b );
  4297. * ```
  4298. */
  4299. class Vector3 {
  4300. /**
  4301. * Constructs a new 3D vector.
  4302. *
  4303. * @param {number} [x=0] - The x value of this vector.
  4304. * @param {number} [y=0] - The y value of this vector.
  4305. * @param {number} [z=0] - The z value of this vector.
  4306. */
  4307. constructor( x = 0, y = 0, z = 0 ) {
  4308. /**
  4309. * This flag can be used for type testing.
  4310. *
  4311. * @type {boolean}
  4312. * @readonly
  4313. * @default true
  4314. */
  4315. Vector3.prototype.isVector3 = true;
  4316. /**
  4317. * The x value of this vector.
  4318. *
  4319. * @type {number}
  4320. */
  4321. this.x = x;
  4322. /**
  4323. * The y value of this vector.
  4324. *
  4325. * @type {number}
  4326. */
  4327. this.y = y;
  4328. /**
  4329. * The z value of this vector.
  4330. *
  4331. * @type {number}
  4332. */
  4333. this.z = z;
  4334. }
  4335. /**
  4336. * Sets the vector components.
  4337. *
  4338. * @param {number} x - The value of the x component.
  4339. * @param {number} y - The value of the y component.
  4340. * @param {number} z - The value of the z component.
  4341. * @return {Vector3} A reference to this vector.
  4342. */
  4343. set( x, y, z ) {
  4344. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  4345. this.x = x;
  4346. this.y = y;
  4347. this.z = z;
  4348. return this;
  4349. }
  4350. /**
  4351. * Sets the vector components to the same value.
  4352. *
  4353. * @param {number} scalar - The value to set for all vector components.
  4354. * @return {Vector3} A reference to this vector.
  4355. */
  4356. setScalar( scalar ) {
  4357. this.x = scalar;
  4358. this.y = scalar;
  4359. this.z = scalar;
  4360. return this;
  4361. }
  4362. /**
  4363. * Sets the vector's x component to the given value
  4364. *
  4365. * @param {number} x - The value to set.
  4366. * @return {Vector3} A reference to this vector.
  4367. */
  4368. setX( x ) {
  4369. this.x = x;
  4370. return this;
  4371. }
  4372. /**
  4373. * Sets the vector's y component to the given value
  4374. *
  4375. * @param {number} y - The value to set.
  4376. * @return {Vector3} A reference to this vector.
  4377. */
  4378. setY( y ) {
  4379. this.y = y;
  4380. return this;
  4381. }
  4382. /**
  4383. * Sets the vector's z component to the given value
  4384. *
  4385. * @param {number} z - The value to set.
  4386. * @return {Vector3} A reference to this vector.
  4387. */
  4388. setZ( z ) {
  4389. this.z = z;
  4390. return this;
  4391. }
  4392. /**
  4393. * Allows to set a vector component with an index.
  4394. *
  4395. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4396. * @param {number} value - The value to set.
  4397. * @return {Vector3} A reference to this vector.
  4398. */
  4399. setComponent( index, value ) {
  4400. switch ( index ) {
  4401. case 0: this.x = value; break;
  4402. case 1: this.y = value; break;
  4403. case 2: this.z = value; break;
  4404. default: throw new Error( 'index is out of range: ' + index );
  4405. }
  4406. return this;
  4407. }
  4408. /**
  4409. * Returns the value of the vector component which matches the given index.
  4410. *
  4411. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4412. * @return {number} A vector component value.
  4413. */
  4414. getComponent( index ) {
  4415. switch ( index ) {
  4416. case 0: return this.x;
  4417. case 1: return this.y;
  4418. case 2: return this.z;
  4419. default: throw new Error( 'index is out of range: ' + index );
  4420. }
  4421. }
  4422. /**
  4423. * Returns a new vector with copied values from this instance.
  4424. *
  4425. * @return {Vector3} A clone of this instance.
  4426. */
  4427. clone() {
  4428. return new this.constructor( this.x, this.y, this.z );
  4429. }
  4430. /**
  4431. * Copies the values of the given vector to this instance.
  4432. *
  4433. * @param {Vector3} v - The vector to copy.
  4434. * @return {Vector3} A reference to this vector.
  4435. */
  4436. copy( v ) {
  4437. this.x = v.x;
  4438. this.y = v.y;
  4439. this.z = v.z;
  4440. return this;
  4441. }
  4442. /**
  4443. * Adds the given vector to this instance.
  4444. *
  4445. * @param {Vector3} v - The vector to add.
  4446. * @return {Vector3} A reference to this vector.
  4447. */
  4448. add( v ) {
  4449. this.x += v.x;
  4450. this.y += v.y;
  4451. this.z += v.z;
  4452. return this;
  4453. }
  4454. /**
  4455. * Adds the given scalar value to all components of this instance.
  4456. *
  4457. * @param {number} s - The scalar to add.
  4458. * @return {Vector3} A reference to this vector.
  4459. */
  4460. addScalar( s ) {
  4461. this.x += s;
  4462. this.y += s;
  4463. this.z += s;
  4464. return this;
  4465. }
  4466. /**
  4467. * Adds the given vectors and stores the result in this instance.
  4468. *
  4469. * @param {Vector3} a - The first vector.
  4470. * @param {Vector3} b - The second vector.
  4471. * @return {Vector3} A reference to this vector.
  4472. */
  4473. addVectors( a, b ) {
  4474. this.x = a.x + b.x;
  4475. this.y = a.y + b.y;
  4476. this.z = a.z + b.z;
  4477. return this;
  4478. }
  4479. /**
  4480. * Adds the given vector scaled by the given factor to this instance.
  4481. *
  4482. * @param {Vector3} v - The vector.
  4483. * @param {number} s - The factor that scales `v`.
  4484. * @return {Vector3} A reference to this vector.
  4485. */
  4486. addScaledVector( v, s ) {
  4487. this.x += v.x * s;
  4488. this.y += v.y * s;
  4489. this.z += v.z * s;
  4490. return this;
  4491. }
  4492. /**
  4493. * Subtracts the given vector from this instance.
  4494. *
  4495. * @param {Vector3} v - The vector to subtract.
  4496. * @return {Vector3} A reference to this vector.
  4497. */
  4498. sub( v ) {
  4499. this.x -= v.x;
  4500. this.y -= v.y;
  4501. this.z -= v.z;
  4502. return this;
  4503. }
  4504. /**
  4505. * Subtracts the given scalar value from all components of this instance.
  4506. *
  4507. * @param {number} s - The scalar to subtract.
  4508. * @return {Vector3} A reference to this vector.
  4509. */
  4510. subScalar( s ) {
  4511. this.x -= s;
  4512. this.y -= s;
  4513. this.z -= s;
  4514. return this;
  4515. }
  4516. /**
  4517. * Subtracts the given vectors and stores the result in this instance.
  4518. *
  4519. * @param {Vector3} a - The first vector.
  4520. * @param {Vector3} b - The second vector.
  4521. * @return {Vector3} A reference to this vector.
  4522. */
  4523. subVectors( a, b ) {
  4524. this.x = a.x - b.x;
  4525. this.y = a.y - b.y;
  4526. this.z = a.z - b.z;
  4527. return this;
  4528. }
  4529. /**
  4530. * Multiplies the given vector with this instance.
  4531. *
  4532. * @param {Vector3} v - The vector to multiply.
  4533. * @return {Vector3} A reference to this vector.
  4534. */
  4535. multiply( v ) {
  4536. this.x *= v.x;
  4537. this.y *= v.y;
  4538. this.z *= v.z;
  4539. return this;
  4540. }
  4541. /**
  4542. * Multiplies the given scalar value with all components of this instance.
  4543. *
  4544. * @param {number} scalar - The scalar to multiply.
  4545. * @return {Vector3} A reference to this vector.
  4546. */
  4547. multiplyScalar( scalar ) {
  4548. this.x *= scalar;
  4549. this.y *= scalar;
  4550. this.z *= scalar;
  4551. return this;
  4552. }
  4553. /**
  4554. * Multiplies the given vectors and stores the result in this instance.
  4555. *
  4556. * @param {Vector3} a - The first vector.
  4557. * @param {Vector3} b - The second vector.
  4558. * @return {Vector3} A reference to this vector.
  4559. */
  4560. multiplyVectors( a, b ) {
  4561. this.x = a.x * b.x;
  4562. this.y = a.y * b.y;
  4563. this.z = a.z * b.z;
  4564. return this;
  4565. }
  4566. /**
  4567. * Applies the given Euler rotation to this vector.
  4568. *
  4569. * @param {Euler} euler - The Euler angles.
  4570. * @return {Vector3} A reference to this vector.
  4571. */
  4572. applyEuler( euler ) {
  4573. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  4574. }
  4575. /**
  4576. * Applies a rotation specified by an axis and an angle to this vector.
  4577. *
  4578. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4579. * @param {number} angle - The angle in radians.
  4580. * @return {Vector3} A reference to this vector.
  4581. */
  4582. applyAxisAngle( axis, angle ) {
  4583. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  4584. }
  4585. /**
  4586. * Multiplies this vector with the given 3x3 matrix.
  4587. *
  4588. * @param {Matrix3} m - The 3x3 matrix.
  4589. * @return {Vector3} A reference to this vector.
  4590. */
  4591. applyMatrix3( m ) {
  4592. const x = this.x, y = this.y, z = this.z;
  4593. const e = m.elements;
  4594. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4595. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4596. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4597. return this;
  4598. }
  4599. /**
  4600. * Multiplies this vector by the given normal matrix and normalizes
  4601. * the result.
  4602. *
  4603. * @param {Matrix3} m - The normal matrix.
  4604. * @return {Vector3} A reference to this vector.
  4605. */
  4606. applyNormalMatrix( m ) {
  4607. return this.applyMatrix3( m ).normalize();
  4608. }
  4609. /**
  4610. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4611. * divides by perspective.
  4612. *
  4613. * @param {Matrix4} m - The matrix to apply.
  4614. * @return {Vector3} A reference to this vector.
  4615. */
  4616. applyMatrix4( m ) {
  4617. const x = this.x, y = this.y, z = this.z;
  4618. const e = m.elements;
  4619. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4620. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4621. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4622. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4623. return this;
  4624. }
  4625. /**
  4626. * Applies the given Quaternion to this vector.
  4627. *
  4628. * @param {Quaternion} q - The Quaternion.
  4629. * @return {Vector3} A reference to this vector.
  4630. */
  4631. applyQuaternion( q ) {
  4632. // quaternion q is assumed to have unit length
  4633. const vx = this.x, vy = this.y, vz = this.z;
  4634. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4635. // t = 2 * cross( q.xyz, v );
  4636. const tx = 2 * ( qy * vz - qz * vy );
  4637. const ty = 2 * ( qz * vx - qx * vz );
  4638. const tz = 2 * ( qx * vy - qy * vx );
  4639. // v + q.w * t + cross( q.xyz, t );
  4640. this.x = vx + qw * tx + qy * tz - qz * ty;
  4641. this.y = vy + qw * ty + qz * tx - qx * tz;
  4642. this.z = vz + qw * tz + qx * ty - qy * tx;
  4643. return this;
  4644. }
  4645. /**
  4646. * Projects this vector from world space into the camera's normalized
  4647. * device coordinate (NDC) space.
  4648. *
  4649. * @param {Camera} camera - The camera.
  4650. * @return {Vector3} A reference to this vector.
  4651. */
  4652. project( camera ) {
  4653. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4654. }
  4655. /**
  4656. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4657. * space into world space.
  4658. *
  4659. * @param {Camera} camera - The camera.
  4660. * @return {Vector3} A reference to this vector.
  4661. */
  4662. unproject( camera ) {
  4663. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4664. }
  4665. /**
  4666. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4667. * subset of the given 4x4 matrix and then normalizes the result.
  4668. *
  4669. * @param {Matrix4} m - The matrix.
  4670. * @return {Vector3} A reference to this vector.
  4671. */
  4672. transformDirection( m ) {
  4673. // input: THREE.Matrix4 affine matrix
  4674. // vector interpreted as a direction
  4675. const x = this.x, y = this.y, z = this.z;
  4676. const e = m.elements;
  4677. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4678. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4679. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4680. return this.normalize();
  4681. }
  4682. /**
  4683. * Divides this instance by the given vector.
  4684. *
  4685. * @param {Vector3} v - The vector to divide.
  4686. * @return {Vector3} A reference to this vector.
  4687. */
  4688. divide( v ) {
  4689. this.x /= v.x;
  4690. this.y /= v.y;
  4691. this.z /= v.z;
  4692. return this;
  4693. }
  4694. /**
  4695. * Divides this vector by the given scalar.
  4696. *
  4697. * @param {number} scalar - The scalar to divide.
  4698. * @return {Vector3} A reference to this vector.
  4699. */
  4700. divideScalar( scalar ) {
  4701. return this.multiplyScalar( 1 / scalar );
  4702. }
  4703. /**
  4704. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4705. * value, replace that value with the corresponding min value.
  4706. *
  4707. * @param {Vector3} v - The vector.
  4708. * @return {Vector3} A reference to this vector.
  4709. */
  4710. min( v ) {
  4711. this.x = Math.min( this.x, v.x );
  4712. this.y = Math.min( this.y, v.y );
  4713. this.z = Math.min( this.z, v.z );
  4714. return this;
  4715. }
  4716. /**
  4717. * If this vector's x, y or z value is less than the given vector's x, y or z
  4718. * value, replace that value with the corresponding max value.
  4719. *
  4720. * @param {Vector3} v - The vector.
  4721. * @return {Vector3} A reference to this vector.
  4722. */
  4723. max( v ) {
  4724. this.x = Math.max( this.x, v.x );
  4725. this.y = Math.max( this.y, v.y );
  4726. this.z = Math.max( this.z, v.z );
  4727. return this;
  4728. }
  4729. /**
  4730. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4731. * value, it is replaced by the corresponding value.
  4732. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4733. * it is replaced by the corresponding value.
  4734. *
  4735. * @param {Vector3} min - The minimum x, y and z values.
  4736. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4737. * @return {Vector3} A reference to this vector.
  4738. */
  4739. clamp( min, max ) {
  4740. // assumes min < max, componentwise
  4741. this.x = clamp( this.x, min.x, max.x );
  4742. this.y = clamp( this.y, min.y, max.y );
  4743. this.z = clamp( this.z, min.z, max.z );
  4744. return this;
  4745. }
  4746. /**
  4747. * If this vector's x, y or z values are greater than the max value, they are
  4748. * replaced by the max value.
  4749. * If this vector's x, y or z values are less than the min value, they are
  4750. * replaced by the min value.
  4751. *
  4752. * @param {number} minVal - The minimum value the components will be clamped to.
  4753. * @param {number} maxVal - The maximum value the components will be clamped to.
  4754. * @return {Vector3} A reference to this vector.
  4755. */
  4756. clampScalar( minVal, maxVal ) {
  4757. this.x = clamp( this.x, minVal, maxVal );
  4758. this.y = clamp( this.y, minVal, maxVal );
  4759. this.z = clamp( this.z, minVal, maxVal );
  4760. return this;
  4761. }
  4762. /**
  4763. * If this vector's length is greater than the max value, it is replaced by
  4764. * the max value.
  4765. * If this vector's length is less than the min value, it is replaced by the
  4766. * min value.
  4767. *
  4768. * @param {number} min - The minimum value the vector length will be clamped to.
  4769. * @param {number} max - The maximum value the vector length will be clamped to.
  4770. * @return {Vector3} A reference to this vector.
  4771. */
  4772. clampLength( min, max ) {
  4773. const length = this.length();
  4774. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4775. }
  4776. /**
  4777. * The components of this vector are rounded down to the nearest integer value.
  4778. *
  4779. * @return {Vector3} A reference to this vector.
  4780. */
  4781. floor() {
  4782. this.x = Math.floor( this.x );
  4783. this.y = Math.floor( this.y );
  4784. this.z = Math.floor( this.z );
  4785. return this;
  4786. }
  4787. /**
  4788. * The components of this vector are rounded up to the nearest integer value.
  4789. *
  4790. * @return {Vector3} A reference to this vector.
  4791. */
  4792. ceil() {
  4793. this.x = Math.ceil( this.x );
  4794. this.y = Math.ceil( this.y );
  4795. this.z = Math.ceil( this.z );
  4796. return this;
  4797. }
  4798. /**
  4799. * The components of this vector are rounded to the nearest integer value
  4800. *
  4801. * @return {Vector3} A reference to this vector.
  4802. */
  4803. round() {
  4804. this.x = Math.round( this.x );
  4805. this.y = Math.round( this.y );
  4806. this.z = Math.round( this.z );
  4807. return this;
  4808. }
  4809. /**
  4810. * The components of this vector are rounded towards zero (up if negative,
  4811. * down if positive) to an integer value.
  4812. *
  4813. * @return {Vector3} A reference to this vector.
  4814. */
  4815. roundToZero() {
  4816. this.x = Math.trunc( this.x );
  4817. this.y = Math.trunc( this.y );
  4818. this.z = Math.trunc( this.z );
  4819. return this;
  4820. }
  4821. /**
  4822. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4823. *
  4824. * @return {Vector3} A reference to this vector.
  4825. */
  4826. negate() {
  4827. this.x = - this.x;
  4828. this.y = - this.y;
  4829. this.z = - this.z;
  4830. return this;
  4831. }
  4832. /**
  4833. * Calculates the dot product of the given vector with this instance.
  4834. *
  4835. * @param {Vector3} v - The vector to compute the dot product with.
  4836. * @return {number} The result of the dot product.
  4837. */
  4838. dot( v ) {
  4839. return this.x * v.x + this.y * v.y + this.z * v.z;
  4840. }
  4841. // TODO lengthSquared?
  4842. /**
  4843. * Computes the square of the Euclidean length (straight-line length) from
  4844. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4845. * compare the length squared instead as it is slightly more efficient to calculate.
  4846. *
  4847. * @return {number} The square length of this vector.
  4848. */
  4849. lengthSq() {
  4850. return this.x * this.x + this.y * this.y + this.z * this.z;
  4851. }
  4852. /**
  4853. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4854. *
  4855. * @return {number} The length of this vector.
  4856. */
  4857. length() {
  4858. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4859. }
  4860. /**
  4861. * Computes the Manhattan length of this vector.
  4862. *
  4863. * @return {number} The length of this vector.
  4864. */
  4865. manhattanLength() {
  4866. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4867. }
  4868. /**
  4869. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4870. * with the same direction as this one, but with a vector length of `1`.
  4871. *
  4872. * @return {Vector3} A reference to this vector.
  4873. */
  4874. normalize() {
  4875. return this.divideScalar( this.length() || 1 );
  4876. }
  4877. /**
  4878. * Sets this vector to a vector with the same direction as this one, but
  4879. * with the specified length.
  4880. *
  4881. * @param {number} length - The new length of this vector.
  4882. * @return {Vector3} A reference to this vector.
  4883. */
  4884. setLength( length ) {
  4885. return this.normalize().multiplyScalar( length );
  4886. }
  4887. /**
  4888. * Linearly interpolates between the given vector and this instance, where
  4889. * alpha is the percent distance along the line - alpha = 0 will be this
  4890. * vector, and alpha = 1 will be the given one.
  4891. *
  4892. * @param {Vector3} v - The vector to interpolate towards.
  4893. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4894. * @return {Vector3} A reference to this vector.
  4895. */
  4896. lerp( v, alpha ) {
  4897. this.x += ( v.x - this.x ) * alpha;
  4898. this.y += ( v.y - this.y ) * alpha;
  4899. this.z += ( v.z - this.z ) * alpha;
  4900. return this;
  4901. }
  4902. /**
  4903. * Linearly interpolates between the given vectors, where alpha is the percent
  4904. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4905. * be the second one. The result is stored in this instance.
  4906. *
  4907. * @param {Vector3} v1 - The first vector.
  4908. * @param {Vector3} v2 - The second vector.
  4909. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4910. * @return {Vector3} A reference to this vector.
  4911. */
  4912. lerpVectors( v1, v2, alpha ) {
  4913. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4914. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4915. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4916. return this;
  4917. }
  4918. /**
  4919. * Calculates the cross product of the given vector with this instance.
  4920. *
  4921. * @param {Vector3} v - The vector to compute the cross product with.
  4922. * @return {Vector3} The result of the cross product.
  4923. */
  4924. cross( v ) {
  4925. return this.crossVectors( this, v );
  4926. }
  4927. /**
  4928. * Calculates the cross product of the given vectors and stores the result
  4929. * in this instance.
  4930. *
  4931. * @param {Vector3} a - The first vector.
  4932. * @param {Vector3} b - The second vector.
  4933. * @return {Vector3} A reference to this vector.
  4934. */
  4935. crossVectors( a, b ) {
  4936. const ax = a.x, ay = a.y, az = a.z;
  4937. const bx = b.x, by = b.y, bz = b.z;
  4938. this.x = ay * bz - az * by;
  4939. this.y = az * bx - ax * bz;
  4940. this.z = ax * by - ay * bx;
  4941. return this;
  4942. }
  4943. /**
  4944. * Projects this vector onto the given one.
  4945. *
  4946. * @param {Vector3} v - The vector to project to.
  4947. * @return {Vector3} A reference to this vector.
  4948. */
  4949. projectOnVector( v ) {
  4950. const denominator = v.lengthSq();
  4951. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4952. const scalar = v.dot( this ) / denominator;
  4953. return this.copy( v ).multiplyScalar( scalar );
  4954. }
  4955. /**
  4956. * Projects this vector onto a plane by subtracting this
  4957. * vector projected onto the plane's normal from this vector.
  4958. *
  4959. * @param {Vector3} planeNormal - The plane normal.
  4960. * @return {Vector3} A reference to this vector.
  4961. */
  4962. projectOnPlane( planeNormal ) {
  4963. _vector$c.copy( this ).projectOnVector( planeNormal );
  4964. return this.sub( _vector$c );
  4965. }
  4966. /**
  4967. * Reflects this vector off a plane orthogonal to the given normal vector.
  4968. *
  4969. * @param {Vector3} normal - The (normalized) normal vector.
  4970. * @return {Vector3} A reference to this vector.
  4971. */
  4972. reflect( normal ) {
  4973. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4974. }
  4975. /**
  4976. * Returns the angle between the given vector and this instance in radians.
  4977. *
  4978. * @param {Vector3} v - The vector to compute the angle with.
  4979. * @return {number} The angle in radians.
  4980. */
  4981. angleTo( v ) {
  4982. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4983. if ( denominator === 0 ) return Math.PI / 2;
  4984. const theta = this.dot( v ) / denominator;
  4985. // clamp, to handle numerical problems
  4986. return Math.acos( clamp( theta, -1, 1 ) );
  4987. }
  4988. /**
  4989. * Computes the distance from the given vector to this instance.
  4990. *
  4991. * @param {Vector3} v - The vector to compute the distance to.
  4992. * @return {number} The distance.
  4993. */
  4994. distanceTo( v ) {
  4995. return Math.sqrt( this.distanceToSquared( v ) );
  4996. }
  4997. /**
  4998. * Computes the squared distance from the given vector to this instance.
  4999. * If you are just comparing the distance with another distance, you should compare
  5000. * the distance squared instead as it is slightly more efficient to calculate.
  5001. *
  5002. * @param {Vector3} v - The vector to compute the squared distance to.
  5003. * @return {number} The squared distance.
  5004. */
  5005. distanceToSquared( v ) {
  5006. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5007. return dx * dx + dy * dy + dz * dz;
  5008. }
  5009. /**
  5010. * Computes the Manhattan distance from the given vector to this instance.
  5011. *
  5012. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  5013. * @return {number} The Manhattan distance.
  5014. */
  5015. manhattanDistanceTo( v ) {
  5016. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5017. }
  5018. /**
  5019. * Sets the vector components from the given spherical coordinates.
  5020. *
  5021. * @param {Spherical} s - The spherical coordinates.
  5022. * @return {Vector3} A reference to this vector.
  5023. */
  5024. setFromSpherical( s ) {
  5025. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  5026. }
  5027. /**
  5028. * Sets the vector components from the given spherical coordinates.
  5029. *
  5030. * @param {number} radius - The radius.
  5031. * @param {number} phi - The phi angle in radians.
  5032. * @param {number} theta - The theta angle in radians.
  5033. * @return {Vector3} A reference to this vector.
  5034. */
  5035. setFromSphericalCoords( radius, phi, theta ) {
  5036. const sinPhiRadius = Math.sin( phi ) * radius;
  5037. this.x = sinPhiRadius * Math.sin( theta );
  5038. this.y = Math.cos( phi ) * radius;
  5039. this.z = sinPhiRadius * Math.cos( theta );
  5040. return this;
  5041. }
  5042. /**
  5043. * Sets the vector components from the given cylindrical coordinates.
  5044. *
  5045. * @param {Cylindrical} c - The cylindrical coordinates.
  5046. * @return {Vector3} A reference to this vector.
  5047. */
  5048. setFromCylindrical( c ) {
  5049. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  5050. }
  5051. /**
  5052. * Sets the vector components from the given cylindrical coordinates.
  5053. *
  5054. * @param {number} radius - The radius.
  5055. * @param {number} theta - The theta angle in radians.
  5056. * @param {number} y - The y value.
  5057. * @return {Vector3} A reference to this vector.
  5058. */
  5059. setFromCylindricalCoords( radius, theta, y ) {
  5060. this.x = radius * Math.sin( theta );
  5061. this.y = y;
  5062. this.z = radius * Math.cos( theta );
  5063. return this;
  5064. }
  5065. /**
  5066. * Sets the vector components to the position elements of the
  5067. * given transformation matrix.
  5068. *
  5069. * @param {Matrix4} m - The 4x4 matrix.
  5070. * @return {Vector3} A reference to this vector.
  5071. */
  5072. setFromMatrixPosition( m ) {
  5073. const e = m.elements;
  5074. this.x = e[ 12 ];
  5075. this.y = e[ 13 ];
  5076. this.z = e[ 14 ];
  5077. return this;
  5078. }
  5079. /**
  5080. * Sets the vector components to the scale elements of the
  5081. * given transformation matrix.
  5082. *
  5083. * @param {Matrix4} m - The 4x4 matrix.
  5084. * @return {Vector3} A reference to this vector.
  5085. */
  5086. setFromMatrixScale( m ) {
  5087. const sx = this.setFromMatrixColumn( m, 0 ).length();
  5088. const sy = this.setFromMatrixColumn( m, 1 ).length();
  5089. const sz = this.setFromMatrixColumn( m, 2 ).length();
  5090. this.x = sx;
  5091. this.y = sy;
  5092. this.z = sz;
  5093. return this;
  5094. }
  5095. /**
  5096. * Sets the vector components from the specified matrix column.
  5097. *
  5098. * @param {Matrix4} m - The 4x4 matrix.
  5099. * @param {number} index - The column index.
  5100. * @return {Vector3} A reference to this vector.
  5101. */
  5102. setFromMatrixColumn( m, index ) {
  5103. return this.fromArray( m.elements, index * 4 );
  5104. }
  5105. /**
  5106. * Sets the vector components from the specified matrix column.
  5107. *
  5108. * @param {Matrix3} m - The 3x3 matrix.
  5109. * @param {number} index - The column index.
  5110. * @return {Vector3} A reference to this vector.
  5111. */
  5112. setFromMatrix3Column( m, index ) {
  5113. return this.fromArray( m.elements, index * 3 );
  5114. }
  5115. /**
  5116. * Sets the vector components from the given Euler angles.
  5117. *
  5118. * @param {Euler} e - The Euler angles to set.
  5119. * @return {Vector3} A reference to this vector.
  5120. */
  5121. setFromEuler( e ) {
  5122. this.x = e._x;
  5123. this.y = e._y;
  5124. this.z = e._z;
  5125. return this;
  5126. }
  5127. /**
  5128. * Sets the vector components from the RGB components of the
  5129. * given color.
  5130. *
  5131. * @param {Color} c - The color to set.
  5132. * @return {Vector3} A reference to this vector.
  5133. */
  5134. setFromColor( c ) {
  5135. this.x = c.r;
  5136. this.y = c.g;
  5137. this.z = c.b;
  5138. return this;
  5139. }
  5140. /**
  5141. * Returns `true` if this vector is equal with the given one.
  5142. *
  5143. * @param {Vector3} v - The vector to test for equality.
  5144. * @return {boolean} Whether this vector is equal with the given one.
  5145. */
  5146. equals( v ) {
  5147. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  5148. }
  5149. /**
  5150. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  5151. * and z value to be `array[ offset + 2 ]`.
  5152. *
  5153. * @param {Array<number>} array - An array holding the vector component values.
  5154. * @param {number} [offset=0] - The offset into the array.
  5155. * @return {Vector3} A reference to this vector.
  5156. */
  5157. fromArray( array, offset = 0 ) {
  5158. this.x = array[ offset ];
  5159. this.y = array[ offset + 1 ];
  5160. this.z = array[ offset + 2 ];
  5161. return this;
  5162. }
  5163. /**
  5164. * Writes the components of this vector to the given array. If no array is provided,
  5165. * the method returns a new instance.
  5166. *
  5167. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  5168. * @param {number} [offset=0] - Index of the first element in the array.
  5169. * @return {Array<number>} The vector components.
  5170. */
  5171. toArray( array = [], offset = 0 ) {
  5172. array[ offset ] = this.x;
  5173. array[ offset + 1 ] = this.y;
  5174. array[ offset + 2 ] = this.z;
  5175. return array;
  5176. }
  5177. /**
  5178. * Sets the components of this vector from the given buffer attribute.
  5179. *
  5180. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  5181. * @param {number} index - The index into the attribute.
  5182. * @return {Vector3} A reference to this vector.
  5183. */
  5184. fromBufferAttribute( attribute, index ) {
  5185. this.x = attribute.getX( index );
  5186. this.y = attribute.getY( index );
  5187. this.z = attribute.getZ( index );
  5188. return this;
  5189. }
  5190. /**
  5191. * Sets each component of this vector to a pseudo-random value between `0` and
  5192. * `1`, excluding `1`.
  5193. *
  5194. * @return {Vector3} A reference to this vector.
  5195. */
  5196. random() {
  5197. this.x = Math.random();
  5198. this.y = Math.random();
  5199. this.z = Math.random();
  5200. return this;
  5201. }
  5202. /**
  5203. * Sets this vector to a uniformly random point on a unit sphere.
  5204. *
  5205. * @return {Vector3} A reference to this vector.
  5206. */
  5207. randomDirection() {
  5208. // https://mathworld.wolfram.com/SpherePointPicking.html
  5209. const theta = Math.random() * Math.PI * 2;
  5210. const u = Math.random() * 2 - 1;
  5211. const c = Math.sqrt( 1 - u * u );
  5212. this.x = c * Math.cos( theta );
  5213. this.y = u;
  5214. this.z = c * Math.sin( theta );
  5215. return this;
  5216. }
  5217. *[ Symbol.iterator ]() {
  5218. yield this.x;
  5219. yield this.y;
  5220. yield this.z;
  5221. }
  5222. }
  5223. const _vector$c = /*@__PURE__*/ new Vector3();
  5224. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  5225. /**
  5226. * Represents an axis-aligned bounding box (AABB) in 3D space.
  5227. */
  5228. class Box3 {
  5229. /**
  5230. * Constructs a new bounding box.
  5231. *
  5232. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  5233. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  5234. */
  5235. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  5236. /**
  5237. * This flag can be used for type testing.
  5238. *
  5239. * @type {boolean}
  5240. * @readonly
  5241. * @default true
  5242. */
  5243. this.isBox3 = true;
  5244. /**
  5245. * The lower boundary of the box.
  5246. *
  5247. * @type {Vector3}
  5248. */
  5249. this.min = min;
  5250. /**
  5251. * The upper boundary of the box.
  5252. *
  5253. * @type {Vector3}
  5254. */
  5255. this.max = max;
  5256. }
  5257. /**
  5258. * Sets the lower and upper boundaries of this box.
  5259. * Please note that this method only copies the values from the given objects.
  5260. *
  5261. * @param {Vector3} min - The lower boundary of the box.
  5262. * @param {Vector3} max - The upper boundary of the box.
  5263. * @return {Box3} A reference to this bounding box.
  5264. */
  5265. set( min, max ) {
  5266. this.min.copy( min );
  5267. this.max.copy( max );
  5268. return this;
  5269. }
  5270. /**
  5271. * Sets the upper and lower bounds of this box so it encloses the position data
  5272. * in the given array.
  5273. *
  5274. * @param {Array<number>} array - An array holding 3D position data.
  5275. * @return {Box3} A reference to this bounding box.
  5276. */
  5277. setFromArray( array ) {
  5278. this.makeEmpty();
  5279. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  5280. this.expandByPoint( _vector$b.fromArray( array, i ) );
  5281. }
  5282. return this;
  5283. }
  5284. /**
  5285. * Sets the upper and lower bounds of this box so it encloses the position data
  5286. * in the given buffer attribute.
  5287. *
  5288. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  5289. * @return {Box3} A reference to this bounding box.
  5290. */
  5291. setFromBufferAttribute( attribute ) {
  5292. this.makeEmpty();
  5293. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  5294. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  5295. }
  5296. return this;
  5297. }
  5298. /**
  5299. * Sets the upper and lower bounds of this box so it encloses the position data
  5300. * in the given array.
  5301. *
  5302. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  5303. * @return {Box3} A reference to this bounding box.
  5304. */
  5305. setFromPoints( points ) {
  5306. this.makeEmpty();
  5307. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5308. this.expandByPoint( points[ i ] );
  5309. }
  5310. return this;
  5311. }
  5312. /**
  5313. * Centers this box on the given center vector and sets this box's width, height and
  5314. * depth to the given size values.
  5315. *
  5316. * @param {Vector3} center - The center of the box.
  5317. * @param {Vector3} size - The x, y and z dimensions of the box.
  5318. * @return {Box3} A reference to this bounding box.
  5319. */
  5320. setFromCenterAndSize( center, size ) {
  5321. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  5322. this.min.copy( center ).sub( halfSize );
  5323. this.max.copy( center ).add( halfSize );
  5324. return this;
  5325. }
  5326. /**
  5327. * Computes the world-axis-aligned bounding box for the given 3D object
  5328. * (including its children), accounting for the object's, and children's,
  5329. * world transforms. The function may result in a larger box than strictly necessary.
  5330. *
  5331. * @param {Object3D} object - The 3D object to compute the bounding box for.
  5332. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  5333. * world-axis-aligned bounding box at the expense of more computation.
  5334. * @return {Box3} A reference to this bounding box.
  5335. */
  5336. setFromObject( object, precise = false ) {
  5337. this.makeEmpty();
  5338. return this.expandByObject( object, precise );
  5339. }
  5340. /**
  5341. * Returns a new box with copied values from this instance.
  5342. *
  5343. * @return {Box3} A clone of this instance.
  5344. */
  5345. clone() {
  5346. return new this.constructor().copy( this );
  5347. }
  5348. /**
  5349. * Copies the values of the given box to this instance.
  5350. *
  5351. * @param {Box3} box - The box to copy.
  5352. * @return {Box3} A reference to this bounding box.
  5353. */
  5354. copy( box ) {
  5355. this.min.copy( box.min );
  5356. this.max.copy( box.max );
  5357. return this;
  5358. }
  5359. /**
  5360. * Makes this box empty which means in encloses a zero space in 3D.
  5361. *
  5362. * @return {Box3} A reference to this bounding box.
  5363. */
  5364. makeEmpty() {
  5365. this.min.x = this.min.y = this.min.z = + Infinity;
  5366. this.max.x = this.max.y = this.max.z = - Infinity;
  5367. return this;
  5368. }
  5369. /**
  5370. * Returns true if this box includes zero points within its bounds.
  5371. * Note that a box with equal lower and upper bounds still includes one
  5372. * point, the one both bounds share.
  5373. *
  5374. * @return {boolean} Whether this box is empty or not.
  5375. */
  5376. isEmpty() {
  5377. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5378. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5379. }
  5380. /**
  5381. * Returns the center point of this box.
  5382. *
  5383. * @param {Vector3} target - The target vector that is used to store the method's result.
  5384. * @return {Vector3} The center point.
  5385. */
  5386. getCenter( target ) {
  5387. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5388. }
  5389. /**
  5390. * Returns the dimensions of this box.
  5391. *
  5392. * @param {Vector3} target - The target vector that is used to store the method's result.
  5393. * @return {Vector3} The size.
  5394. */
  5395. getSize( target ) {
  5396. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  5397. }
  5398. /**
  5399. * Expands the boundaries of this box to include the given point.
  5400. *
  5401. * @param {Vector3} point - The point that should be included by the bounding box.
  5402. * @return {Box3} A reference to this bounding box.
  5403. */
  5404. expandByPoint( point ) {
  5405. this.min.min( point );
  5406. this.max.max( point );
  5407. return this;
  5408. }
  5409. /**
  5410. * Expands this box equilaterally by the given vector. The width of this
  5411. * box will be expanded by the x component of the vector in both
  5412. * directions. The height of this box will be expanded by the y component of
  5413. * the vector in both directions. The depth of this box will be
  5414. * expanded by the z component of the vector in both directions.
  5415. *
  5416. * @param {Vector3} vector - The vector that should expand the bounding box.
  5417. * @return {Box3} A reference to this bounding box.
  5418. */
  5419. expandByVector( vector ) {
  5420. this.min.sub( vector );
  5421. this.max.add( vector );
  5422. return this;
  5423. }
  5424. /**
  5425. * Expands each dimension of the box by the given scalar. If negative, the
  5426. * dimensions of the box will be contracted.
  5427. *
  5428. * @param {number} scalar - The scalar value that should expand the bounding box.
  5429. * @return {Box3} A reference to this bounding box.
  5430. */
  5431. expandByScalar( scalar ) {
  5432. this.min.addScalar( - scalar );
  5433. this.max.addScalar( scalar );
  5434. return this;
  5435. }
  5436. /**
  5437. * Expands the boundaries of this box to include the given 3D object and
  5438. * its children, accounting for the object's, and children's, world
  5439. * transforms. The function may result in a larger box than strictly
  5440. * necessary (unless the precise parameter is set to true).
  5441. *
  5442. * @param {Object3D} object - The 3D object that should expand the bounding box.
  5443. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  5444. * as little as necessary at the expense of more computation.
  5445. * @return {Box3} A reference to this bounding box.
  5446. */
  5447. expandByObject( object, precise = false ) {
  5448. // Computes the world-axis-aligned bounding box of an object (including its children),
  5449. // accounting for both the object's, and children's, world transforms
  5450. object.updateWorldMatrix( false, false );
  5451. const geometry = object.geometry;
  5452. if ( geometry !== undefined ) {
  5453. const positionAttribute = geometry.getAttribute( 'position' );
  5454. // precise AABB computation based on vertex data requires at least a position attribute.
  5455. // instancing isn't supported so far and uses the normal (conservative) code path.
  5456. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  5457. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  5458. if ( object.isMesh === true ) {
  5459. object.getVertexPosition( i, _vector$b );
  5460. } else {
  5461. _vector$b.fromBufferAttribute( positionAttribute, i );
  5462. }
  5463. _vector$b.applyMatrix4( object.matrixWorld );
  5464. this.expandByPoint( _vector$b );
  5465. }
  5466. } else {
  5467. if ( object.boundingBox !== undefined ) {
  5468. // object-level bounding box
  5469. if ( object.boundingBox === null ) {
  5470. object.computeBoundingBox();
  5471. }
  5472. _box$4.copy( object.boundingBox );
  5473. } else {
  5474. // geometry-level bounding box
  5475. if ( geometry.boundingBox === null ) {
  5476. geometry.computeBoundingBox();
  5477. }
  5478. _box$4.copy( geometry.boundingBox );
  5479. }
  5480. _box$4.applyMatrix4( object.matrixWorld );
  5481. this.union( _box$4 );
  5482. }
  5483. }
  5484. const children = object.children;
  5485. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5486. this.expandByObject( children[ i ], precise );
  5487. }
  5488. return this;
  5489. }
  5490. /**
  5491. * Returns `true` if the given point lies within or on the boundaries of this box.
  5492. *
  5493. * @param {Vector3} point - The point to test.
  5494. * @return {boolean} Whether the bounding box contains the given point or not.
  5495. */
  5496. containsPoint( point ) {
  5497. return point.x >= this.min.x && point.x <= this.max.x &&
  5498. point.y >= this.min.y && point.y <= this.max.y &&
  5499. point.z >= this.min.z && point.z <= this.max.z;
  5500. }
  5501. /**
  5502. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  5503. * If this box and the given one are identical, this function also returns `true`.
  5504. *
  5505. * @param {Box3} box - The bounding box to test.
  5506. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  5507. */
  5508. containsBox( box ) {
  5509. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  5510. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  5511. this.min.z <= box.min.z && box.max.z <= this.max.z;
  5512. }
  5513. /**
  5514. * Returns a point as a proportion of this box's width, height and depth.
  5515. *
  5516. * @param {Vector3} point - A point in 3D space.
  5517. * @param {Vector3} target - The target vector that is used to store the method's result.
  5518. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  5519. */
  5520. getParameter( point, target ) {
  5521. // This can potentially have a divide by zero if the box
  5522. // has a size dimension of 0.
  5523. return target.set(
  5524. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5525. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5526. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5527. );
  5528. }
  5529. /**
  5530. * Returns `true` if the given bounding box intersects with this bounding box.
  5531. *
  5532. * @param {Box3} box - The bounding box to test.
  5533. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  5534. */
  5535. intersectsBox( box ) {
  5536. // using 6 splitting planes to rule out intersections.
  5537. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  5538. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  5539. box.max.z >= this.min.z && box.min.z <= this.max.z;
  5540. }
  5541. /**
  5542. * Returns `true` if the given bounding sphere intersects with this bounding box.
  5543. *
  5544. * @param {Sphere} sphere - The bounding sphere to test.
  5545. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  5546. */
  5547. intersectsSphere( sphere ) {
  5548. // Find the point on the AABB closest to the sphere center.
  5549. this.clampPoint( sphere.center, _vector$b );
  5550. // If that point is inside the sphere, the AABB and sphere intersect.
  5551. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5552. }
  5553. /**
  5554. * Returns `true` if the given plane intersects with this bounding box.
  5555. *
  5556. * @param {Plane} plane - The plane to test.
  5557. * @return {boolean} Whether the given plane intersects with this bounding box.
  5558. */
  5559. intersectsPlane( plane ) {
  5560. // We compute the minimum and maximum dot product values. If those values
  5561. // are on the same side (back or front) of the plane, then there is no intersection.
  5562. let min, max;
  5563. if ( plane.normal.x > 0 ) {
  5564. min = plane.normal.x * this.min.x;
  5565. max = plane.normal.x * this.max.x;
  5566. } else {
  5567. min = plane.normal.x * this.max.x;
  5568. max = plane.normal.x * this.min.x;
  5569. }
  5570. if ( plane.normal.y > 0 ) {
  5571. min += plane.normal.y * this.min.y;
  5572. max += plane.normal.y * this.max.y;
  5573. } else {
  5574. min += plane.normal.y * this.max.y;
  5575. max += plane.normal.y * this.min.y;
  5576. }
  5577. if ( plane.normal.z > 0 ) {
  5578. min += plane.normal.z * this.min.z;
  5579. max += plane.normal.z * this.max.z;
  5580. } else {
  5581. min += plane.normal.z * this.max.z;
  5582. max += plane.normal.z * this.min.z;
  5583. }
  5584. return ( min <= - plane.constant && max >= - plane.constant );
  5585. }
  5586. /**
  5587. * Returns `true` if the given triangle intersects with this bounding box.
  5588. *
  5589. * @param {Triangle} triangle - The triangle to test.
  5590. * @return {boolean} Whether the given triangle intersects with this bounding box.
  5591. */
  5592. intersectsTriangle( triangle ) {
  5593. if ( this.isEmpty() ) {
  5594. return false;
  5595. }
  5596. // compute box center and extents
  5597. this.getCenter( _center );
  5598. _extents.subVectors( this.max, _center );
  5599. // translate triangle to aabb origin
  5600. _v0$3.subVectors( triangle.a, _center );
  5601. _v1$7.subVectors( triangle.b, _center );
  5602. _v2$4.subVectors( triangle.c, _center );
  5603. // compute edge vectors for triangle
  5604. _f0.subVectors( _v1$7, _v0$3 );
  5605. _f1.subVectors( _v2$4, _v1$7 );
  5606. _f2.subVectors( _v0$3, _v2$4 );
  5607. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  5608. // 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
  5609. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5610. let axes = [
  5611. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  5612. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  5613. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  5614. ];
  5615. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  5616. return false;
  5617. }
  5618. // test 3 face normals from the aabb
  5619. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  5620. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  5621. return false;
  5622. }
  5623. // finally testing the face normal of the triangle
  5624. // use already existing triangle edge vectors here
  5625. _triangleNormal.crossVectors( _f0, _f1 );
  5626. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  5627. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  5628. }
  5629. /**
  5630. * Clamps the given point within the bounds of this box.
  5631. *
  5632. * @param {Vector3} point - The point to clamp.
  5633. * @param {Vector3} target - The target vector that is used to store the method's result.
  5634. * @return {Vector3} The clamped point.
  5635. */
  5636. clampPoint( point, target ) {
  5637. return target.copy( point ).clamp( this.min, this.max );
  5638. }
  5639. /**
  5640. * Returns the euclidean distance from any edge of this box to the specified point. If
  5641. * the given point lies inside of this box, the distance will be `0`.
  5642. *
  5643. * @param {Vector3} point - The point to compute the distance to.
  5644. * @return {number} The euclidean distance.
  5645. */
  5646. distanceToPoint( point ) {
  5647. return this.clampPoint( point, _vector$b ).distanceTo( point );
  5648. }
  5649. /**
  5650. * Returns a bounding sphere that encloses this bounding box.
  5651. *
  5652. * @param {Sphere} target - The target sphere that is used to store the method's result.
  5653. * @return {Sphere} The bounding sphere that encloses this bounding box.
  5654. */
  5655. getBoundingSphere( target ) {
  5656. if ( this.isEmpty() ) {
  5657. target.makeEmpty();
  5658. } else {
  5659. this.getCenter( target.center );
  5660. target.radius = this.getSize( _vector$b ).length() * 0.5;
  5661. }
  5662. return target;
  5663. }
  5664. /**
  5665. * Computes the intersection of this bounding box and the given one, setting the upper
  5666. * bound of this box to the lesser of the two boxes' upper bounds and the
  5667. * lower bound of this box to the greater of the two boxes' lower bounds. If
  5668. * there's no overlap, makes this box empty.
  5669. *
  5670. * @param {Box3} box - The bounding box to intersect with.
  5671. * @return {Box3} A reference to this bounding box.
  5672. */
  5673. intersect( box ) {
  5674. this.min.max( box.min );
  5675. this.max.min( box.max );
  5676. // 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.
  5677. if ( this.isEmpty() ) this.makeEmpty();
  5678. return this;
  5679. }
  5680. /**
  5681. * Computes the union of this box and another and the given one, setting the upper
  5682. * bound of this box to the greater of the two boxes' upper bounds and the
  5683. * lower bound of this box to the lesser of the two boxes' lower bounds.
  5684. *
  5685. * @param {Box3} box - The bounding box that will be unioned with this instance.
  5686. * @return {Box3} A reference to this bounding box.
  5687. */
  5688. union( box ) {
  5689. this.min.min( box.min );
  5690. this.max.max( box.max );
  5691. return this;
  5692. }
  5693. /**
  5694. * Transforms this bounding box by the given 4x4 transformation matrix.
  5695. *
  5696. * @param {Matrix4} matrix - The transformation matrix.
  5697. * @return {Box3} A reference to this bounding box.
  5698. */
  5699. applyMatrix4( matrix ) {
  5700. // transform of empty box is an empty box.
  5701. if ( this.isEmpty() ) return this;
  5702. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5703. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5704. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5705. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5706. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5707. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5708. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5709. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5710. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5711. this.setFromPoints( _points );
  5712. return this;
  5713. }
  5714. /**
  5715. * Adds the given offset to both the upper and lower bounds of this bounding box,
  5716. * effectively moving it in 3D space.
  5717. *
  5718. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  5719. * @return {Box3} A reference to this bounding box.
  5720. */
  5721. translate( offset ) {
  5722. this.min.add( offset );
  5723. this.max.add( offset );
  5724. return this;
  5725. }
  5726. /**
  5727. * Returns `true` if this bounding box is equal with the given one.
  5728. *
  5729. * @param {Box3} box - The box to test for equality.
  5730. * @return {boolean} Whether this bounding box is equal with the given one.
  5731. */
  5732. equals( box ) {
  5733. return box.min.equals( this.min ) && box.max.equals( this.max );
  5734. }
  5735. }
  5736. const _points = [
  5737. /*@__PURE__*/ new Vector3(),
  5738. /*@__PURE__*/ new Vector3(),
  5739. /*@__PURE__*/ new Vector3(),
  5740. /*@__PURE__*/ new Vector3(),
  5741. /*@__PURE__*/ new Vector3(),
  5742. /*@__PURE__*/ new Vector3(),
  5743. /*@__PURE__*/ new Vector3(),
  5744. /*@__PURE__*/ new Vector3()
  5745. ];
  5746. const _vector$b = /*@__PURE__*/ new Vector3();
  5747. const _box$4 = /*@__PURE__*/ new Box3();
  5748. // triangle centered vertices
  5749. const _v0$3 = /*@__PURE__*/ new Vector3();
  5750. const _v1$7 = /*@__PURE__*/ new Vector3();
  5751. const _v2$4 = /*@__PURE__*/ new Vector3();
  5752. // triangle edge vectors
  5753. const _f0 = /*@__PURE__*/ new Vector3();
  5754. const _f1 = /*@__PURE__*/ new Vector3();
  5755. const _f2 = /*@__PURE__*/ new Vector3();
  5756. const _center = /*@__PURE__*/ new Vector3();
  5757. const _extents = /*@__PURE__*/ new Vector3();
  5758. const _triangleNormal = /*@__PURE__*/ new Vector3();
  5759. const _testAxis = /*@__PURE__*/ new Vector3();
  5760. function satForAxes( axes, v0, v1, v2, extents ) {
  5761. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  5762. _testAxis.fromArray( axes, i );
  5763. // project the aabb onto the separating axis
  5764. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  5765. // project all 3 vertices of the triangle onto the separating axis
  5766. const p0 = v0.dot( _testAxis );
  5767. const p1 = v1.dot( _testAxis );
  5768. const p2 = v2.dot( _testAxis );
  5769. // actual test, basically see if either of the most extreme of the triangle points intersects r
  5770. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  5771. // points of the projected triangle are outside the projected half-length of the aabb
  5772. // the axis is separating and we can exit
  5773. return false;
  5774. }
  5775. }
  5776. return true;
  5777. }
  5778. const _box$3 = /*@__PURE__*/ new Box3();
  5779. const _v1$6 = /*@__PURE__*/ new Vector3();
  5780. const _v2$3 = /*@__PURE__*/ new Vector3();
  5781. /**
  5782. * An analytical 3D sphere defined by a center and radius. This class is mainly
  5783. * used as a Bounding Sphere for 3D objects.
  5784. */
  5785. class Sphere {
  5786. /**
  5787. * Constructs a new sphere.
  5788. *
  5789. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  5790. * @param {number} [radius=-1] - The radius of the sphere.
  5791. */
  5792. constructor( center = new Vector3(), radius = -1 ) {
  5793. /**
  5794. * This flag can be used for type testing.
  5795. *
  5796. * @type {boolean}
  5797. * @readonly
  5798. * @default true
  5799. */
  5800. this.isSphere = true;
  5801. /**
  5802. * The center of the sphere
  5803. *
  5804. * @type {Vector3}
  5805. */
  5806. this.center = center;
  5807. /**
  5808. * The radius of the sphere.
  5809. *
  5810. * @type {number}
  5811. */
  5812. this.radius = radius;
  5813. }
  5814. /**
  5815. * Sets the sphere's components by copying the given values.
  5816. *
  5817. * @param {Vector3} center - The center.
  5818. * @param {number} radius - The radius.
  5819. * @return {Sphere} A reference to this sphere.
  5820. */
  5821. set( center, radius ) {
  5822. this.center.copy( center );
  5823. this.radius = radius;
  5824. return this;
  5825. }
  5826. /**
  5827. * Computes the minimum bounding sphere for list of points.
  5828. * If the optional center point is given, it is used as the sphere's
  5829. * center. Otherwise, the center of the axis-aligned bounding box
  5830. * encompassing the points is calculated.
  5831. *
  5832. * @param {Array<Vector3>} points - A list of points in 3D space.
  5833. * @param {Vector3} [optionalCenter] - The center of the sphere.
  5834. * @return {Sphere} A reference to this sphere.
  5835. */
  5836. setFromPoints( points, optionalCenter ) {
  5837. const center = this.center;
  5838. if ( optionalCenter !== undefined ) {
  5839. center.copy( optionalCenter );
  5840. } else {
  5841. _box$3.setFromPoints( points ).getCenter( center );
  5842. }
  5843. let maxRadiusSq = 0;
  5844. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5845. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5846. }
  5847. this.radius = Math.sqrt( maxRadiusSq );
  5848. return this;
  5849. }
  5850. /**
  5851. * Copies the values of the given sphere to this instance.
  5852. *
  5853. * @param {Sphere} sphere - The sphere to copy.
  5854. * @return {Sphere} A reference to this sphere.
  5855. */
  5856. copy( sphere ) {
  5857. this.center.copy( sphere.center );
  5858. this.radius = sphere.radius;
  5859. return this;
  5860. }
  5861. /**
  5862. * Returns `true` if the sphere is empty (the radius set to a negative number).
  5863. *
  5864. * Spheres with a radius of `0` contain only their center point and are not
  5865. * considered to be empty.
  5866. *
  5867. * @return {boolean} Whether this sphere is empty or not.
  5868. */
  5869. isEmpty() {
  5870. return ( this.radius < 0 );
  5871. }
  5872. /**
  5873. * Makes this sphere empty which means in encloses a zero space in 3D.
  5874. *
  5875. * @return {Sphere} A reference to this sphere.
  5876. */
  5877. makeEmpty() {
  5878. this.center.set( 0, 0, 0 );
  5879. this.radius = -1;
  5880. return this;
  5881. }
  5882. /**
  5883. * Returns `true` if this sphere contains the given point inclusive of
  5884. * the surface of the sphere.
  5885. *
  5886. * @param {Vector3} point - The point to check.
  5887. * @return {boolean} Whether this sphere contains the given point or not.
  5888. */
  5889. containsPoint( point ) {
  5890. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5891. }
  5892. /**
  5893. * Returns the closest distance from the boundary of the sphere to the
  5894. * given point. If the sphere contains the point, the distance will
  5895. * be negative.
  5896. *
  5897. * @param {Vector3} point - The point to compute the distance to.
  5898. * @return {number} The distance to the point.
  5899. */
  5900. distanceToPoint( point ) {
  5901. return ( point.distanceTo( this.center ) - this.radius );
  5902. }
  5903. /**
  5904. * Returns `true` if this sphere intersects with the given one.
  5905. *
  5906. * @param {Sphere} sphere - The sphere to test.
  5907. * @return {boolean} Whether this sphere intersects with the given one or not.
  5908. */
  5909. intersectsSphere( sphere ) {
  5910. const radiusSum = this.radius + sphere.radius;
  5911. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5912. }
  5913. /**
  5914. * Returns `true` if this sphere intersects with the given box.
  5915. *
  5916. * @param {Box3} box - The box to test.
  5917. * @return {boolean} Whether this sphere intersects with the given box or not.
  5918. */
  5919. intersectsBox( box ) {
  5920. return box.intersectsSphere( this );
  5921. }
  5922. /**
  5923. * Returns `true` if this sphere intersects with the given plane.
  5924. *
  5925. * @param {Plane} plane - The plane to test.
  5926. * @return {boolean} Whether this sphere intersects with the given plane or not.
  5927. */
  5928. intersectsPlane( plane ) {
  5929. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5930. }
  5931. /**
  5932. * Clamps a point within the sphere. If the point is outside the sphere, it
  5933. * will clamp it to the closest point on the edge of the sphere. Points
  5934. * already inside the sphere will not be affected.
  5935. *
  5936. * @param {Vector3} point - The plane to clamp.
  5937. * @param {Vector3} target - The target vector that is used to store the method's result.
  5938. * @return {Vector3} The clamped point.
  5939. */
  5940. clampPoint( point, target ) {
  5941. const deltaLengthSq = this.center.distanceToSquared( point );
  5942. target.copy( point );
  5943. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5944. target.sub( this.center ).normalize();
  5945. target.multiplyScalar( this.radius ).add( this.center );
  5946. }
  5947. return target;
  5948. }
  5949. /**
  5950. * Returns a bounding box that encloses this sphere.
  5951. *
  5952. * @param {Box3} target - The target box that is used to store the method's result.
  5953. * @return {Box3} The bounding box that encloses this sphere.
  5954. */
  5955. getBoundingBox( target ) {
  5956. if ( this.isEmpty() ) {
  5957. // Empty sphere produces empty bounding box
  5958. target.makeEmpty();
  5959. return target;
  5960. }
  5961. target.set( this.center, this.center );
  5962. target.expandByScalar( this.radius );
  5963. return target;
  5964. }
  5965. /**
  5966. * Transforms this sphere with the given 4x4 transformation matrix.
  5967. *
  5968. * @param {Matrix4} matrix - The transformation matrix.
  5969. * @return {Sphere} A reference to this sphere.
  5970. */
  5971. applyMatrix4( matrix ) {
  5972. this.center.applyMatrix4( matrix );
  5973. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5974. return this;
  5975. }
  5976. /**
  5977. * Translates the sphere's center by the given offset.
  5978. *
  5979. * @param {Vector3} offset - The offset.
  5980. * @return {Sphere} A reference to this sphere.
  5981. */
  5982. translate( offset ) {
  5983. this.center.add( offset );
  5984. return this;
  5985. }
  5986. /**
  5987. * Expands the boundaries of this sphere to include the given point.
  5988. *
  5989. * @param {Vector3} point - The point to include.
  5990. * @return {Sphere} A reference to this sphere.
  5991. */
  5992. expandByPoint( point ) {
  5993. if ( this.isEmpty() ) {
  5994. this.center.copy( point );
  5995. this.radius = 0;
  5996. return this;
  5997. }
  5998. _v1$6.subVectors( point, this.center );
  5999. const lengthSq = _v1$6.lengthSq();
  6000. if ( lengthSq > ( this.radius * this.radius ) ) {
  6001. // calculate the minimal sphere
  6002. const length = Math.sqrt( lengthSq );
  6003. const delta = ( length - this.radius ) * 0.5;
  6004. this.center.addScaledVector( _v1$6, delta / length );
  6005. this.radius += delta;
  6006. }
  6007. return this;
  6008. }
  6009. /**
  6010. * Expands this sphere to enclose both the original sphere and the given sphere.
  6011. *
  6012. * @param {Sphere} sphere - The sphere to include.
  6013. * @return {Sphere} A reference to this sphere.
  6014. */
  6015. union( sphere ) {
  6016. if ( sphere.isEmpty() ) {
  6017. return this;
  6018. }
  6019. if ( this.isEmpty() ) {
  6020. this.copy( sphere );
  6021. return this;
  6022. }
  6023. if ( this.center.equals( sphere.center ) === true ) {
  6024. this.radius = Math.max( this.radius, sphere.radius );
  6025. } else {
  6026. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  6027. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  6028. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  6029. }
  6030. return this;
  6031. }
  6032. /**
  6033. * Returns `true` if this sphere is equal with the given one.
  6034. *
  6035. * @param {Sphere} sphere - The sphere to test for equality.
  6036. * @return {boolean} Whether this bounding sphere is equal with the given one.
  6037. */
  6038. equals( sphere ) {
  6039. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  6040. }
  6041. /**
  6042. * Returns a new sphere with copied values from this instance.
  6043. *
  6044. * @return {Sphere} A clone of this instance.
  6045. */
  6046. clone() {
  6047. return new this.constructor().copy( this );
  6048. }
  6049. }
  6050. const _vector$a = /*@__PURE__*/ new Vector3();
  6051. const _segCenter = /*@__PURE__*/ new Vector3();
  6052. const _segDir = /*@__PURE__*/ new Vector3();
  6053. const _diff = /*@__PURE__*/ new Vector3();
  6054. const _edge1 = /*@__PURE__*/ new Vector3();
  6055. const _edge2 = /*@__PURE__*/ new Vector3();
  6056. const _normal$1 = /*@__PURE__*/ new Vector3();
  6057. /**
  6058. * A ray that emits from an origin in a certain direction. The class is used by
  6059. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  6060. * mouse picking (working out what objects in the 3D space the mouse is over)
  6061. * amongst other things.
  6062. */
  6063. class Ray {
  6064. /**
  6065. * Constructs a new ray.
  6066. *
  6067. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  6068. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  6069. */
  6070. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  6071. /**
  6072. * The origin of the ray.
  6073. *
  6074. * @type {Vector3}
  6075. */
  6076. this.origin = origin;
  6077. /**
  6078. * The (normalized) direction of the ray.
  6079. *
  6080. * @type {Vector3}
  6081. */
  6082. this.direction = direction;
  6083. }
  6084. /**
  6085. * Sets the ray's components by copying the given values.
  6086. *
  6087. * @param {Vector3} origin - The origin.
  6088. * @param {Vector3} direction - The direction.
  6089. * @return {Ray} A reference to this ray.
  6090. */
  6091. set( origin, direction ) {
  6092. this.origin.copy( origin );
  6093. this.direction.copy( direction );
  6094. return this;
  6095. }
  6096. /**
  6097. * Copies the values of the given ray to this instance.
  6098. *
  6099. * @param {Ray} ray - The ray to copy.
  6100. * @return {Ray} A reference to this ray.
  6101. */
  6102. copy( ray ) {
  6103. this.origin.copy( ray.origin );
  6104. this.direction.copy( ray.direction );
  6105. return this;
  6106. }
  6107. /**
  6108. * Returns a vector that is located at a given distance along this ray.
  6109. *
  6110. * @param {number} t - The distance along the ray to retrieve a position for.
  6111. * @param {Vector3} target - The target vector that is used to store the method's result.
  6112. * @return {Vector3} A position on the ray.
  6113. */
  6114. at( t, target ) {
  6115. return target.copy( this.origin ).addScaledVector( this.direction, t );
  6116. }
  6117. /**
  6118. * Adjusts the direction of the ray to point at the given vector in world space.
  6119. *
  6120. * @param {Vector3} v - The target position.
  6121. * @return {Ray} A reference to this ray.
  6122. */
  6123. lookAt( v ) {
  6124. this.direction.copy( v ).sub( this.origin ).normalize();
  6125. return this;
  6126. }
  6127. /**
  6128. * Shift the origin of this ray along its direction by the given distance.
  6129. *
  6130. * @param {number} t - The distance along the ray to interpolate.
  6131. * @return {Ray} A reference to this ray.
  6132. */
  6133. recast( t ) {
  6134. this.origin.copy( this.at( t, _vector$a ) );
  6135. return this;
  6136. }
  6137. /**
  6138. * Returns the point along this ray that is closest to the given point.
  6139. *
  6140. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  6141. * @param {Vector3} target - The target vector that is used to store the method's result.
  6142. * @return {Vector3} The closest point on this ray.
  6143. */
  6144. closestPointToPoint( point, target ) {
  6145. target.subVectors( point, this.origin );
  6146. const directionDistance = target.dot( this.direction );
  6147. if ( directionDistance < 0 ) {
  6148. return target.copy( this.origin );
  6149. }
  6150. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6151. }
  6152. /**
  6153. * Returns the distance of the closest approach between this ray and the given point.
  6154. *
  6155. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6156. * @return {number} The distance.
  6157. */
  6158. distanceToPoint( point ) {
  6159. return Math.sqrt( this.distanceSqToPoint( point ) );
  6160. }
  6161. /**
  6162. * Returns the squared distance of the closest approach between this ray and the given point.
  6163. *
  6164. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6165. * @return {number} The squared distance.
  6166. */
  6167. distanceSqToPoint( point ) {
  6168. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  6169. // point behind the ray
  6170. if ( directionDistance < 0 ) {
  6171. return this.origin.distanceToSquared( point );
  6172. }
  6173. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6174. return _vector$a.distanceToSquared( point );
  6175. }
  6176. /**
  6177. * Returns the squared distance between this ray and the given line segment.
  6178. *
  6179. * @param {Vector3} v0 - The start point of the line segment.
  6180. * @param {Vector3} v1 - The end point of the line segment.
  6181. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  6182. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  6183. * @return {number} The squared distance.
  6184. */
  6185. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  6186. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  6187. // It returns the min distance between the ray and the segment
  6188. // defined by v0 and v1
  6189. // It can also set two optional targets :
  6190. // - The closest point on the ray
  6191. // - The closest point on the segment
  6192. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  6193. _segDir.copy( v1 ).sub( v0 ).normalize();
  6194. _diff.copy( this.origin ).sub( _segCenter );
  6195. const segExtent = v0.distanceTo( v1 ) * 0.5;
  6196. const a01 = - this.direction.dot( _segDir );
  6197. const b0 = _diff.dot( this.direction );
  6198. const b1 = - _diff.dot( _segDir );
  6199. const c = _diff.lengthSq();
  6200. const det = Math.abs( 1 - a01 * a01 );
  6201. let s0, s1, sqrDist, extDet;
  6202. if ( det > 0 ) {
  6203. // The ray and segment are not parallel.
  6204. s0 = a01 * b1 - b0;
  6205. s1 = a01 * b0 - b1;
  6206. extDet = segExtent * det;
  6207. if ( s0 >= 0 ) {
  6208. if ( s1 >= - extDet ) {
  6209. if ( s1 <= extDet ) {
  6210. // region 0
  6211. // Minimum at interior points of ray and segment.
  6212. const invDet = 1 / det;
  6213. s0 *= invDet;
  6214. s1 *= invDet;
  6215. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  6216. } else {
  6217. // region 1
  6218. s1 = segExtent;
  6219. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6220. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6221. }
  6222. } else {
  6223. // region 5
  6224. s1 = - segExtent;
  6225. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6226. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6227. }
  6228. } else {
  6229. if ( s1 <= - extDet ) {
  6230. // region 4
  6231. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  6232. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6233. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6234. } else if ( s1 <= extDet ) {
  6235. // region 3
  6236. s0 = 0;
  6237. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6238. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  6239. } else {
  6240. // region 2
  6241. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  6242. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6243. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6244. }
  6245. }
  6246. } else {
  6247. // Ray and segment are parallel.
  6248. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6249. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6250. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6251. }
  6252. if ( optionalPointOnRay ) {
  6253. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  6254. }
  6255. if ( optionalPointOnSegment ) {
  6256. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  6257. }
  6258. return sqrDist;
  6259. }
  6260. /**
  6261. * Intersects this ray with the given sphere, returning the intersection
  6262. * point or `null` if there is no intersection.
  6263. *
  6264. * @param {Sphere} sphere - The sphere to intersect.
  6265. * @param {Vector3} target - The target vector that is used to store the method's result.
  6266. * @return {?Vector3} The intersection point.
  6267. */
  6268. intersectSphere( sphere, target ) {
  6269. _vector$a.subVectors( sphere.center, this.origin );
  6270. const tca = _vector$a.dot( this.direction );
  6271. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  6272. const radius2 = sphere.radius * sphere.radius;
  6273. if ( d2 > radius2 ) return null;
  6274. const thc = Math.sqrt( radius2 - d2 );
  6275. // t0 = first intersect point - entrance on front of sphere
  6276. const t0 = tca - thc;
  6277. // t1 = second intersect point - exit point on back of sphere
  6278. const t1 = tca + thc;
  6279. // test to see if t1 is behind the ray - if so, return null
  6280. if ( t1 < 0 ) return null;
  6281. // test to see if t0 is behind the ray:
  6282. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6283. // in order to always return an intersect point that is in front of the ray.
  6284. if ( t0 < 0 ) return this.at( t1, target );
  6285. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6286. return this.at( t0, target );
  6287. }
  6288. /**
  6289. * Returns `true` if this ray intersects with the given sphere.
  6290. *
  6291. * @param {Sphere} sphere - The sphere to intersect.
  6292. * @return {boolean} Whether this ray intersects with the given sphere or not.
  6293. */
  6294. intersectsSphere( sphere ) {
  6295. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  6296. }
  6297. /**
  6298. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  6299. * does not intersect with the plane.
  6300. *
  6301. * @param {Plane} plane - The plane to compute the distance to.
  6302. * @return {?number} Whether this ray intersects with the given sphere or not.
  6303. */
  6304. distanceToPlane( plane ) {
  6305. const denominator = plane.normal.dot( this.direction );
  6306. if ( denominator === 0 ) {
  6307. // line is coplanar, return origin
  6308. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6309. return 0;
  6310. }
  6311. // Null is preferable to undefined since undefined means.... it is undefined
  6312. return null;
  6313. }
  6314. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6315. // Return if the ray never intersects the plane
  6316. return t >= 0 ? t : null;
  6317. }
  6318. /**
  6319. * Intersects this ray with the given plane, returning the intersection
  6320. * point or `null` if there is no intersection.
  6321. *
  6322. * @param {Plane} plane - The plane to intersect.
  6323. * @param {Vector3} target - The target vector that is used to store the method's result.
  6324. * @return {?Vector3} The intersection point.
  6325. */
  6326. intersectPlane( plane, target ) {
  6327. const t = this.distanceToPlane( plane );
  6328. if ( t === null ) {
  6329. return null;
  6330. }
  6331. return this.at( t, target );
  6332. }
  6333. /**
  6334. * Returns `true` if this ray intersects with the given plane.
  6335. *
  6336. * @param {Plane} plane - The plane to intersect.
  6337. * @return {boolean} Whether this ray intersects with the given plane or not.
  6338. */
  6339. intersectsPlane( plane ) {
  6340. // check if the ray lies on the plane first
  6341. const distToPoint = plane.distanceToPoint( this.origin );
  6342. if ( distToPoint === 0 ) {
  6343. return true;
  6344. }
  6345. const denominator = plane.normal.dot( this.direction );
  6346. if ( denominator * distToPoint < 0 ) {
  6347. return true;
  6348. }
  6349. // ray origin is behind the plane (and is pointing behind it)
  6350. return false;
  6351. }
  6352. /**
  6353. * Intersects this ray with the given bounding box, returning the intersection
  6354. * point or `null` if there is no intersection.
  6355. *
  6356. * @param {Box3} box - The box to intersect.
  6357. * @param {Vector3} target - The target vector that is used to store the method's result.
  6358. * @return {?Vector3} The intersection point.
  6359. */
  6360. intersectBox( box, target ) {
  6361. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  6362. const invdirx = 1 / this.direction.x,
  6363. invdiry = 1 / this.direction.y,
  6364. invdirz = 1 / this.direction.z;
  6365. const origin = this.origin;
  6366. if ( invdirx >= 0 ) {
  6367. tmin = ( box.min.x - origin.x ) * invdirx;
  6368. tmax = ( box.max.x - origin.x ) * invdirx;
  6369. } else {
  6370. tmin = ( box.max.x - origin.x ) * invdirx;
  6371. tmax = ( box.min.x - origin.x ) * invdirx;
  6372. }
  6373. if ( invdiry >= 0 ) {
  6374. tymin = ( box.min.y - origin.y ) * invdiry;
  6375. tymax = ( box.max.y - origin.y ) * invdiry;
  6376. } else {
  6377. tymin = ( box.max.y - origin.y ) * invdiry;
  6378. tymax = ( box.min.y - origin.y ) * invdiry;
  6379. }
  6380. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6381. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  6382. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  6383. if ( invdirz >= 0 ) {
  6384. tzmin = ( box.min.z - origin.z ) * invdirz;
  6385. tzmax = ( box.max.z - origin.z ) * invdirz;
  6386. } else {
  6387. tzmin = ( box.max.z - origin.z ) * invdirz;
  6388. tzmax = ( box.min.z - origin.z ) * invdirz;
  6389. }
  6390. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6391. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6392. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6393. //return point closest to the ray (positive side)
  6394. if ( tmax < 0 ) return null;
  6395. return this.at( tmin >= 0 ? tmin : tmax, target );
  6396. }
  6397. /**
  6398. * Returns `true` if this ray intersects with the given box.
  6399. *
  6400. * @param {Box3} box - The box to intersect.
  6401. * @return {boolean} Whether this ray intersects with the given box or not.
  6402. */
  6403. intersectsBox( box ) {
  6404. return this.intersectBox( box, _vector$a ) !== null;
  6405. }
  6406. /**
  6407. * Intersects this ray with the given triangle, returning the intersection
  6408. * point or `null` if there is no intersection.
  6409. *
  6410. * @param {Vector3} a - The first vertex of the triangle.
  6411. * @param {Vector3} b - The second vertex of the triangle.
  6412. * @param {Vector3} c - The third vertex of the triangle.
  6413. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  6414. * @param {Vector3} target - The target vector that is used to store the method's result.
  6415. * @return {?Vector3} The intersection point.
  6416. */
  6417. intersectTriangle( a, b, c, backfaceCulling, target ) {
  6418. // Compute the offset origin, edges, and normal.
  6419. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6420. _edge1.subVectors( b, a );
  6421. _edge2.subVectors( c, a );
  6422. _normal$1.crossVectors( _edge1, _edge2 );
  6423. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6424. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6425. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6426. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6427. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6428. let DdN = this.direction.dot( _normal$1 );
  6429. let sign;
  6430. if ( DdN > 0 ) {
  6431. if ( backfaceCulling ) return null;
  6432. sign = 1;
  6433. } else if ( DdN < 0 ) {
  6434. sign = -1;
  6435. DdN = - DdN;
  6436. } else {
  6437. return null;
  6438. }
  6439. _diff.subVectors( this.origin, a );
  6440. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  6441. // b1 < 0, no intersection
  6442. if ( DdQxE2 < 0 ) {
  6443. return null;
  6444. }
  6445. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  6446. // b2 < 0, no intersection
  6447. if ( DdE1xQ < 0 ) {
  6448. return null;
  6449. }
  6450. // b1+b2 > 1, no intersection
  6451. if ( DdQxE2 + DdE1xQ > DdN ) {
  6452. return null;
  6453. }
  6454. // Line intersects triangle, check if ray does.
  6455. const QdN = - sign * _diff.dot( _normal$1 );
  6456. // t < 0, no intersection
  6457. if ( QdN < 0 ) {
  6458. return null;
  6459. }
  6460. // Ray intersects triangle.
  6461. return this.at( QdN / DdN, target );
  6462. }
  6463. /**
  6464. * Transforms this ray with the given 4x4 transformation matrix.
  6465. *
  6466. * @param {Matrix4} matrix4 - The transformation matrix.
  6467. * @return {Ray} A reference to this ray.
  6468. */
  6469. applyMatrix4( matrix4 ) {
  6470. this.origin.applyMatrix4( matrix4 );
  6471. this.direction.transformDirection( matrix4 );
  6472. return this;
  6473. }
  6474. /**
  6475. * Returns `true` if this ray is equal with the given one.
  6476. *
  6477. * @param {Ray} ray - The ray to test for equality.
  6478. * @return {boolean} Whether this ray is equal with the given one.
  6479. */
  6480. equals( ray ) {
  6481. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6482. }
  6483. /**
  6484. * Returns a new ray with copied values from this instance.
  6485. *
  6486. * @return {Ray} A clone of this instance.
  6487. */
  6488. clone() {
  6489. return new this.constructor().copy( this );
  6490. }
  6491. }
  6492. /**
  6493. * Represents a 4x4 matrix.
  6494. *
  6495. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  6496. * 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}
  6497. *
  6498. * This allows a 3D vector representing a point in 3D space to undergo
  6499. * transformations such as translation, rotation, shear, scale, reflection,
  6500. * orthogonal or perspective projection and so on, by being multiplied by the
  6501. * matrix. This is known as `applying` the matrix to the vector.
  6502. *
  6503. * A Note on Row-Major and Column-Major Ordering:
  6504. *
  6505. * The constructor and {@link Matrix3#set} method take arguments in
  6506. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  6507. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  6508. * This means that calling:
  6509. * ```js
  6510. * const m = new THREE.Matrix4();
  6511. * m.set( 11, 12, 13, 14,
  6512. * 21, 22, 23, 24,
  6513. * 31, 32, 33, 34,
  6514. * 41, 42, 43, 44 );
  6515. * ```
  6516. * will result in the elements array containing:
  6517. * ```js
  6518. * m.elements = [ 11, 21, 31, 41,
  6519. * 12, 22, 32, 42,
  6520. * 13, 23, 33, 43,
  6521. * 14, 24, 34, 44 ];
  6522. * ```
  6523. * and internally all calculations are performed using column-major ordering.
  6524. * However, as the actual ordering makes no difference mathematically and
  6525. * most people are used to thinking about matrices in row-major order, the
  6526. * three.js documentation shows matrices in row-major order. Just bear in
  6527. * mind that if you are reading the source code, you'll have to take the
  6528. * transpose of any matrices outlined here to make sense of the calculations.
  6529. */
  6530. class Matrix4 {
  6531. /**
  6532. * Constructs a new 4x4 matrix. The arguments are supposed to be
  6533. * in row-major order. If no arguments are provided, the constructor
  6534. * initializes the matrix as an identity matrix.
  6535. *
  6536. * @param {number} [n11] - 1-1 matrix element.
  6537. * @param {number} [n12] - 1-2 matrix element.
  6538. * @param {number} [n13] - 1-3 matrix element.
  6539. * @param {number} [n14] - 1-4 matrix element.
  6540. * @param {number} [n21] - 2-1 matrix element.
  6541. * @param {number} [n22] - 2-2 matrix element.
  6542. * @param {number} [n23] - 2-3 matrix element.
  6543. * @param {number} [n24] - 2-4 matrix element.
  6544. * @param {number} [n31] - 3-1 matrix element.
  6545. * @param {number} [n32] - 3-2 matrix element.
  6546. * @param {number} [n33] - 3-3 matrix element.
  6547. * @param {number} [n34] - 3-4 matrix element.
  6548. * @param {number} [n41] - 4-1 matrix element.
  6549. * @param {number} [n42] - 4-2 matrix element.
  6550. * @param {number} [n43] - 4-3 matrix element.
  6551. * @param {number} [n44] - 4-4 matrix element.
  6552. */
  6553. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6554. /**
  6555. * This flag can be used for type testing.
  6556. *
  6557. * @type {boolean}
  6558. * @readonly
  6559. * @default true
  6560. */
  6561. Matrix4.prototype.isMatrix4 = true;
  6562. /**
  6563. * A column-major list of matrix values.
  6564. *
  6565. * @type {Array<number>}
  6566. */
  6567. this.elements = [
  6568. 1, 0, 0, 0,
  6569. 0, 1, 0, 0,
  6570. 0, 0, 1, 0,
  6571. 0, 0, 0, 1
  6572. ];
  6573. if ( n11 !== undefined ) {
  6574. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  6575. }
  6576. }
  6577. /**
  6578. * Sets the elements of the matrix.The arguments are supposed to be
  6579. * in row-major order.
  6580. *
  6581. * @param {number} [n11] - 1-1 matrix element.
  6582. * @param {number} [n12] - 1-2 matrix element.
  6583. * @param {number} [n13] - 1-3 matrix element.
  6584. * @param {number} [n14] - 1-4 matrix element.
  6585. * @param {number} [n21] - 2-1 matrix element.
  6586. * @param {number} [n22] - 2-2 matrix element.
  6587. * @param {number} [n23] - 2-3 matrix element.
  6588. * @param {number} [n24] - 2-4 matrix element.
  6589. * @param {number} [n31] - 3-1 matrix element.
  6590. * @param {number} [n32] - 3-2 matrix element.
  6591. * @param {number} [n33] - 3-3 matrix element.
  6592. * @param {number} [n34] - 3-4 matrix element.
  6593. * @param {number} [n41] - 4-1 matrix element.
  6594. * @param {number} [n42] - 4-2 matrix element.
  6595. * @param {number} [n43] - 4-3 matrix element.
  6596. * @param {number} [n44] - 4-4 matrix element.
  6597. * @return {Matrix4} A reference to this matrix.
  6598. */
  6599. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6600. const te = this.elements;
  6601. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6602. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6603. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6604. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6605. return this;
  6606. }
  6607. /**
  6608. * Sets this matrix to the 4x4 identity matrix.
  6609. *
  6610. * @return {Matrix4} A reference to this matrix.
  6611. */
  6612. identity() {
  6613. this.set(
  6614. 1, 0, 0, 0,
  6615. 0, 1, 0, 0,
  6616. 0, 0, 1, 0,
  6617. 0, 0, 0, 1
  6618. );
  6619. return this;
  6620. }
  6621. /**
  6622. * Returns a matrix with copied values from this instance.
  6623. *
  6624. * @return {Matrix4} A clone of this instance.
  6625. */
  6626. clone() {
  6627. return new Matrix4().fromArray( this.elements );
  6628. }
  6629. /**
  6630. * Copies the values of the given matrix to this instance.
  6631. *
  6632. * @param {Matrix4} m - The matrix to copy.
  6633. * @return {Matrix4} A reference to this matrix.
  6634. */
  6635. copy( m ) {
  6636. const te = this.elements;
  6637. const me = m.elements;
  6638. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  6639. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  6640. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  6641. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  6642. return this;
  6643. }
  6644. /**
  6645. * Copies the translation component of the given matrix
  6646. * into this matrix's translation component.
  6647. *
  6648. * @param {Matrix4} m - The matrix to copy the translation component.
  6649. * @return {Matrix4} A reference to this matrix.
  6650. */
  6651. copyPosition( m ) {
  6652. const te = this.elements, me = m.elements;
  6653. te[ 12 ] = me[ 12 ];
  6654. te[ 13 ] = me[ 13 ];
  6655. te[ 14 ] = me[ 14 ];
  6656. return this;
  6657. }
  6658. /**
  6659. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  6660. *
  6661. * @param {Matrix3} m - The 3x3 matrix.
  6662. * @return {Matrix4} A reference to this matrix.
  6663. */
  6664. setFromMatrix3( m ) {
  6665. const me = m.elements;
  6666. this.set(
  6667. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  6668. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  6669. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  6670. 0, 0, 0, 1
  6671. );
  6672. return this;
  6673. }
  6674. /**
  6675. * Extracts the basis of this matrix into the three axis vectors provided.
  6676. *
  6677. * @param {Vector3} xAxis - The basis's x axis.
  6678. * @param {Vector3} yAxis - The basis's y axis.
  6679. * @param {Vector3} zAxis - The basis's z axis.
  6680. * @return {Matrix4} A reference to this matrix.
  6681. */
  6682. extractBasis( xAxis, yAxis, zAxis ) {
  6683. xAxis.setFromMatrixColumn( this, 0 );
  6684. yAxis.setFromMatrixColumn( this, 1 );
  6685. zAxis.setFromMatrixColumn( this, 2 );
  6686. return this;
  6687. }
  6688. /**
  6689. * Sets the given basis vectors to this matrix.
  6690. *
  6691. * @param {Vector3} xAxis - The basis's x axis.
  6692. * @param {Vector3} yAxis - The basis's y axis.
  6693. * @param {Vector3} zAxis - The basis's z axis.
  6694. * @return {Matrix4} A reference to this matrix.
  6695. */
  6696. makeBasis( xAxis, yAxis, zAxis ) {
  6697. this.set(
  6698. xAxis.x, yAxis.x, zAxis.x, 0,
  6699. xAxis.y, yAxis.y, zAxis.y, 0,
  6700. xAxis.z, yAxis.z, zAxis.z, 0,
  6701. 0, 0, 0, 1
  6702. );
  6703. return this;
  6704. }
  6705. /**
  6706. * Extracts the rotation component of the given matrix
  6707. * into this matrix's rotation component.
  6708. *
  6709. * Note: This method does not support reflection matrices.
  6710. *
  6711. * @param {Matrix4} m - The matrix.
  6712. * @return {Matrix4} A reference to this matrix.
  6713. */
  6714. extractRotation( m ) {
  6715. const te = this.elements;
  6716. const me = m.elements;
  6717. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  6718. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  6719. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  6720. te[ 0 ] = me[ 0 ] * scaleX;
  6721. te[ 1 ] = me[ 1 ] * scaleX;
  6722. te[ 2 ] = me[ 2 ] * scaleX;
  6723. te[ 3 ] = 0;
  6724. te[ 4 ] = me[ 4 ] * scaleY;
  6725. te[ 5 ] = me[ 5 ] * scaleY;
  6726. te[ 6 ] = me[ 6 ] * scaleY;
  6727. te[ 7 ] = 0;
  6728. te[ 8 ] = me[ 8 ] * scaleZ;
  6729. te[ 9 ] = me[ 9 ] * scaleZ;
  6730. te[ 10 ] = me[ 10 ] * scaleZ;
  6731. te[ 11 ] = 0;
  6732. te[ 12 ] = 0;
  6733. te[ 13 ] = 0;
  6734. te[ 14 ] = 0;
  6735. te[ 15 ] = 1;
  6736. return this;
  6737. }
  6738. /**
  6739. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  6740. * the rotation specified by the given Euler angles. The rest of
  6741. * the matrix is set to the identity. Depending on the {@link Euler#order},
  6742. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  6743. * for a complete list.
  6744. *
  6745. * @param {Euler} euler - The Euler angles.
  6746. * @return {Matrix4} A reference to this matrix.
  6747. */
  6748. makeRotationFromEuler( euler ) {
  6749. const te = this.elements;
  6750. const x = euler.x, y = euler.y, z = euler.z;
  6751. const a = Math.cos( x ), b = Math.sin( x );
  6752. const c = Math.cos( y ), d = Math.sin( y );
  6753. const e = Math.cos( z ), f = Math.sin( z );
  6754. if ( euler.order === 'XYZ' ) {
  6755. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6756. te[ 0 ] = c * e;
  6757. te[ 4 ] = - c * f;
  6758. te[ 8 ] = d;
  6759. te[ 1 ] = af + be * d;
  6760. te[ 5 ] = ae - bf * d;
  6761. te[ 9 ] = - b * c;
  6762. te[ 2 ] = bf - ae * d;
  6763. te[ 6 ] = be + af * d;
  6764. te[ 10 ] = a * c;
  6765. } else if ( euler.order === 'YXZ' ) {
  6766. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6767. te[ 0 ] = ce + df * b;
  6768. te[ 4 ] = de * b - cf;
  6769. te[ 8 ] = a * d;
  6770. te[ 1 ] = a * f;
  6771. te[ 5 ] = a * e;
  6772. te[ 9 ] = - b;
  6773. te[ 2 ] = cf * b - de;
  6774. te[ 6 ] = df + ce * b;
  6775. te[ 10 ] = a * c;
  6776. } else if ( euler.order === 'ZXY' ) {
  6777. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6778. te[ 0 ] = ce - df * b;
  6779. te[ 4 ] = - a * f;
  6780. te[ 8 ] = de + cf * b;
  6781. te[ 1 ] = cf + de * b;
  6782. te[ 5 ] = a * e;
  6783. te[ 9 ] = df - ce * b;
  6784. te[ 2 ] = - a * d;
  6785. te[ 6 ] = b;
  6786. te[ 10 ] = a * c;
  6787. } else if ( euler.order === 'ZYX' ) {
  6788. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6789. te[ 0 ] = c * e;
  6790. te[ 4 ] = be * d - af;
  6791. te[ 8 ] = ae * d + bf;
  6792. te[ 1 ] = c * f;
  6793. te[ 5 ] = bf * d + ae;
  6794. te[ 9 ] = af * d - be;
  6795. te[ 2 ] = - d;
  6796. te[ 6 ] = b * c;
  6797. te[ 10 ] = a * c;
  6798. } else if ( euler.order === 'YZX' ) {
  6799. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6800. te[ 0 ] = c * e;
  6801. te[ 4 ] = bd - ac * f;
  6802. te[ 8 ] = bc * f + ad;
  6803. te[ 1 ] = f;
  6804. te[ 5 ] = a * e;
  6805. te[ 9 ] = - b * e;
  6806. te[ 2 ] = - d * e;
  6807. te[ 6 ] = ad * f + bc;
  6808. te[ 10 ] = ac - bd * f;
  6809. } else if ( euler.order === 'XZY' ) {
  6810. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6811. te[ 0 ] = c * e;
  6812. te[ 4 ] = - f;
  6813. te[ 8 ] = d * e;
  6814. te[ 1 ] = ac * f + bd;
  6815. te[ 5 ] = a * e;
  6816. te[ 9 ] = ad * f - bc;
  6817. te[ 2 ] = bc * f - ad;
  6818. te[ 6 ] = b * e;
  6819. te[ 10 ] = bd * f + ac;
  6820. }
  6821. // bottom row
  6822. te[ 3 ] = 0;
  6823. te[ 7 ] = 0;
  6824. te[ 11 ] = 0;
  6825. // last column
  6826. te[ 12 ] = 0;
  6827. te[ 13 ] = 0;
  6828. te[ 14 ] = 0;
  6829. te[ 15 ] = 1;
  6830. return this;
  6831. }
  6832. /**
  6833. * Sets the rotation component of this matrix to the rotation specified by
  6834. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  6835. * The rest of the matrix is set to the identity.
  6836. *
  6837. * @param {Quaternion} q - The Quaternion.
  6838. * @return {Matrix4} A reference to this matrix.
  6839. */
  6840. makeRotationFromQuaternion( q ) {
  6841. return this.compose( _zero, q, _one );
  6842. }
  6843. /**
  6844. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  6845. * `target`, and oriented by the up-direction.
  6846. *
  6847. * @param {Vector3} eye - The eye vector.
  6848. * @param {Vector3} target - The target vector.
  6849. * @param {Vector3} up - The up vector.
  6850. * @return {Matrix4} A reference to this matrix.
  6851. */
  6852. lookAt( eye, target, up ) {
  6853. const te = this.elements;
  6854. _z.subVectors( eye, target );
  6855. if ( _z.lengthSq() === 0 ) {
  6856. // eye and target are in the same position
  6857. _z.z = 1;
  6858. }
  6859. _z.normalize();
  6860. _x.crossVectors( up, _z );
  6861. if ( _x.lengthSq() === 0 ) {
  6862. // up and z are parallel
  6863. if ( Math.abs( up.z ) === 1 ) {
  6864. _z.x += 0.0001;
  6865. } else {
  6866. _z.z += 0.0001;
  6867. }
  6868. _z.normalize();
  6869. _x.crossVectors( up, _z );
  6870. }
  6871. _x.normalize();
  6872. _y.crossVectors( _z, _x );
  6873. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  6874. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  6875. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  6876. return this;
  6877. }
  6878. /**
  6879. * Post-multiplies this matrix by the given 4x4 matrix.
  6880. *
  6881. * @param {Matrix4} m - The matrix to multiply with.
  6882. * @return {Matrix4} A reference to this matrix.
  6883. */
  6884. multiply( m ) {
  6885. return this.multiplyMatrices( this, m );
  6886. }
  6887. /**
  6888. * Pre-multiplies this matrix by the given 4x4 matrix.
  6889. *
  6890. * @param {Matrix4} m - The matrix to multiply with.
  6891. * @return {Matrix4} A reference to this matrix.
  6892. */
  6893. premultiply( m ) {
  6894. return this.multiplyMatrices( m, this );
  6895. }
  6896. /**
  6897. * Multiples the given 4x4 matrices and stores the result
  6898. * in this matrix.
  6899. *
  6900. * @param {Matrix4} a - The first matrix.
  6901. * @param {Matrix4} b - The second matrix.
  6902. * @return {Matrix4} A reference to this matrix.
  6903. */
  6904. multiplyMatrices( a, b ) {
  6905. const ae = a.elements;
  6906. const be = b.elements;
  6907. const te = this.elements;
  6908. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6909. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6910. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6911. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6912. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6913. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6914. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6915. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6916. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6917. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6918. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6919. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6920. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6921. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6922. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6923. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6924. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6925. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6926. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6927. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6928. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6929. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6930. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6931. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6932. return this;
  6933. }
  6934. /**
  6935. * Multiplies every component of the matrix by the given scalar.
  6936. *
  6937. * @param {number} s - The scalar.
  6938. * @return {Matrix4} A reference to this matrix.
  6939. */
  6940. multiplyScalar( s ) {
  6941. const te = this.elements;
  6942. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6943. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6944. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6945. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6946. return this;
  6947. }
  6948. /**
  6949. * Computes and returns the determinant of this matrix.
  6950. *
  6951. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  6952. *
  6953. * @return {number} The determinant.
  6954. */
  6955. determinant() {
  6956. const te = this.elements;
  6957. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6958. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6959. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6960. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6961. //TODO: make this more efficient
  6962. return (
  6963. n41 * (
  6964. + n14 * n23 * n32
  6965. - n13 * n24 * n32
  6966. - n14 * n22 * n33
  6967. + n12 * n24 * n33
  6968. + n13 * n22 * n34
  6969. - n12 * n23 * n34
  6970. ) +
  6971. n42 * (
  6972. + n11 * n23 * n34
  6973. - n11 * n24 * n33
  6974. + n14 * n21 * n33
  6975. - n13 * n21 * n34
  6976. + n13 * n24 * n31
  6977. - n14 * n23 * n31
  6978. ) +
  6979. n43 * (
  6980. + n11 * n24 * n32
  6981. - n11 * n22 * n34
  6982. - n14 * n21 * n32
  6983. + n12 * n21 * n34
  6984. + n14 * n22 * n31
  6985. - n12 * n24 * n31
  6986. ) +
  6987. n44 * (
  6988. - n13 * n22 * n31
  6989. - n11 * n23 * n32
  6990. + n11 * n22 * n33
  6991. + n13 * n21 * n32
  6992. - n12 * n21 * n33
  6993. + n12 * n23 * n31
  6994. )
  6995. );
  6996. }
  6997. /**
  6998. * Transposes this matrix in place.
  6999. *
  7000. * @return {Matrix4} A reference to this matrix.
  7001. */
  7002. transpose() {
  7003. const te = this.elements;
  7004. let tmp;
  7005. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  7006. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  7007. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  7008. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  7009. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  7010. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  7011. return this;
  7012. }
  7013. /**
  7014. * Sets the position component for this matrix from the given vector,
  7015. * without affecting the rest of the matrix.
  7016. *
  7017. * @param {number|Vector3} x - The x component of the vector or alternativley the vector object.
  7018. * @param {number} y - The y component of the vector.
  7019. * @param {number} z - The z component of the vector.
  7020. * @return {Matrix4} A reference to this matrix.
  7021. */
  7022. setPosition( x, y, z ) {
  7023. const te = this.elements;
  7024. if ( x.isVector3 ) {
  7025. te[ 12 ] = x.x;
  7026. te[ 13 ] = x.y;
  7027. te[ 14 ] = x.z;
  7028. } else {
  7029. te[ 12 ] = x;
  7030. te[ 13 ] = y;
  7031. te[ 14 ] = z;
  7032. }
  7033. return this;
  7034. }
  7035. /**
  7036. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  7037. * You can not invert with a determinant of zero. If you attempt this, the method produces
  7038. * a zero matrix instead.
  7039. *
  7040. * @return {Matrix4} A reference to this matrix.
  7041. */
  7042. invert() {
  7043. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  7044. const te = this.elements,
  7045. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  7046. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  7047. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  7048. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  7049. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  7050. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  7051. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  7052. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  7053. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  7054. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  7055. const detInv = 1 / det;
  7056. te[ 0 ] = t11 * detInv;
  7057. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  7058. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  7059. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  7060. te[ 4 ] = t12 * detInv;
  7061. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  7062. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  7063. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  7064. te[ 8 ] = t13 * detInv;
  7065. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  7066. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  7067. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  7068. te[ 12 ] = t14 * detInv;
  7069. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  7070. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  7071. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  7072. return this;
  7073. }
  7074. /**
  7075. * Multiplies the columns of this matrix by the given vector.
  7076. *
  7077. * @param {Vector3} v - The scale vector.
  7078. * @return {Matrix4} A reference to this matrix.
  7079. */
  7080. scale( v ) {
  7081. const te = this.elements;
  7082. const x = v.x, y = v.y, z = v.z;
  7083. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  7084. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  7085. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  7086. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  7087. return this;
  7088. }
  7089. /**
  7090. * Gets the maximum scale value of the three axes.
  7091. *
  7092. * @return {number} The maxium scale.
  7093. */
  7094. getMaxScaleOnAxis() {
  7095. const te = this.elements;
  7096. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  7097. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  7098. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  7099. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  7100. }
  7101. /**
  7102. * Sets this matrix as a translation transform from the given vector.
  7103. *
  7104. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  7105. * @param {number} y - The amount to translate in the Y axis.
  7106. * @param {number} z - The amount to translate in the z axis.
  7107. * @return {Matrix4} A reference to this matrix.
  7108. */
  7109. makeTranslation( x, y, z ) {
  7110. if ( x.isVector3 ) {
  7111. this.set(
  7112. 1, 0, 0, x.x,
  7113. 0, 1, 0, x.y,
  7114. 0, 0, 1, x.z,
  7115. 0, 0, 0, 1
  7116. );
  7117. } else {
  7118. this.set(
  7119. 1, 0, 0, x,
  7120. 0, 1, 0, y,
  7121. 0, 0, 1, z,
  7122. 0, 0, 0, 1
  7123. );
  7124. }
  7125. return this;
  7126. }
  7127. /**
  7128. * Sets this matrix as a rotational transformation around the X axis by
  7129. * the given angle.
  7130. *
  7131. * @param {number} theta - The rotation in radians.
  7132. * @return {Matrix4} A reference to this matrix.
  7133. */
  7134. makeRotationX( theta ) {
  7135. const c = Math.cos( theta ), s = Math.sin( theta );
  7136. this.set(
  7137. 1, 0, 0, 0,
  7138. 0, c, - s, 0,
  7139. 0, s, c, 0,
  7140. 0, 0, 0, 1
  7141. );
  7142. return this;
  7143. }
  7144. /**
  7145. * Sets this matrix as a rotational transformation around the Y axis by
  7146. * the given angle.
  7147. *
  7148. * @param {number} theta - The rotation in radians.
  7149. * @return {Matrix4} A reference to this matrix.
  7150. */
  7151. makeRotationY( theta ) {
  7152. const c = Math.cos( theta ), s = Math.sin( theta );
  7153. this.set(
  7154. c, 0, s, 0,
  7155. 0, 1, 0, 0,
  7156. - s, 0, c, 0,
  7157. 0, 0, 0, 1
  7158. );
  7159. return this;
  7160. }
  7161. /**
  7162. * Sets this matrix as a rotational transformation around the Z axis by
  7163. * the given angle.
  7164. *
  7165. * @param {number} theta - The rotation in radians.
  7166. * @return {Matrix4} A reference to this matrix.
  7167. */
  7168. makeRotationZ( theta ) {
  7169. const c = Math.cos( theta ), s = Math.sin( theta );
  7170. this.set(
  7171. c, - s, 0, 0,
  7172. s, c, 0, 0,
  7173. 0, 0, 1, 0,
  7174. 0, 0, 0, 1
  7175. );
  7176. return this;
  7177. }
  7178. /**
  7179. * Sets this matrix as a rotational transformation around the given axis by
  7180. * the given angle.
  7181. *
  7182. * This is a somewhat controversial but mathematically sound alternative to
  7183. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  7184. *
  7185. * @param {Vector3} axis - The normalized rotation axis.
  7186. * @param {number} angle - The rotation in radians.
  7187. * @return {Matrix4} A reference to this matrix.
  7188. */
  7189. makeRotationAxis( axis, angle ) {
  7190. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  7191. const c = Math.cos( angle );
  7192. const s = Math.sin( angle );
  7193. const t = 1 - c;
  7194. const x = axis.x, y = axis.y, z = axis.z;
  7195. const tx = t * x, ty = t * y;
  7196. this.set(
  7197. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  7198. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  7199. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  7200. 0, 0, 0, 1
  7201. );
  7202. return this;
  7203. }
  7204. /**
  7205. * Sets this matrix as a scale transformation.
  7206. *
  7207. * @param {number} x - The amount to scale in the X axis.
  7208. * @param {number} y - The amount to scale in the Y axis.
  7209. * @param {number} z - The amount to scale in the Z axis.
  7210. * @return {Matrix4} A reference to this matrix.
  7211. */
  7212. makeScale( x, y, z ) {
  7213. this.set(
  7214. x, 0, 0, 0,
  7215. 0, y, 0, 0,
  7216. 0, 0, z, 0,
  7217. 0, 0, 0, 1
  7218. );
  7219. return this;
  7220. }
  7221. /**
  7222. * Sets this matrix as a shear transformation.
  7223. *
  7224. * @param {number} xy - The amount to shear X by Y.
  7225. * @param {number} xz - The amount to shear X by Z.
  7226. * @param {number} yx - The amount to shear Y by X.
  7227. * @param {number} yz - The amount to shear Y by Z.
  7228. * @param {number} zx - The amount to shear Z by X.
  7229. * @param {number} zy - The amount to shear Z by Y.
  7230. * @return {Matrix4} A reference to this matrix.
  7231. */
  7232. makeShear( xy, xz, yx, yz, zx, zy ) {
  7233. this.set(
  7234. 1, yx, zx, 0,
  7235. xy, 1, zy, 0,
  7236. xz, yz, 1, 0,
  7237. 0, 0, 0, 1
  7238. );
  7239. return this;
  7240. }
  7241. /**
  7242. * Sets this matrix to the transformation composed of the given position,
  7243. * rotation (Quaternion) and scale.
  7244. *
  7245. * @param {Vector3} position - The position vector.
  7246. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7247. * @param {Vector3} scale - The scale vector.
  7248. * @return {Matrix4} A reference to this matrix.
  7249. */
  7250. compose( position, quaternion, scale ) {
  7251. const te = this.elements;
  7252. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  7253. const x2 = x + x, y2 = y + y, z2 = z + z;
  7254. const xx = x * x2, xy = x * y2, xz = x * z2;
  7255. const yy = y * y2, yz = y * z2, zz = z * z2;
  7256. const wx = w * x2, wy = w * y2, wz = w * z2;
  7257. const sx = scale.x, sy = scale.y, sz = scale.z;
  7258. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  7259. te[ 1 ] = ( xy + wz ) * sx;
  7260. te[ 2 ] = ( xz - wy ) * sx;
  7261. te[ 3 ] = 0;
  7262. te[ 4 ] = ( xy - wz ) * sy;
  7263. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  7264. te[ 6 ] = ( yz + wx ) * sy;
  7265. te[ 7 ] = 0;
  7266. te[ 8 ] = ( xz + wy ) * sz;
  7267. te[ 9 ] = ( yz - wx ) * sz;
  7268. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  7269. te[ 11 ] = 0;
  7270. te[ 12 ] = position.x;
  7271. te[ 13 ] = position.y;
  7272. te[ 14 ] = position.z;
  7273. te[ 15 ] = 1;
  7274. return this;
  7275. }
  7276. /**
  7277. * Decomposes this matrix into its positon, rotation and scale components
  7278. * and provides the result in the given objects.
  7279. *
  7280. * Note: Not all matrices are decomposable in this way. For example, if an
  7281. * object has a non-uniformly scaled parent, then the object's world matrix
  7282. * may not be decomposable, and this method may not be appropriate.
  7283. *
  7284. * @param {Vector3} position - The position vector.
  7285. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7286. * @param {Vector3} scale - The scale vector.
  7287. * @return {Matrix4} A reference to this matrix.
  7288. */
  7289. decompose( position, quaternion, scale ) {
  7290. const te = this.elements;
  7291. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  7292. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  7293. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  7294. // if determine is negative, we need to invert one scale
  7295. const det = this.determinant();
  7296. if ( det < 0 ) sx = - sx;
  7297. position.x = te[ 12 ];
  7298. position.y = te[ 13 ];
  7299. position.z = te[ 14 ];
  7300. // scale the rotation part
  7301. _m1$4.copy( this );
  7302. const invSX = 1 / sx;
  7303. const invSY = 1 / sy;
  7304. const invSZ = 1 / sz;
  7305. _m1$4.elements[ 0 ] *= invSX;
  7306. _m1$4.elements[ 1 ] *= invSX;
  7307. _m1$4.elements[ 2 ] *= invSX;
  7308. _m1$4.elements[ 4 ] *= invSY;
  7309. _m1$4.elements[ 5 ] *= invSY;
  7310. _m1$4.elements[ 6 ] *= invSY;
  7311. _m1$4.elements[ 8 ] *= invSZ;
  7312. _m1$4.elements[ 9 ] *= invSZ;
  7313. _m1$4.elements[ 10 ] *= invSZ;
  7314. quaternion.setFromRotationMatrix( _m1$4 );
  7315. scale.x = sx;
  7316. scale.y = sy;
  7317. scale.z = sz;
  7318. return this;
  7319. }
  7320. /**
  7321. * Creates a perspective projection matrix. This is used internally by
  7322. * {@link PerspectiveCamera#updateProjectionMatrix}.
  7323. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7324. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7325. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7326. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7327. * @param {number} near - The distance from the camera to the near plane.
  7328. * @param {number} far - The distance from the camera to the far plane.
  7329. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7330. * @return {Matrix4} A reference to this matrix.
  7331. */
  7332. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7333. const te = this.elements;
  7334. const x = 2 * near / ( right - left );
  7335. const y = 2 * near / ( top - bottom );
  7336. const a = ( right + left ) / ( right - left );
  7337. const b = ( top + bottom ) / ( top - bottom );
  7338. let c, d;
  7339. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7340. c = - ( far + near ) / ( far - near );
  7341. d = ( -2 * far * near ) / ( far - near );
  7342. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7343. c = - far / ( far - near );
  7344. d = ( - far * near ) / ( far - near );
  7345. } else {
  7346. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  7347. }
  7348. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  7349. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  7350. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  7351. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  7352. return this;
  7353. }
  7354. /**
  7355. * Creates a orthographic projection matrix. This is used internally by
  7356. * {@link OrthographicCamera#updateProjectionMatrix}.
  7357. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7358. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7359. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7360. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7361. * @param {number} near - The distance from the camera to the near plane.
  7362. * @param {number} far - The distance from the camera to the far plane.
  7363. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7364. * @return {Matrix4} A reference to this matrix.
  7365. */
  7366. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7367. const te = this.elements;
  7368. const w = 1.0 / ( right - left );
  7369. const h = 1.0 / ( top - bottom );
  7370. const p = 1.0 / ( far - near );
  7371. const x = ( right + left ) * w;
  7372. const y = ( top + bottom ) * h;
  7373. let z, zInv;
  7374. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7375. z = ( far + near ) * p;
  7376. zInv = -2 * p;
  7377. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7378. z = near * p;
  7379. zInv = -1 * p;
  7380. } else {
  7381. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  7382. }
  7383. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  7384. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  7385. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  7386. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  7387. return this;
  7388. }
  7389. /**
  7390. * Returns `true` if this matrix is equal with the given one.
  7391. *
  7392. * @param {Matrix4} matrix - The matrix to test for equality.
  7393. * @return {boolean} Whether this matrix is equal with the given one.
  7394. */
  7395. equals( matrix ) {
  7396. const te = this.elements;
  7397. const me = matrix.elements;
  7398. for ( let i = 0; i < 16; i ++ ) {
  7399. if ( te[ i ] !== me[ i ] ) return false;
  7400. }
  7401. return true;
  7402. }
  7403. /**
  7404. * Sets the elements of the matrix from the given array.
  7405. *
  7406. * @param {Array<number>} array - The matrix elements in column-major order.
  7407. * @param {number} [offset=0] - Index of the first element in the array.
  7408. * @return {Matrix4} A reference to this matrix.
  7409. */
  7410. fromArray( array, offset = 0 ) {
  7411. for ( let i = 0; i < 16; i ++ ) {
  7412. this.elements[ i ] = array[ i + offset ];
  7413. }
  7414. return this;
  7415. }
  7416. /**
  7417. * Writes the elements of this matrix to the given array. If no array is provided,
  7418. * the method returns a new instance.
  7419. *
  7420. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  7421. * @param {number} [offset=0] - Index of the first element in the array.
  7422. * @return {Array<number>} The matrix elements in column-major order.
  7423. */
  7424. toArray( array = [], offset = 0 ) {
  7425. const te = this.elements;
  7426. array[ offset ] = te[ 0 ];
  7427. array[ offset + 1 ] = te[ 1 ];
  7428. array[ offset + 2 ] = te[ 2 ];
  7429. array[ offset + 3 ] = te[ 3 ];
  7430. array[ offset + 4 ] = te[ 4 ];
  7431. array[ offset + 5 ] = te[ 5 ];
  7432. array[ offset + 6 ] = te[ 6 ];
  7433. array[ offset + 7 ] = te[ 7 ];
  7434. array[ offset + 8 ] = te[ 8 ];
  7435. array[ offset + 9 ] = te[ 9 ];
  7436. array[ offset + 10 ] = te[ 10 ];
  7437. array[ offset + 11 ] = te[ 11 ];
  7438. array[ offset + 12 ] = te[ 12 ];
  7439. array[ offset + 13 ] = te[ 13 ];
  7440. array[ offset + 14 ] = te[ 14 ];
  7441. array[ offset + 15 ] = te[ 15 ];
  7442. return array;
  7443. }
  7444. }
  7445. const _v1$5 = /*@__PURE__*/ new Vector3();
  7446. const _m1$4 = /*@__PURE__*/ new Matrix4();
  7447. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  7448. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  7449. const _x = /*@__PURE__*/ new Vector3();
  7450. const _y = /*@__PURE__*/ new Vector3();
  7451. const _z = /*@__PURE__*/ new Vector3();
  7452. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  7453. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  7454. /**
  7455. * A class representing Euler angles.
  7456. *
  7457. * Euler angles describe a rotational transformation by rotating an object on
  7458. * its various axes in specified amounts per axis, and a specified axis
  7459. * order.
  7460. *
  7461. * Iterating through an instance will yield its components (x, y, z,
  7462. * order) in the corresponding order.
  7463. *
  7464. * ```js
  7465. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  7466. * const b = new THREE.Vector3( 1, 0, 1 );
  7467. * b.applyEuler(a);
  7468. * ```
  7469. */
  7470. class Euler {
  7471. /**
  7472. * Constructs a new euler instance.
  7473. *
  7474. * @param {number} [x=0] - The angle of the x axis in radians.
  7475. * @param {number} [y=0] - The angle of the y axis in radians.
  7476. * @param {number} [z=0] - The angle of the z axis in radians.
  7477. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  7478. */
  7479. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  7480. /**
  7481. * This flag can be used for type testing.
  7482. *
  7483. * @type {boolean}
  7484. * @readonly
  7485. * @default true
  7486. */
  7487. this.isEuler = true;
  7488. this._x = x;
  7489. this._y = y;
  7490. this._z = z;
  7491. this._order = order;
  7492. }
  7493. /**
  7494. * The angle of the x axis in radians.
  7495. *
  7496. * @type {number}
  7497. * @default 0
  7498. */
  7499. get x() {
  7500. return this._x;
  7501. }
  7502. set x( value ) {
  7503. this._x = value;
  7504. this._onChangeCallback();
  7505. }
  7506. /**
  7507. * The angle of the y axis in radians.
  7508. *
  7509. * @type {number}
  7510. * @default 0
  7511. */
  7512. get y() {
  7513. return this._y;
  7514. }
  7515. set y( value ) {
  7516. this._y = value;
  7517. this._onChangeCallback();
  7518. }
  7519. /**
  7520. * The angle of the z axis in radians.
  7521. *
  7522. * @type {number}
  7523. * @default 0
  7524. */
  7525. get z() {
  7526. return this._z;
  7527. }
  7528. set z( value ) {
  7529. this._z = value;
  7530. this._onChangeCallback();
  7531. }
  7532. /**
  7533. * A string representing the order that the rotations are applied.
  7534. *
  7535. * @type {string}
  7536. * @default 'XYZ'
  7537. */
  7538. get order() {
  7539. return this._order;
  7540. }
  7541. set order( value ) {
  7542. this._order = value;
  7543. this._onChangeCallback();
  7544. }
  7545. /**
  7546. * Sets the Euler components.
  7547. *
  7548. * @param {number} x - The angle of the x axis in radians.
  7549. * @param {number} y - The angle of the y axis in radians.
  7550. * @param {number} z - The angle of the z axis in radians.
  7551. * @param {string} [order] - A string representing the order that the rotations are applied.
  7552. * @return {Euler} A reference to this Euler instance.
  7553. */
  7554. set( x, y, z, order = this._order ) {
  7555. this._x = x;
  7556. this._y = y;
  7557. this._z = z;
  7558. this._order = order;
  7559. this._onChangeCallback();
  7560. return this;
  7561. }
  7562. /**
  7563. * Returns a new Euler instance with copied values from this instance.
  7564. *
  7565. * @return {Euler} A clone of this instance.
  7566. */
  7567. clone() {
  7568. return new this.constructor( this._x, this._y, this._z, this._order );
  7569. }
  7570. /**
  7571. * Copies the values of the given Euler instance to this instance.
  7572. *
  7573. * @param {Euler} euler - The Euler instance to copy.
  7574. * @return {Euler} A reference to this Euler instance.
  7575. */
  7576. copy( euler ) {
  7577. this._x = euler._x;
  7578. this._y = euler._y;
  7579. this._z = euler._z;
  7580. this._order = euler._order;
  7581. this._onChangeCallback();
  7582. return this;
  7583. }
  7584. /**
  7585. * Sets the angles of this Euler instance from a pure rotation matrix.
  7586. *
  7587. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  7588. * @param {string} [order] - A string representing the order that the rotations are applied.
  7589. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7590. * @return {Euler} A reference to this Euler instance.
  7591. */
  7592. setFromRotationMatrix( m, order = this._order, update = true ) {
  7593. const te = m.elements;
  7594. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  7595. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  7596. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7597. switch ( order ) {
  7598. case 'XYZ':
  7599. this._y = Math.asin( clamp( m13, -1, 1 ) );
  7600. if ( Math.abs( m13 ) < 0.9999999 ) {
  7601. this._x = Math.atan2( - m23, m33 );
  7602. this._z = Math.atan2( - m12, m11 );
  7603. } else {
  7604. this._x = Math.atan2( m32, m22 );
  7605. this._z = 0;
  7606. }
  7607. break;
  7608. case 'YXZ':
  7609. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  7610. if ( Math.abs( m23 ) < 0.9999999 ) {
  7611. this._y = Math.atan2( m13, m33 );
  7612. this._z = Math.atan2( m21, m22 );
  7613. } else {
  7614. this._y = Math.atan2( - m31, m11 );
  7615. this._z = 0;
  7616. }
  7617. break;
  7618. case 'ZXY':
  7619. this._x = Math.asin( clamp( m32, -1, 1 ) );
  7620. if ( Math.abs( m32 ) < 0.9999999 ) {
  7621. this._y = Math.atan2( - m31, m33 );
  7622. this._z = Math.atan2( - m12, m22 );
  7623. } else {
  7624. this._y = 0;
  7625. this._z = Math.atan2( m21, m11 );
  7626. }
  7627. break;
  7628. case 'ZYX':
  7629. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  7630. if ( Math.abs( m31 ) < 0.9999999 ) {
  7631. this._x = Math.atan2( m32, m33 );
  7632. this._z = Math.atan2( m21, m11 );
  7633. } else {
  7634. this._x = 0;
  7635. this._z = Math.atan2( - m12, m22 );
  7636. }
  7637. break;
  7638. case 'YZX':
  7639. this._z = Math.asin( clamp( m21, -1, 1 ) );
  7640. if ( Math.abs( m21 ) < 0.9999999 ) {
  7641. this._x = Math.atan2( - m23, m22 );
  7642. this._y = Math.atan2( - m31, m11 );
  7643. } else {
  7644. this._x = 0;
  7645. this._y = Math.atan2( m13, m33 );
  7646. }
  7647. break;
  7648. case 'XZY':
  7649. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  7650. if ( Math.abs( m12 ) < 0.9999999 ) {
  7651. this._x = Math.atan2( m32, m22 );
  7652. this._y = Math.atan2( m13, m11 );
  7653. } else {
  7654. this._x = Math.atan2( - m23, m33 );
  7655. this._y = 0;
  7656. }
  7657. break;
  7658. default:
  7659. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  7660. }
  7661. this._order = order;
  7662. if ( update === true ) this._onChangeCallback();
  7663. return this;
  7664. }
  7665. /**
  7666. * Sets the angles of this Euler instance from a normalized quaternion.
  7667. *
  7668. * @param {Quaternion} q - A normalized Quaternion.
  7669. * @param {string} [order] - A string representing the order that the rotations are applied.
  7670. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7671. * @return {Euler} A reference to this Euler instance.
  7672. */
  7673. setFromQuaternion( q, order, update ) {
  7674. _matrix$2.makeRotationFromQuaternion( q );
  7675. return this.setFromRotationMatrix( _matrix$2, order, update );
  7676. }
  7677. /**
  7678. * Sets the angles of this Euler instance from the given vector.
  7679. *
  7680. * @param {Vector3} v - The vector.
  7681. * @param {string} [order] - A string representing the order that the rotations are applied.
  7682. * @return {Euler} A reference to this Euler instance.
  7683. */
  7684. setFromVector3( v, order = this._order ) {
  7685. return this.set( v.x, v.y, v.z, order );
  7686. }
  7687. /**
  7688. * Resets the euler angle with a new order by creating a quaternion from this
  7689. * euler angle and then setting this euler angle with the quaternion and the
  7690. * new order.
  7691. *
  7692. * Warning: This discards revolution information.
  7693. *
  7694. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  7695. * @return {Euler} A reference to this Euler instance.
  7696. */
  7697. reorder( newOrder ) {
  7698. _quaternion$3.setFromEuler( this );
  7699. return this.setFromQuaternion( _quaternion$3, newOrder );
  7700. }
  7701. /**
  7702. * Returns `true` if this Euler instance is equal with the given one.
  7703. *
  7704. * @param {Euler} euler - The Euler instance to test for equality.
  7705. * @return {boolean} Whether this Euler instance is equal with the given one.
  7706. */
  7707. equals( euler ) {
  7708. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  7709. }
  7710. /**
  7711. * Sets this Euler instance's components to values from the given array. The first three
  7712. * entries of the array are assign to the x,y and z components. An optinal fourth entry
  7713. * defines the Euler order.
  7714. *
  7715. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  7716. * @return {Euler} A reference to this Euler instance.
  7717. */
  7718. fromArray( array ) {
  7719. this._x = array[ 0 ];
  7720. this._y = array[ 1 ];
  7721. this._z = array[ 2 ];
  7722. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  7723. this._onChangeCallback();
  7724. return this;
  7725. }
  7726. /**
  7727. * Writes the components of this Euler instance to the given array. If no array is provided,
  7728. * the method returns a new instance.
  7729. *
  7730. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  7731. * @param {number} [offset=0] - Index of the first element in the array.
  7732. * @return {Array<number,number,number,string>} The Euler components.
  7733. */
  7734. toArray( array = [], offset = 0 ) {
  7735. array[ offset ] = this._x;
  7736. array[ offset + 1 ] = this._y;
  7737. array[ offset + 2 ] = this._z;
  7738. array[ offset + 3 ] = this._order;
  7739. return array;
  7740. }
  7741. _onChange( callback ) {
  7742. this._onChangeCallback = callback;
  7743. return this;
  7744. }
  7745. _onChangeCallback() {}
  7746. *[ Symbol.iterator ]() {
  7747. yield this._x;
  7748. yield this._y;
  7749. yield this._z;
  7750. yield this._order;
  7751. }
  7752. }
  7753. /**
  7754. * The default Euler angle order.
  7755. *
  7756. * @static
  7757. * @type {string}
  7758. * @default 'XYZ'
  7759. */
  7760. Euler.DEFAULT_ORDER = 'XYZ';
  7761. class Layers {
  7762. constructor() {
  7763. this.mask = 1 | 0;
  7764. }
  7765. set( channel ) {
  7766. this.mask = ( 1 << channel | 0 ) >>> 0;
  7767. }
  7768. enable( channel ) {
  7769. this.mask |= 1 << channel | 0;
  7770. }
  7771. enableAll() {
  7772. this.mask = 0xffffffff | 0;
  7773. }
  7774. toggle( channel ) {
  7775. this.mask ^= 1 << channel | 0;
  7776. }
  7777. disable( channel ) {
  7778. this.mask &= ~ ( 1 << channel | 0 );
  7779. }
  7780. disableAll() {
  7781. this.mask = 0;
  7782. }
  7783. test( layers ) {
  7784. return ( this.mask & layers.mask ) !== 0;
  7785. }
  7786. isEnabled( channel ) {
  7787. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  7788. }
  7789. }
  7790. let _object3DId = 0;
  7791. const _v1$4 = /*@__PURE__*/ new Vector3();
  7792. const _q1 = /*@__PURE__*/ new Quaternion();
  7793. const _m1$3 = /*@__PURE__*/ new Matrix4();
  7794. const _target = /*@__PURE__*/ new Vector3();
  7795. const _position$3 = /*@__PURE__*/ new Vector3();
  7796. const _scale$2 = /*@__PURE__*/ new Vector3();
  7797. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  7798. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  7799. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  7800. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  7801. /**
  7802. * Fires when the object has been added to its parent object.
  7803. *
  7804. * @event Object3D#added
  7805. * @type {Object}
  7806. */
  7807. const _addedEvent = { type: 'added' };
  7808. /**
  7809. * Fires when the object has been removed from its parent object.
  7810. *
  7811. * @event Object3D#removed
  7812. * @type {Object}
  7813. */
  7814. const _removedEvent = { type: 'removed' };
  7815. /**
  7816. * Fires when a new child object has been added.
  7817. *
  7818. * @event Object3D#childadded
  7819. * @type {Object}
  7820. */
  7821. const _childaddedEvent = { type: 'childadded', child: null };
  7822. /**
  7823. * Fires when a new child object has been added.
  7824. *
  7825. * @event Object3D#childremoved
  7826. * @type {Object}
  7827. */
  7828. const _childremovedEvent = { type: 'childremoved', child: null };
  7829. /**
  7830. * This is the base class for most objects in three.js and provides a set of
  7831. * properties and methods for manipulating objects in 3D space.
  7832. *
  7833. * @augments EventDispatcher
  7834. */
  7835. class Object3D extends EventDispatcher {
  7836. /**
  7837. * Constructs a new 3D object.
  7838. */
  7839. constructor() {
  7840. super();
  7841. /**
  7842. * This flag can be used for type testing.
  7843. *
  7844. * @type {boolean}
  7845. * @readonly
  7846. * @default true
  7847. */
  7848. this.isObject3D = true;
  7849. /**
  7850. * The ID of the 3D object.
  7851. *
  7852. * @name Object3D#id
  7853. * @type {number}
  7854. * @readonly
  7855. */
  7856. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  7857. /**
  7858. * The UUID of the 3D object.
  7859. *
  7860. * @type {string}
  7861. * @readonly
  7862. */
  7863. this.uuid = generateUUID();
  7864. /**
  7865. * The name of the 3D object.
  7866. *
  7867. * @type {string}
  7868. */
  7869. this.name = '';
  7870. /**
  7871. * The type property is used for detecting the object type
  7872. * in context of serialization/deserialization.
  7873. *
  7874. * @type {string}
  7875. * @readonly
  7876. */
  7877. this.type = 'Object3D';
  7878. /**
  7879. * A reference to the parent object.
  7880. *
  7881. * @type {?Object3D}
  7882. * @default null
  7883. */
  7884. this.parent = null;
  7885. /**
  7886. * An array holding the child 3D objects of this instance.
  7887. *
  7888. * @type {Array<Object3D>}
  7889. */
  7890. this.children = [];
  7891. /**
  7892. * Defines the `up` direction of the 3D object which influences
  7893. * the orientation via methods like {@link Object3D#lookAt}.
  7894. *
  7895. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  7896. *
  7897. * @type {Vector3}
  7898. */
  7899. this.up = Object3D.DEFAULT_UP.clone();
  7900. const position = new Vector3();
  7901. const rotation = new Euler();
  7902. const quaternion = new Quaternion();
  7903. const scale = new Vector3( 1, 1, 1 );
  7904. function onRotationChange() {
  7905. quaternion.setFromEuler( rotation, false );
  7906. }
  7907. function onQuaternionChange() {
  7908. rotation.setFromQuaternion( quaternion, undefined, false );
  7909. }
  7910. rotation._onChange( onRotationChange );
  7911. quaternion._onChange( onQuaternionChange );
  7912. Object.defineProperties( this, {
  7913. /**
  7914. * Represents the object's local position.
  7915. *
  7916. * @name Object3D#position
  7917. * @type {Vector3}
  7918. * @default (0,0,0)
  7919. */
  7920. position: {
  7921. configurable: true,
  7922. enumerable: true,
  7923. value: position
  7924. },
  7925. /**
  7926. * Represents the object's local rotation as Euler angles, in radians.
  7927. *
  7928. * @name Object3D#rotation
  7929. * @type {Euler}
  7930. * @default (0,0,0)
  7931. */
  7932. rotation: {
  7933. configurable: true,
  7934. enumerable: true,
  7935. value: rotation
  7936. },
  7937. /**
  7938. * Represents the object's local rotation as Quaterions.
  7939. *
  7940. * @name Object3D#quaternion
  7941. * @type {Quaternion}
  7942. */
  7943. quaternion: {
  7944. configurable: true,
  7945. enumerable: true,
  7946. value: quaternion
  7947. },
  7948. /**
  7949. * Represents the object's local scale.
  7950. *
  7951. * @name Object3D#scale
  7952. * @type {Vector3}
  7953. * @default (1,1,1)
  7954. */
  7955. scale: {
  7956. configurable: true,
  7957. enumerable: true,
  7958. value: scale
  7959. },
  7960. /**
  7961. * Represents the object's model-view matrix.
  7962. *
  7963. * @name Object3D#modelViewMatrix
  7964. * @type {Matrix4}
  7965. */
  7966. modelViewMatrix: {
  7967. value: new Matrix4()
  7968. },
  7969. /**
  7970. * Represents the object's normal matrix.
  7971. *
  7972. * @name Object3D#normalMatrix
  7973. * @type {Matrix3}
  7974. */
  7975. normalMatrix: {
  7976. value: new Matrix3()
  7977. }
  7978. } );
  7979. /**
  7980. * Represents the object's transformation matrix in local space.
  7981. *
  7982. * @type {Matrix4}
  7983. */
  7984. this.matrix = new Matrix4();
  7985. /**
  7986. * Represents the object's transformation matrix in world space.
  7987. * If the 3D object has no parent, then it's identical to the local transformation matrix
  7988. *
  7989. * @type {Matrix4}
  7990. */
  7991. this.matrixWorld = new Matrix4();
  7992. /**
  7993. * When set to `true`, the engine automatically computes the local matrix from position,
  7994. * rotation and scale every frame.
  7995. *
  7996. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  7997. *
  7998. * @type {boolean}
  7999. * @default true
  8000. */
  8001. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  8002. /**
  8003. * When set to `true`, the engine automatically computes the world matrix from the current local
  8004. * matrix and the object's transformation hierarchy.
  8005. *
  8006. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  8007. *
  8008. * @type {boolean}
  8009. * @default true
  8010. */
  8011. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  8012. /**
  8013. * When set to `true`, it calculates the world matrix in that frame and resets this property
  8014. * to `false`.
  8015. *
  8016. * @type {boolean}
  8017. * @default false
  8018. */
  8019. this.matrixWorldNeedsUpdate = false;
  8020. /**
  8021. * The layer membership of the 3D object. The 3D object is only visible if it has
  8022. * at least one layer in common with the camera in use. This property can also be
  8023. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  8024. *
  8025. * @type {Layers}
  8026. */
  8027. this.layers = new Layers();
  8028. /**
  8029. * When set to `true`, the 3D object gets rendered.
  8030. *
  8031. * @type {boolean}
  8032. * @default true
  8033. */
  8034. this.visible = true;
  8035. /**
  8036. * When set to `true`, the 3D object gets rendered into shadow maps.
  8037. *
  8038. * @type {boolean}
  8039. * @default false
  8040. */
  8041. this.castShadow = false;
  8042. /**
  8043. * When set to `true`, the 3D object is affected by shadows in the scene.
  8044. *
  8045. * @type {boolean}
  8046. * @default false
  8047. */
  8048. this.receiveShadow = false;
  8049. /**
  8050. * When set to `true`, the 3D object is honored by view frustum culling.
  8051. *
  8052. * @type {boolean}
  8053. * @default true
  8054. */
  8055. this.frustumCulled = true;
  8056. /**
  8057. * This value allows the default rendering order of scene graph objects to be
  8058. * overridden although opaque and transparent objects remain sorted independently.
  8059. * When this property is set for an instance of {@link Group},all descendants
  8060. * objects will be sorted and rendered together. Sorting is from lowest to highest
  8061. * render order.
  8062. *
  8063. * @type {number}
  8064. * @default 0
  8065. */
  8066. this.renderOrder = 0;
  8067. /**
  8068. * An array holding the animation clips of the 3D object.
  8069. *
  8070. * @type {Array<AnimationClip>}
  8071. */
  8072. this.animations = [];
  8073. /**
  8074. * An object that can be used to store custom data about the 3D object. It
  8075. * should not hold references to functions as these will not be cloned.
  8076. *
  8077. * @type {Object}
  8078. */
  8079. this.userData = {};
  8080. }
  8081. /**
  8082. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  8083. *
  8084. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8085. * @param {Object3D} object - The 3D object.
  8086. * @param {Camera} camera - The camera that is used to render the scene.
  8087. * @param {Camera} shadowCamera - The shadow camera.
  8088. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8089. * @param {Material} depthMaterial - The depth material.
  8090. * @param {Object} group - The geometry group data.
  8091. */
  8092. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8093. /**
  8094. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  8095. *
  8096. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8097. * @param {Object3D} object - The 3D object.
  8098. * @param {Camera} camera - The camera that is used to render the scene.
  8099. * @param {Camera} shadowCamera - The shadow camera.
  8100. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8101. * @param {Material} depthMaterial - The depth material.
  8102. * @param {Object} group - The geometry group data.
  8103. */
  8104. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8105. /**
  8106. * A callback that is executed immediately before a 3D object is rendered.
  8107. *
  8108. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8109. * @param {Object3D} object - The 3D object.
  8110. * @param {Camera} camera - The camera that is used to render the scene.
  8111. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8112. * @param {Material} material - The 3D object's material.
  8113. * @param {Object} group - The geometry group data.
  8114. */
  8115. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8116. /**
  8117. * A callback that is executed immediately after a 3D object is rendered.
  8118. *
  8119. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8120. * @param {Object3D} object - The 3D object.
  8121. * @param {Camera} camera - The camera that is used to render the scene.
  8122. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8123. * @param {Material} material - The 3D object's material.
  8124. * @param {Object} group - The geometry group data.
  8125. */
  8126. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8127. /**
  8128. * Applies the given transformation matrix to the object and updates the object's position,
  8129. * rotation and scale.
  8130. *
  8131. * @param {Matrix4} matrix - The transformation matrix.
  8132. */
  8133. applyMatrix4( matrix ) {
  8134. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8135. this.matrix.premultiply( matrix );
  8136. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8137. }
  8138. /**
  8139. * Applies a rotation represented by given the quaternion to the 3D object.
  8140. *
  8141. * @param {Quaternion} q - The quaterion.
  8142. * @return {Object3D} A reference to this instance.
  8143. */
  8144. applyQuaternion( q ) {
  8145. this.quaternion.premultiply( q );
  8146. return this;
  8147. }
  8148. /**
  8149. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  8150. *
  8151. * @param {Vector3} axis - The (normalized) axis vector.
  8152. * @param {number} angle - The angle in radians.
  8153. */
  8154. setRotationFromAxisAngle( axis, angle ) {
  8155. // assumes axis is normalized
  8156. this.quaternion.setFromAxisAngle( axis, angle );
  8157. }
  8158. /**
  8159. * Sets the given rotation represented as Euler angles to the 3D object.
  8160. *
  8161. * @param {Euler} euler - The Euler angles.
  8162. */
  8163. setRotationFromEuler( euler ) {
  8164. this.quaternion.setFromEuler( euler, true );
  8165. }
  8166. /**
  8167. * Sets the given rotation represented as rotation matrix to the 3D object.
  8168. *
  8169. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  8170. * a pure rotation matrix (i.e, unscaled).
  8171. */
  8172. setRotationFromMatrix( m ) {
  8173. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8174. this.quaternion.setFromRotationMatrix( m );
  8175. }
  8176. /**
  8177. * Sets the given rotation represented as a Quanterion to the 3D object.
  8178. *
  8179. * @param {Quaternion} q - The Quanterion
  8180. */
  8181. setRotationFromQuaternion( q ) {
  8182. // assumes q is normalized
  8183. this.quaternion.copy( q );
  8184. }
  8185. /**
  8186. * Rotates the 3D object along an axis in local space.
  8187. *
  8188. * @param {Vector3} axis - The (normalized) axis vector.
  8189. * @param {number} angle - The angle in radians.
  8190. * @return {Object3D} A reference to this instance.
  8191. */
  8192. rotateOnAxis( axis, angle ) {
  8193. // rotate object on axis in object space
  8194. // axis is assumed to be normalized
  8195. _q1.setFromAxisAngle( axis, angle );
  8196. this.quaternion.multiply( _q1 );
  8197. return this;
  8198. }
  8199. /**
  8200. * Rotates the 3D object along an axis in world space.
  8201. *
  8202. * @param {Vector3} axis - The (normalized) axis vector.
  8203. * @param {number} angle - The angle in radians.
  8204. * @return {Object3D} A reference to this instance.
  8205. */
  8206. rotateOnWorldAxis( axis, angle ) {
  8207. // rotate object on axis in world space
  8208. // axis is assumed to be normalized
  8209. // method assumes no rotated parent
  8210. _q1.setFromAxisAngle( axis, angle );
  8211. this.quaternion.premultiply( _q1 );
  8212. return this;
  8213. }
  8214. /**
  8215. * Rotates the 3D object around its X axis in local space.
  8216. *
  8217. * @param {number} angle - The angle in radians.
  8218. * @return {Object3D} A reference to this instance.
  8219. */
  8220. rotateX( angle ) {
  8221. return this.rotateOnAxis( _xAxis, angle );
  8222. }
  8223. /**
  8224. * Rotates the 3D object around its Y axis in local space.
  8225. *
  8226. * @param {number} angle - The angle in radians.
  8227. * @return {Object3D} A reference to this instance.
  8228. */
  8229. rotateY( angle ) {
  8230. return this.rotateOnAxis( _yAxis, angle );
  8231. }
  8232. /**
  8233. * Rotates the 3D object around its Z axis in local space.
  8234. *
  8235. * @param {number} angle - The angle in radians.
  8236. * @return {Object3D} A reference to this instance.
  8237. */
  8238. rotateZ( angle ) {
  8239. return this.rotateOnAxis( _zAxis, angle );
  8240. }
  8241. /**
  8242. * Translate the 3D object by a distance along the given axis in local space.
  8243. *
  8244. * @param {Vector3} axis - The (normalized) axis vector.
  8245. * @param {number} distance - The distance in world units.
  8246. * @return {Object3D} A reference to this instance.
  8247. */
  8248. translateOnAxis( axis, distance ) {
  8249. // translate object by distance along axis in object space
  8250. // axis is assumed to be normalized
  8251. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  8252. this.position.add( _v1$4.multiplyScalar( distance ) );
  8253. return this;
  8254. }
  8255. /**
  8256. * Translate the 3D object by a distance along its X-axis in local space.
  8257. *
  8258. * @param {number} distance - The distance in world units.
  8259. * @return {Object3D} A reference to this instance.
  8260. */
  8261. translateX( distance ) {
  8262. return this.translateOnAxis( _xAxis, distance );
  8263. }
  8264. /**
  8265. * Translate the 3D object by a distance along its Y-axis in local space.
  8266. *
  8267. * @param {number} distance - The distance in world units.
  8268. * @return {Object3D} A reference to this instance.
  8269. */
  8270. translateY( distance ) {
  8271. return this.translateOnAxis( _yAxis, distance );
  8272. }
  8273. /**
  8274. * Translate the 3D object by a distance along its Z-axis in local space.
  8275. *
  8276. * @param {number} distance - The distance in world units.
  8277. * @return {Object3D} A reference to this instance.
  8278. */
  8279. translateZ( distance ) {
  8280. return this.translateOnAxis( _zAxis, distance );
  8281. }
  8282. /**
  8283. * Converts the given vector from this 3D object's local space to world space.
  8284. *
  8285. * @param {Vector3} vector - The vector to convert.
  8286. * @return {Vector3} The converted vector.
  8287. */
  8288. localToWorld( vector ) {
  8289. this.updateWorldMatrix( true, false );
  8290. return vector.applyMatrix4( this.matrixWorld );
  8291. }
  8292. /**
  8293. * Converts the given vector from this 3D object's word space to local space.
  8294. *
  8295. * @param {Vector3} vector - The vector to convert.
  8296. * @return {Vector3} The converted vector.
  8297. */
  8298. worldToLocal( vector ) {
  8299. this.updateWorldMatrix( true, false );
  8300. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  8301. }
  8302. /**
  8303. * Rotates the object to face a point in world space.
  8304. *
  8305. * This method does not support objects having non-uniformly-scaled parent(s).
  8306. *
  8307. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  8308. * @param {number} [y] - The y coordinate in world space.
  8309. * @param {number} [z] - The z coordinate in world space.
  8310. */
  8311. lookAt( x, y, z ) {
  8312. // This method does not support objects having non-uniformly-scaled parent(s)
  8313. if ( x.isVector3 ) {
  8314. _target.copy( x );
  8315. } else {
  8316. _target.set( x, y, z );
  8317. }
  8318. const parent = this.parent;
  8319. this.updateWorldMatrix( true, false );
  8320. _position$3.setFromMatrixPosition( this.matrixWorld );
  8321. if ( this.isCamera || this.isLight ) {
  8322. _m1$3.lookAt( _position$3, _target, this.up );
  8323. } else {
  8324. _m1$3.lookAt( _target, _position$3, this.up );
  8325. }
  8326. this.quaternion.setFromRotationMatrix( _m1$3 );
  8327. if ( parent ) {
  8328. _m1$3.extractRotation( parent.matrixWorld );
  8329. _q1.setFromRotationMatrix( _m1$3 );
  8330. this.quaternion.premultiply( _q1.invert() );
  8331. }
  8332. }
  8333. /**
  8334. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  8335. * objects may be added. Any current parent on an object passed in here will be
  8336. * removed, since an object can have at most one parent.
  8337. *
  8338. * @fires Object3D#added
  8339. * @fires Object3D#childadded
  8340. * @param {Object3D} object - The 3D object to add.
  8341. * @return {Object3D} A reference to this instance.
  8342. */
  8343. add( object ) {
  8344. if ( arguments.length > 1 ) {
  8345. for ( let i = 0; i < arguments.length; i ++ ) {
  8346. this.add( arguments[ i ] );
  8347. }
  8348. return this;
  8349. }
  8350. if ( object === this ) {
  8351. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  8352. return this;
  8353. }
  8354. if ( object && object.isObject3D ) {
  8355. object.removeFromParent();
  8356. object.parent = this;
  8357. this.children.push( object );
  8358. object.dispatchEvent( _addedEvent );
  8359. _childaddedEvent.child = object;
  8360. this.dispatchEvent( _childaddedEvent );
  8361. _childaddedEvent.child = null;
  8362. } else {
  8363. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  8364. }
  8365. return this;
  8366. }
  8367. /**
  8368. * Removes the given 3D object as child from this 3D object.
  8369. * An arbitrary number of objects may be removed.
  8370. *
  8371. * @fires Object3D#removed
  8372. * @fires Object3D#childremoved
  8373. * @param {Object3D} object - The 3D object to remove.
  8374. * @return {Object3D} A reference to this instance.
  8375. */
  8376. remove( object ) {
  8377. if ( arguments.length > 1 ) {
  8378. for ( let i = 0; i < arguments.length; i ++ ) {
  8379. this.remove( arguments[ i ] );
  8380. }
  8381. return this;
  8382. }
  8383. const index = this.children.indexOf( object );
  8384. if ( index !== -1 ) {
  8385. object.parent = null;
  8386. this.children.splice( index, 1 );
  8387. object.dispatchEvent( _removedEvent );
  8388. _childremovedEvent.child = object;
  8389. this.dispatchEvent( _childremovedEvent );
  8390. _childremovedEvent.child = null;
  8391. }
  8392. return this;
  8393. }
  8394. /**
  8395. * Removes this 3D object from its current parent.
  8396. *
  8397. * @fires Object3D#removed
  8398. * @fires Object3D#childremoved
  8399. * @return {Object3D} A reference to this instance.
  8400. */
  8401. removeFromParent() {
  8402. const parent = this.parent;
  8403. if ( parent !== null ) {
  8404. parent.remove( this );
  8405. }
  8406. return this;
  8407. }
  8408. /**
  8409. * Removes all child objects.
  8410. *
  8411. * @fires Object3D#removed
  8412. * @fires Object3D#childremoved
  8413. * @return {Object3D} A reference to this instance.
  8414. */
  8415. clear() {
  8416. return this.remove( ... this.children );
  8417. }
  8418. /**
  8419. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  8420. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  8421. *
  8422. * @fires Object3D#added
  8423. * @fires Object3D#childadded
  8424. * @param {Object3D} object - The 3D object to attach.
  8425. * @return {Object3D} A reference to this instance.
  8426. */
  8427. attach( object ) {
  8428. // adds object as a child of this, while maintaining the object's world transform
  8429. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  8430. this.updateWorldMatrix( true, false );
  8431. _m1$3.copy( this.matrixWorld ).invert();
  8432. if ( object.parent !== null ) {
  8433. object.parent.updateWorldMatrix( true, false );
  8434. _m1$3.multiply( object.parent.matrixWorld );
  8435. }
  8436. object.applyMatrix4( _m1$3 );
  8437. object.removeFromParent();
  8438. object.parent = this;
  8439. this.children.push( object );
  8440. object.updateWorldMatrix( false, true );
  8441. object.dispatchEvent( _addedEvent );
  8442. _childaddedEvent.child = object;
  8443. this.dispatchEvent( _childaddedEvent );
  8444. _childaddedEvent.child = null;
  8445. return this;
  8446. }
  8447. /**
  8448. * Searches through the 3D object and its children, starting with the 3D object
  8449. * itself, and returns the first with a matching ID.
  8450. *
  8451. * @param {number} id - The id.
  8452. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8453. */
  8454. getObjectById( id ) {
  8455. return this.getObjectByProperty( 'id', id );
  8456. }
  8457. /**
  8458. * Searches through the 3D object and its children, starting with the 3D object
  8459. * itself, and returns the first with a matching name.
  8460. *
  8461. * @param {string} name - The name.
  8462. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8463. */
  8464. getObjectByName( name ) {
  8465. return this.getObjectByProperty( 'name', name );
  8466. }
  8467. /**
  8468. * Searches through the 3D object and its children, starting with the 3D object
  8469. * itself, and returns the first with a matching property value.
  8470. *
  8471. * @param {string} name - The name of the property.
  8472. * @param {any} value - The value.
  8473. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8474. */
  8475. getObjectByProperty( name, value ) {
  8476. if ( this[ name ] === value ) return this;
  8477. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  8478. const child = this.children[ i ];
  8479. const object = child.getObjectByProperty( name, value );
  8480. if ( object !== undefined ) {
  8481. return object;
  8482. }
  8483. }
  8484. return undefined;
  8485. }
  8486. /**
  8487. * Searches through the 3D object and its children, starting with the 3D object
  8488. * itself, and returns all 3D objects with a matching property value.
  8489. *
  8490. * @param {string} name - The name of the property.
  8491. * @param {any} value - The value.
  8492. * @param {Array<Object3D>} result - The method stores the result in this array.
  8493. * @return {Array<Object3D>} The found 3D objects.
  8494. */
  8495. getObjectsByProperty( name, value, result = [] ) {
  8496. if ( this[ name ] === value ) result.push( this );
  8497. const children = this.children;
  8498. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8499. children[ i ].getObjectsByProperty( name, value, result );
  8500. }
  8501. return result;
  8502. }
  8503. /**
  8504. * Returns a vector representing the position of the 3D object in world space.
  8505. *
  8506. * @param {Vector3} target - The target vector the result is stored to.
  8507. * @return {Vector3} The 3D object's position in world space.
  8508. */
  8509. getWorldPosition( target ) {
  8510. this.updateWorldMatrix( true, false );
  8511. return target.setFromMatrixPosition( this.matrixWorld );
  8512. }
  8513. /**
  8514. * Returns a Quaternion representing the position of the 3D object in world space.
  8515. *
  8516. * @param {Quaternion} target - The target Quaternion the result is stored to.
  8517. * @return {Quaternion} The 3D object's rotation in world space.
  8518. */
  8519. getWorldQuaternion( target ) {
  8520. this.updateWorldMatrix( true, false );
  8521. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  8522. return target;
  8523. }
  8524. /**
  8525. * Returns a vector representing the scale of the 3D object in world space.
  8526. *
  8527. * @param {Vector3} target - The target vector the result is stored to.
  8528. * @return {Vector3} The 3D object's scale in world space.
  8529. */
  8530. getWorldScale( target ) {
  8531. this.updateWorldMatrix( true, false );
  8532. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  8533. return target;
  8534. }
  8535. /**
  8536. * Returns a vector representing the ("look") direction of the 3D object in world space.
  8537. *
  8538. * @param {Vector3} target - The target vector the result is stored to.
  8539. * @return {Vector3} The 3D object's direction in world space.
  8540. */
  8541. getWorldDirection( target ) {
  8542. this.updateWorldMatrix( true, false );
  8543. const e = this.matrixWorld.elements;
  8544. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  8545. }
  8546. /**
  8547. * Abstract method to get intersections between a casted ray and this
  8548. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  8549. * implement this method in order to use raycasting.
  8550. *
  8551. * @abstract
  8552. * @param {Raycaster} raycaster - The raycaster.
  8553. * @param {Array<Object>} intersects - An array holding the result of the method.
  8554. */
  8555. raycast( /* raycaster, intersects */ ) {}
  8556. /**
  8557. * Executes the callback on this 3D object and all descendants.
  8558. *
  8559. * Note: Modifying the scene graph inside the callback is discouraged.
  8560. *
  8561. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8562. */
  8563. traverse( callback ) {
  8564. callback( this );
  8565. const children = this.children;
  8566. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8567. children[ i ].traverse( callback );
  8568. }
  8569. }
  8570. /**
  8571. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  8572. * Descendants of invisible 3D objects are not traversed.
  8573. *
  8574. * Note: Modifying the scene graph inside the callback is discouraged.
  8575. *
  8576. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8577. */
  8578. traverseVisible( callback ) {
  8579. if ( this.visible === false ) return;
  8580. callback( this );
  8581. const children = this.children;
  8582. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8583. children[ i ].traverseVisible( callback );
  8584. }
  8585. }
  8586. /**
  8587. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  8588. *
  8589. * Note: Modifying the scene graph inside the callback is discouraged.
  8590. *
  8591. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8592. */
  8593. traverseAncestors( callback ) {
  8594. const parent = this.parent;
  8595. if ( parent !== null ) {
  8596. callback( parent );
  8597. parent.traverseAncestors( callback );
  8598. }
  8599. }
  8600. /**
  8601. * Updates the transformation matrix in local space by computing it from the current
  8602. * positon, rotation and scale values.
  8603. */
  8604. updateMatrix() {
  8605. this.matrix.compose( this.position, this.quaternion, this.scale );
  8606. this.matrixWorldNeedsUpdate = true;
  8607. }
  8608. /**
  8609. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  8610. *
  8611. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  8612. * local space. The computation of the local and world matrix can be controlled with the
  8613. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  8614. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  8615. *
  8616. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  8617. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  8618. */
  8619. updateMatrixWorld( force ) {
  8620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8621. if ( this.matrixWorldNeedsUpdate || force ) {
  8622. if ( this.matrixWorldAutoUpdate === true ) {
  8623. if ( this.parent === null ) {
  8624. this.matrixWorld.copy( this.matrix );
  8625. } else {
  8626. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8627. }
  8628. }
  8629. this.matrixWorldNeedsUpdate = false;
  8630. force = true;
  8631. }
  8632. // make sure descendants are updated if required
  8633. const children = this.children;
  8634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8635. const child = children[ i ];
  8636. child.updateMatrixWorld( force );
  8637. }
  8638. }
  8639. /**
  8640. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  8641. * update of ancestor and descendant nodes.
  8642. *
  8643. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  8644. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  8645. */
  8646. updateWorldMatrix( updateParents, updateChildren ) {
  8647. const parent = this.parent;
  8648. if ( updateParents === true && parent !== null ) {
  8649. parent.updateWorldMatrix( true, false );
  8650. }
  8651. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8652. if ( this.matrixWorldAutoUpdate === true ) {
  8653. if ( this.parent === null ) {
  8654. this.matrixWorld.copy( this.matrix );
  8655. } else {
  8656. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8657. }
  8658. }
  8659. // make sure descendants are updated
  8660. if ( updateChildren === true ) {
  8661. const children = this.children;
  8662. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8663. const child = children[ i ];
  8664. child.updateWorldMatrix( false, true );
  8665. }
  8666. }
  8667. }
  8668. /**
  8669. * Serializes the 3D object into JSON.
  8670. *
  8671. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  8672. * @return {Object} A JSON object representing the serialized 3D object.
  8673. * @see {@link ObjectLoader#parse}
  8674. */
  8675. toJSON( meta ) {
  8676. // meta is a string when called from JSON.stringify
  8677. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  8678. const output = {};
  8679. // meta is a hash used to collect geometries, materials.
  8680. // not providing it implies that this is the root object
  8681. // being serialized.
  8682. if ( isRootObject ) {
  8683. // initialize meta obj
  8684. meta = {
  8685. geometries: {},
  8686. materials: {},
  8687. textures: {},
  8688. images: {},
  8689. shapes: {},
  8690. skeletons: {},
  8691. animations: {},
  8692. nodes: {}
  8693. };
  8694. output.metadata = {
  8695. version: 4.6,
  8696. type: 'Object',
  8697. generator: 'Object3D.toJSON'
  8698. };
  8699. }
  8700. // standard Object3D serialization
  8701. const object = {};
  8702. object.uuid = this.uuid;
  8703. object.type = this.type;
  8704. if ( this.name !== '' ) object.name = this.name;
  8705. if ( this.castShadow === true ) object.castShadow = true;
  8706. if ( this.receiveShadow === true ) object.receiveShadow = true;
  8707. if ( this.visible === false ) object.visible = false;
  8708. if ( this.frustumCulled === false ) object.frustumCulled = false;
  8709. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  8710. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  8711. object.layers = this.layers.mask;
  8712. object.matrix = this.matrix.toArray();
  8713. object.up = this.up.toArray();
  8714. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  8715. // object specific properties
  8716. if ( this.isInstancedMesh ) {
  8717. object.type = 'InstancedMesh';
  8718. object.count = this.count;
  8719. object.instanceMatrix = this.instanceMatrix.toJSON();
  8720. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  8721. }
  8722. if ( this.isBatchedMesh ) {
  8723. object.type = 'BatchedMesh';
  8724. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  8725. object.sortObjects = this.sortObjects;
  8726. object.drawRanges = this._drawRanges;
  8727. object.reservedRanges = this._reservedRanges;
  8728. object.visibility = this._visibility;
  8729. object.active = this._active;
  8730. object.bounds = this._bounds.map( bound => ( {
  8731. boxInitialized: bound.boxInitialized,
  8732. boxMin: bound.box.min.toArray(),
  8733. boxMax: bound.box.max.toArray(),
  8734. sphereInitialized: bound.sphereInitialized,
  8735. sphereRadius: bound.sphere.radius,
  8736. sphereCenter: bound.sphere.center.toArray()
  8737. } ) );
  8738. object.maxInstanceCount = this._maxInstanceCount;
  8739. object.maxVertexCount = this._maxVertexCount;
  8740. object.maxIndexCount = this._maxIndexCount;
  8741. object.geometryInitialized = this._geometryInitialized;
  8742. object.geometryCount = this._geometryCount;
  8743. object.matricesTexture = this._matricesTexture.toJSON( meta );
  8744. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  8745. if ( this.boundingSphere !== null ) {
  8746. object.boundingSphere = {
  8747. center: object.boundingSphere.center.toArray(),
  8748. radius: object.boundingSphere.radius
  8749. };
  8750. }
  8751. if ( this.boundingBox !== null ) {
  8752. object.boundingBox = {
  8753. min: object.boundingBox.min.toArray(),
  8754. max: object.boundingBox.max.toArray()
  8755. };
  8756. }
  8757. }
  8758. //
  8759. function serialize( library, element ) {
  8760. if ( library[ element.uuid ] === undefined ) {
  8761. library[ element.uuid ] = element.toJSON( meta );
  8762. }
  8763. return element.uuid;
  8764. }
  8765. if ( this.isScene ) {
  8766. if ( this.background ) {
  8767. if ( this.background.isColor ) {
  8768. object.background = this.background.toJSON();
  8769. } else if ( this.background.isTexture ) {
  8770. object.background = this.background.toJSON( meta ).uuid;
  8771. }
  8772. }
  8773. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  8774. object.environment = this.environment.toJSON( meta ).uuid;
  8775. }
  8776. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  8777. object.geometry = serialize( meta.geometries, this.geometry );
  8778. const parameters = this.geometry.parameters;
  8779. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  8780. const shapes = parameters.shapes;
  8781. if ( Array.isArray( shapes ) ) {
  8782. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  8783. const shape = shapes[ i ];
  8784. serialize( meta.shapes, shape );
  8785. }
  8786. } else {
  8787. serialize( meta.shapes, shapes );
  8788. }
  8789. }
  8790. }
  8791. if ( this.isSkinnedMesh ) {
  8792. object.bindMode = this.bindMode;
  8793. object.bindMatrix = this.bindMatrix.toArray();
  8794. if ( this.skeleton !== undefined ) {
  8795. serialize( meta.skeletons, this.skeleton );
  8796. object.skeleton = this.skeleton.uuid;
  8797. }
  8798. }
  8799. if ( this.material !== undefined ) {
  8800. if ( Array.isArray( this.material ) ) {
  8801. const uuids = [];
  8802. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  8803. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  8804. }
  8805. object.material = uuids;
  8806. } else {
  8807. object.material = serialize( meta.materials, this.material );
  8808. }
  8809. }
  8810. //
  8811. if ( this.children.length > 0 ) {
  8812. object.children = [];
  8813. for ( let i = 0; i < this.children.length; i ++ ) {
  8814. object.children.push( this.children[ i ].toJSON( meta ).object );
  8815. }
  8816. }
  8817. //
  8818. if ( this.animations.length > 0 ) {
  8819. object.animations = [];
  8820. for ( let i = 0; i < this.animations.length; i ++ ) {
  8821. const animation = this.animations[ i ];
  8822. object.animations.push( serialize( meta.animations, animation ) );
  8823. }
  8824. }
  8825. if ( isRootObject ) {
  8826. const geometries = extractFromCache( meta.geometries );
  8827. const materials = extractFromCache( meta.materials );
  8828. const textures = extractFromCache( meta.textures );
  8829. const images = extractFromCache( meta.images );
  8830. const shapes = extractFromCache( meta.shapes );
  8831. const skeletons = extractFromCache( meta.skeletons );
  8832. const animations = extractFromCache( meta.animations );
  8833. const nodes = extractFromCache( meta.nodes );
  8834. if ( geometries.length > 0 ) output.geometries = geometries;
  8835. if ( materials.length > 0 ) output.materials = materials;
  8836. if ( textures.length > 0 ) output.textures = textures;
  8837. if ( images.length > 0 ) output.images = images;
  8838. if ( shapes.length > 0 ) output.shapes = shapes;
  8839. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  8840. if ( animations.length > 0 ) output.animations = animations;
  8841. if ( nodes.length > 0 ) output.nodes = nodes;
  8842. }
  8843. output.object = object;
  8844. return output;
  8845. // extract data from the cache hash
  8846. // remove metadata on each item
  8847. // and return as array
  8848. function extractFromCache( cache ) {
  8849. const values = [];
  8850. for ( const key in cache ) {
  8851. const data = cache[ key ];
  8852. delete data.metadata;
  8853. values.push( data );
  8854. }
  8855. return values;
  8856. }
  8857. }
  8858. /**
  8859. * Returns a new 3D object with copied values from this instance.
  8860. *
  8861. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  8862. * @return {Object3D} A clone of this instance.
  8863. */
  8864. clone( recursive ) {
  8865. return new this.constructor().copy( this, recursive );
  8866. }
  8867. /**
  8868. * Copies the values of the given 3D object to this instance.
  8869. *
  8870. * @param {Object3D} source - The 3D object to copy.
  8871. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  8872. * @return {Object3D} A reference to this instance.
  8873. */
  8874. copy( source, recursive = true ) {
  8875. this.name = source.name;
  8876. this.up.copy( source.up );
  8877. this.position.copy( source.position );
  8878. this.rotation.order = source.rotation.order;
  8879. this.quaternion.copy( source.quaternion );
  8880. this.scale.copy( source.scale );
  8881. this.matrix.copy( source.matrix );
  8882. this.matrixWorld.copy( source.matrixWorld );
  8883. this.matrixAutoUpdate = source.matrixAutoUpdate;
  8884. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  8885. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  8886. this.layers.mask = source.layers.mask;
  8887. this.visible = source.visible;
  8888. this.castShadow = source.castShadow;
  8889. this.receiveShadow = source.receiveShadow;
  8890. this.frustumCulled = source.frustumCulled;
  8891. this.renderOrder = source.renderOrder;
  8892. this.animations = source.animations.slice();
  8893. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  8894. if ( recursive === true ) {
  8895. for ( let i = 0; i < source.children.length; i ++ ) {
  8896. const child = source.children[ i ];
  8897. this.add( child.clone() );
  8898. }
  8899. }
  8900. return this;
  8901. }
  8902. }
  8903. /**
  8904. * The default up direction for objects, also used as the default
  8905. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  8906. *
  8907. * @static
  8908. * @type {Vector3}
  8909. * @default (0,1,0)
  8910. */
  8911. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8912. /**
  8913. * The default setting for {@link Object3D#matrixAutoUpdate} for
  8914. * newly created 3D objects.
  8915. *
  8916. * @static
  8917. * @type {boolean}
  8918. * @default true
  8919. */
  8920. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  8921. /**
  8922. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  8923. * newly created 3D objects.
  8924. *
  8925. * @static
  8926. * @type {boolean}
  8927. * @default true
  8928. */
  8929. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  8930. const _v0$2 = /*@__PURE__*/ new Vector3();
  8931. const _v1$3 = /*@__PURE__*/ new Vector3();
  8932. const _v2$2 = /*@__PURE__*/ new Vector3();
  8933. const _v3$2 = /*@__PURE__*/ new Vector3();
  8934. const _vab = /*@__PURE__*/ new Vector3();
  8935. const _vac = /*@__PURE__*/ new Vector3();
  8936. const _vbc = /*@__PURE__*/ new Vector3();
  8937. const _vap = /*@__PURE__*/ new Vector3();
  8938. const _vbp = /*@__PURE__*/ new Vector3();
  8939. const _vcp = /*@__PURE__*/ new Vector3();
  8940. const _v40 = /*@__PURE__*/ new Vector4();
  8941. const _v41 = /*@__PURE__*/ new Vector4();
  8942. const _v42 = /*@__PURE__*/ new Vector4();
  8943. /**
  8944. * A geometric triangle as defined by three vectors representing its three corners.
  8945. */
  8946. class Triangle {
  8947. /**
  8948. * Constructs a new triangle.
  8949. *
  8950. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  8951. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  8952. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  8953. */
  8954. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  8955. /**
  8956. * The first corner of the triangle.
  8957. *
  8958. * @type {Vector3}
  8959. */
  8960. this.a = a;
  8961. /**
  8962. * The second corner of the triangle.
  8963. *
  8964. * @type {Vector3}
  8965. */
  8966. this.b = b;
  8967. /**
  8968. * The third corner of the triangle.
  8969. *
  8970. * @type {Vector3}
  8971. */
  8972. this.c = c;
  8973. }
  8974. /**
  8975. * Computes the normal vector of a triangle.
  8976. *
  8977. * @param {Vector3} a - The first corner of the triangle.
  8978. * @param {Vector3} b - The second corner of the triangle.
  8979. * @param {Vector3} c - The third corner of the triangle.
  8980. * @param {Vector3} target - The target vector that is used to store the method's result.
  8981. * @return {Vector3} The triangle's normal.
  8982. */
  8983. static getNormal( a, b, c, target ) {
  8984. target.subVectors( c, b );
  8985. _v0$2.subVectors( a, b );
  8986. target.cross( _v0$2 );
  8987. const targetLengthSq = target.lengthSq();
  8988. if ( targetLengthSq > 0 ) {
  8989. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  8990. }
  8991. return target.set( 0, 0, 0 );
  8992. }
  8993. /**
  8994. * Copmutes a barycentric coordinates from the given vector.
  8995. * Returns `null` if the triangle is degenerate.
  8996. *
  8997. * @param {Vector3} point - A point in 3D space.
  8998. * @param {Vector3} a - The first corner of the triangle.
  8999. * @param {Vector3} b - The second corner of the triangle.
  9000. * @param {Vector3} c - The third corner of the triangle.
  9001. * @param {Vector3} target - The target vector that is used to store the method's result.
  9002. * @return {?Vector3} The barycentric coordinates for the given point
  9003. */
  9004. static getBarycoord( point, a, b, c, target ) {
  9005. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9006. _v0$2.subVectors( c, a );
  9007. _v1$3.subVectors( b, a );
  9008. _v2$2.subVectors( point, a );
  9009. const dot00 = _v0$2.dot( _v0$2 );
  9010. const dot01 = _v0$2.dot( _v1$3 );
  9011. const dot02 = _v0$2.dot( _v2$2 );
  9012. const dot11 = _v1$3.dot( _v1$3 );
  9013. const dot12 = _v1$3.dot( _v2$2 );
  9014. const denom = ( dot00 * dot11 - dot01 * dot01 );
  9015. // collinear or singular triangle
  9016. if ( denom === 0 ) {
  9017. target.set( 0, 0, 0 );
  9018. return null;
  9019. }
  9020. const invDenom = 1 / denom;
  9021. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9022. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9023. // barycentric coordinates must always sum to 1
  9024. return target.set( 1 - u - v, v, u );
  9025. }
  9026. /**
  9027. * Returns `true` if the given point, when projected onto the plane of the
  9028. * triangle, lies within the triangle.
  9029. *
  9030. * @param {Vector3} point - The point in 3D space to test.
  9031. * @param {Vector3} a - The first corner of the triangle.
  9032. * @param {Vector3} b - The second corner of the triangle.
  9033. * @param {Vector3} c - The third corner of the triangle.
  9034. * @return {boolean} Whether the given point, when projected onto the plane of the
  9035. * triangle, lies within the triangle or not.
  9036. */
  9037. static containsPoint( point, a, b, c ) {
  9038. // if the triangle is degenerate then we can't contain a point
  9039. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  9040. return false;
  9041. }
  9042. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  9043. }
  9044. /**
  9045. * Computes the value barycentrically interpolated for the given point on the
  9046. * triangle. Returns `null` if the triangle is degenerate.
  9047. *
  9048. * @param {Vector3} point - Position of interpolated point.
  9049. * @param {Vector3} p1 - The first corner of the triangle.
  9050. * @param {Vector3} p2 - The second corner of the triangle.
  9051. * @param {Vector3} p3 - The third corner of the triangle.
  9052. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9053. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9054. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9055. * @param {Vector3} target - The target vector that is used to store the method's result.
  9056. * @return {?Vector3} The interpolated value.
  9057. */
  9058. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  9059. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  9060. target.x = 0;
  9061. target.y = 0;
  9062. if ( 'z' in target ) target.z = 0;
  9063. if ( 'w' in target ) target.w = 0;
  9064. return null;
  9065. }
  9066. target.setScalar( 0 );
  9067. target.addScaledVector( v1, _v3$2.x );
  9068. target.addScaledVector( v2, _v3$2.y );
  9069. target.addScaledVector( v3, _v3$2.z );
  9070. return target;
  9071. }
  9072. /**
  9073. * Computes the value barycentrically interpolated for the given attribute and indices.
  9074. *
  9075. * @param {BufferAttribute} attr - The attribute to interpolate.
  9076. * @param {number} i1 - Index of first vertex.
  9077. * @param {number} i2 - Index of second vertex.
  9078. * @param {number} i3 - Index of third vertex.
  9079. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  9080. * @param {Vector3} target - The target vector that is used to store the method's result.
  9081. * @return {Vector3} The interpolated attribute value.
  9082. */
  9083. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  9084. _v40.setScalar( 0 );
  9085. _v41.setScalar( 0 );
  9086. _v42.setScalar( 0 );
  9087. _v40.fromBufferAttribute( attr, i1 );
  9088. _v41.fromBufferAttribute( attr, i2 );
  9089. _v42.fromBufferAttribute( attr, i3 );
  9090. target.setScalar( 0 );
  9091. target.addScaledVector( _v40, barycoord.x );
  9092. target.addScaledVector( _v41, barycoord.y );
  9093. target.addScaledVector( _v42, barycoord.z );
  9094. return target;
  9095. }
  9096. /**
  9097. * Returns `true` if the triangle is oriented towards the given direction.
  9098. *
  9099. * @param {Vector3} a - The first corner of the triangle.
  9100. * @param {Vector3} b - The second corner of the triangle.
  9101. * @param {Vector3} c - The third corner of the triangle.
  9102. * @param {Vector3} direction - The (normalized) direction vector.
  9103. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9104. */
  9105. static isFrontFacing( a, b, c, direction ) {
  9106. _v0$2.subVectors( c, b );
  9107. _v1$3.subVectors( a, b );
  9108. // strictly front facing
  9109. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  9110. }
  9111. /**
  9112. * Sets the triangle's vertices by copying the given values.
  9113. *
  9114. * @param {Vector3} a - The first corner of the triangle.
  9115. * @param {Vector3} b - The second corner of the triangle.
  9116. * @param {Vector3} c - The third corner of the triangle.
  9117. * @return {Triangle} A reference to this triangle.
  9118. */
  9119. set( a, b, c ) {
  9120. this.a.copy( a );
  9121. this.b.copy( b );
  9122. this.c.copy( c );
  9123. return this;
  9124. }
  9125. /**
  9126. * Sets the triangle's vertices by copying the given array values.
  9127. *
  9128. * @param {Array<Vector3>} points - An array with 3D points.
  9129. * @param {number} i0 - The array index representing the first corner of the triangle.
  9130. * @param {number} i1 - The array index representing the second corner of the triangle.
  9131. * @param {number} i2 - The array index representing the third corner of the triangle.
  9132. * @return {Triangle} A reference to this triangle.
  9133. */
  9134. setFromPointsAndIndices( points, i0, i1, i2 ) {
  9135. this.a.copy( points[ i0 ] );
  9136. this.b.copy( points[ i1 ] );
  9137. this.c.copy( points[ i2 ] );
  9138. return this;
  9139. }
  9140. /**
  9141. * Sets the triangle's vertices by copying the given attribute values.
  9142. *
  9143. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  9144. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  9145. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  9146. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  9147. * @return {Triangle} A reference to this triangle.
  9148. */
  9149. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  9150. this.a.fromBufferAttribute( attribute, i0 );
  9151. this.b.fromBufferAttribute( attribute, i1 );
  9152. this.c.fromBufferAttribute( attribute, i2 );
  9153. return this;
  9154. }
  9155. /**
  9156. * Returns a new triangle with copied values from this instance.
  9157. *
  9158. * @return {Triangle} A clone of this instance.
  9159. */
  9160. clone() {
  9161. return new this.constructor().copy( this );
  9162. }
  9163. /**
  9164. * Copies the values of the given triangle to this instance.
  9165. *
  9166. * @param {Triangle} triangle - The triangle to copy.
  9167. * @return {Triangle} A reference to this triangle.
  9168. */
  9169. copy( triangle ) {
  9170. this.a.copy( triangle.a );
  9171. this.b.copy( triangle.b );
  9172. this.c.copy( triangle.c );
  9173. return this;
  9174. }
  9175. /**
  9176. * Computes the area of the triangle.
  9177. *
  9178. * @return {number} The triangle's area.
  9179. */
  9180. getArea() {
  9181. _v0$2.subVectors( this.c, this.b );
  9182. _v1$3.subVectors( this.a, this.b );
  9183. return _v0$2.cross( _v1$3 ).length() * 0.5;
  9184. }
  9185. /**
  9186. * Computes the midpoint of the triangle.
  9187. *
  9188. * @param {Vector3} target - The target vector that is used to store the method's result.
  9189. * @return {Vector3} The triangle's midpoint.
  9190. */
  9191. getMidpoint( target ) {
  9192. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9193. }
  9194. /**
  9195. * Computes the normal of the triangle.
  9196. *
  9197. * @param {Vector3} target - The target vector that is used to store the method's result.
  9198. * @return {Vector3} The triangle's normal.
  9199. */
  9200. getNormal( target ) {
  9201. return Triangle.getNormal( this.a, this.b, this.c, target );
  9202. }
  9203. /**
  9204. * Computes a plane the triangle lies within.
  9205. *
  9206. * @param {Plane} target - The target vector that is used to store the method's result.
  9207. * @return {Plane} The plane the triangle lies within.
  9208. */
  9209. getPlane( target ) {
  9210. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  9211. }
  9212. /**
  9213. * Copmutes a barycentric coordinates from the given vector.
  9214. * Returns `null` if the triangle is degenerate.
  9215. *
  9216. * @param {Vector3} point - A point in 3D space.
  9217. * @param {Vector3} target - The target vector that is used to store the method's result.
  9218. * @return {?Vector3} The barycentric coordinates for the given point
  9219. */
  9220. getBarycoord( point, target ) {
  9221. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  9222. }
  9223. /**
  9224. * Computes the value barycentrically interpolated for the given point on the
  9225. * triangle. Returns `null` if the triangle is degenerate.
  9226. *
  9227. * @param {Vector3} point - Position of interpolated point.
  9228. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9229. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9230. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9231. * @param {Vector3} target - The target vector that is used to store the method's result.
  9232. * @return {?Vector3} The interpolated value.
  9233. */
  9234. getInterpolation( point, v1, v2, v3, target ) {
  9235. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  9236. }
  9237. /**
  9238. * Returns `true` if the given point, when projected onto the plane of the
  9239. * triangle, lies within the triangle.
  9240. *
  9241. * @param {Vector3} point - The point in 3D space to test.
  9242. * @return {boolean} Whether the given point, when projected onto the plane of the
  9243. * triangle, lies within the triangle or not.
  9244. */
  9245. containsPoint( point ) {
  9246. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9247. }
  9248. /**
  9249. * Returns `true` if the triangle is oriented towards the given direction.
  9250. *
  9251. * @param {Vector3} direction - The (normalized) direction vector.
  9252. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9253. */
  9254. isFrontFacing( direction ) {
  9255. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  9256. }
  9257. /**
  9258. * Returns `true` if this triangle intersects with the given box.
  9259. *
  9260. * @param {Box3} box - The box to intersect.
  9261. * @return {boolean} Whether this triangle intersects with the given box or not.
  9262. */
  9263. intersectsBox( box ) {
  9264. return box.intersectsTriangle( this );
  9265. }
  9266. /**
  9267. * Returns the closest point on the triangle to the given point.
  9268. *
  9269. * @param {Vector3} p - The point to compute the closest point for.
  9270. * @param {Vector3} target - The target vector that is used to store the method's result.
  9271. * @return {Vector3} The closest point on the triangle.
  9272. */
  9273. closestPointToPoint( p, target ) {
  9274. const a = this.a, b = this.b, c = this.c;
  9275. let v, w;
  9276. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  9277. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  9278. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  9279. // basically, we're distinguishing which of the voronoi regions of the triangle
  9280. // the point lies in with the minimum amount of redundant computation.
  9281. _vab.subVectors( b, a );
  9282. _vac.subVectors( c, a );
  9283. _vap.subVectors( p, a );
  9284. const d1 = _vab.dot( _vap );
  9285. const d2 = _vac.dot( _vap );
  9286. if ( d1 <= 0 && d2 <= 0 ) {
  9287. // vertex region of A; barycentric coords (1, 0, 0)
  9288. return target.copy( a );
  9289. }
  9290. _vbp.subVectors( p, b );
  9291. const d3 = _vab.dot( _vbp );
  9292. const d4 = _vac.dot( _vbp );
  9293. if ( d3 >= 0 && d4 <= d3 ) {
  9294. // vertex region of B; barycentric coords (0, 1, 0)
  9295. return target.copy( b );
  9296. }
  9297. const vc = d1 * d4 - d3 * d2;
  9298. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  9299. v = d1 / ( d1 - d3 );
  9300. // edge region of AB; barycentric coords (1-v, v, 0)
  9301. return target.copy( a ).addScaledVector( _vab, v );
  9302. }
  9303. _vcp.subVectors( p, c );
  9304. const d5 = _vab.dot( _vcp );
  9305. const d6 = _vac.dot( _vcp );
  9306. if ( d6 >= 0 && d5 <= d6 ) {
  9307. // vertex region of C; barycentric coords (0, 0, 1)
  9308. return target.copy( c );
  9309. }
  9310. const vb = d5 * d2 - d1 * d6;
  9311. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  9312. w = d2 / ( d2 - d6 );
  9313. // edge region of AC; barycentric coords (1-w, 0, w)
  9314. return target.copy( a ).addScaledVector( _vac, w );
  9315. }
  9316. const va = d3 * d6 - d5 * d4;
  9317. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  9318. _vbc.subVectors( c, b );
  9319. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  9320. // edge region of BC; barycentric coords (0, 1-w, w)
  9321. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  9322. }
  9323. // face region
  9324. const denom = 1 / ( va + vb + vc );
  9325. // u = va * denom
  9326. v = vb * denom;
  9327. w = vc * denom;
  9328. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  9329. }
  9330. /**
  9331. * Returns `true` if this triangle is equal with the given one.
  9332. *
  9333. * @param {Triangle} triangle - The triangle to test for equality.
  9334. * @return {boolean} Whether this triangle is equal with the given one.
  9335. */
  9336. equals( triangle ) {
  9337. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9338. }
  9339. }
  9340. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  9341. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  9342. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  9343. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  9344. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  9345. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  9346. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  9347. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  9348. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  9349. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  9350. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  9351. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  9352. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  9353. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  9354. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  9355. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  9356. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  9357. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  9358. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  9359. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  9360. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  9361. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  9362. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  9363. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  9364. const _hslA = { h: 0, s: 0, l: 0 };
  9365. const _hslB = { h: 0, s: 0, l: 0 };
  9366. function hue2rgb( p, q, t ) {
  9367. if ( t < 0 ) t += 1;
  9368. if ( t > 1 ) t -= 1;
  9369. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  9370. if ( t < 1 / 2 ) return q;
  9371. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  9372. return p;
  9373. }
  9374. /**
  9375. * A Color instance is represented by RGB components in the linear <i>working
  9376. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  9377. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  9378. * strings) are converted to the working color space automatically.
  9379. *
  9380. * ```js
  9381. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  9382. * const color = new THREE.Color().setHex( 0x112233 );
  9383. * ```
  9384. * Source color spaces may be specified explicitly, to ensure correct conversions.
  9385. * ```js
  9386. * // assumed already LinearSRGBColorSpace; no conversion
  9387. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  9388. *
  9389. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  9390. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  9391. * ```
  9392. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  9393. * see <i>Color management</i>. Iterating through a Color instance will yield
  9394. * its components (r, g, b) in the corresponding order. A Color can be initialised
  9395. * in any of the following ways:
  9396. * ```js
  9397. * //empty constructor - will default white
  9398. * const color1 = new THREE.Color();
  9399. *
  9400. * //Hexadecimal color (recommended)
  9401. * const color2 = new THREE.Color( 0xff0000 );
  9402. *
  9403. * //RGB string
  9404. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  9405. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  9406. *
  9407. * //X11 color name - all 140 color names are supported.
  9408. * //Note the lack of CamelCase in the name
  9409. * const color5 = new THREE.Color( 'skyblue' );
  9410. * //HSL string
  9411. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  9412. *
  9413. * //Separate RGB values between 0 and 1
  9414. * const color7 = new THREE.Color( 1, 0, 0 );
  9415. * ```
  9416. */
  9417. class Color {
  9418. /**
  9419. * Constructs a new color.
  9420. *
  9421. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  9422. * and that method is used throughout the rest of the documentation.
  9423. *
  9424. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9425. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9426. * @param {number} [g] - The green component.
  9427. * @param {number} [b] - The blue component.
  9428. */
  9429. constructor( r, g, b ) {
  9430. /**
  9431. * This flag can be used for type testing.
  9432. *
  9433. * @type {boolean}
  9434. * @readonly
  9435. * @default true
  9436. */
  9437. this.isColor = true;
  9438. /**
  9439. * The red component.
  9440. *
  9441. * @type {number}
  9442. * @default 1
  9443. */
  9444. this.r = 1;
  9445. /**
  9446. * The green component.
  9447. *
  9448. * @type {number}
  9449. * @default 1
  9450. */
  9451. this.g = 1;
  9452. /**
  9453. * The blue component.
  9454. *
  9455. * @type {number}
  9456. * @default 1
  9457. */
  9458. this.b = 1;
  9459. return this.set( r, g, b );
  9460. }
  9461. /**
  9462. * Sets the colors's components from the given values.
  9463. *
  9464. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9465. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9466. * @param {number} [g] - The green component.
  9467. * @param {number} [b] - The blue component.
  9468. * @return {Color} A reference to this color.
  9469. */
  9470. set( r, g, b ) {
  9471. if ( g === undefined && b === undefined ) {
  9472. // r is THREE.Color, hex or string
  9473. const value = r;
  9474. if ( value && value.isColor ) {
  9475. this.copy( value );
  9476. } else if ( typeof value === 'number' ) {
  9477. this.setHex( value );
  9478. } else if ( typeof value === 'string' ) {
  9479. this.setStyle( value );
  9480. }
  9481. } else {
  9482. this.setRGB( r, g, b );
  9483. }
  9484. return this;
  9485. }
  9486. /**
  9487. * Sets the colors's components to the given scalar value.
  9488. *
  9489. * @param {number} scalar - The scalar value.
  9490. * @return {Color} A reference to this color.
  9491. */
  9492. setScalar( scalar ) {
  9493. this.r = scalar;
  9494. this.g = scalar;
  9495. this.b = scalar;
  9496. return this;
  9497. }
  9498. /**
  9499. * Sets this color from a hexadecimal value.
  9500. *
  9501. * @param {number} hex - The hexadecimal value.
  9502. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9503. * @return {Color} A reference to this color.
  9504. */
  9505. setHex( hex, colorSpace = SRGBColorSpace ) {
  9506. hex = Math.floor( hex );
  9507. this.r = ( hex >> 16 & 255 ) / 255;
  9508. this.g = ( hex >> 8 & 255 ) / 255;
  9509. this.b = ( hex & 255 ) / 255;
  9510. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9511. return this;
  9512. }
  9513. /**
  9514. * Sets this color from RGB values.
  9515. *
  9516. * @param {number} r - Red channel value between `0.0` and `1.0`.
  9517. * @param {number} g - Green channel value between `0.0` and `1.0`.
  9518. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  9519. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9520. * @return {Color} A reference to this color.
  9521. */
  9522. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  9523. this.r = r;
  9524. this.g = g;
  9525. this.b = b;
  9526. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9527. return this;
  9528. }
  9529. /**
  9530. * Sets this color from RGB values.
  9531. *
  9532. * @param {number} h - Hue value between `0.0` and `1.0`.
  9533. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9534. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9535. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9536. * @return {Color} A reference to this color.
  9537. */
  9538. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  9539. // h,s,l ranges are in 0.0 - 1.0
  9540. h = euclideanModulo( h, 1 );
  9541. s = clamp( s, 0, 1 );
  9542. l = clamp( l, 0, 1 );
  9543. if ( s === 0 ) {
  9544. this.r = this.g = this.b = l;
  9545. } else {
  9546. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  9547. const q = ( 2 * l ) - p;
  9548. this.r = hue2rgb( q, p, h + 1 / 3 );
  9549. this.g = hue2rgb( q, p, h );
  9550. this.b = hue2rgb( q, p, h - 1 / 3 );
  9551. }
  9552. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9553. return this;
  9554. }
  9555. /**
  9556. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  9557. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  9558. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  9559. * all 140 color names are supported).
  9560. *
  9561. * @param {string} style - Color as a CSS-style string.
  9562. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9563. * @return {Color} A reference to this color.
  9564. */
  9565. setStyle( style, colorSpace = SRGBColorSpace ) {
  9566. function handleAlpha( string ) {
  9567. if ( string === undefined ) return;
  9568. if ( parseFloat( string ) < 1 ) {
  9569. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  9570. }
  9571. }
  9572. let m;
  9573. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  9574. // rgb / hsl
  9575. let color;
  9576. const name = m[ 1 ];
  9577. const components = m[ 2 ];
  9578. switch ( name ) {
  9579. case 'rgb':
  9580. case 'rgba':
  9581. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9582. // rgb(255,0,0) rgba(255,0,0,0.5)
  9583. handleAlpha( color[ 4 ] );
  9584. return this.setRGB(
  9585. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  9586. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  9587. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  9588. colorSpace
  9589. );
  9590. }
  9591. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9592. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  9593. handleAlpha( color[ 4 ] );
  9594. return this.setRGB(
  9595. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  9596. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  9597. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  9598. colorSpace
  9599. );
  9600. }
  9601. break;
  9602. case 'hsl':
  9603. case 'hsla':
  9604. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9605. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  9606. handleAlpha( color[ 4 ] );
  9607. return this.setHSL(
  9608. parseFloat( color[ 1 ] ) / 360,
  9609. parseFloat( color[ 2 ] ) / 100,
  9610. parseFloat( color[ 3 ] ) / 100,
  9611. colorSpace
  9612. );
  9613. }
  9614. break;
  9615. default:
  9616. console.warn( 'THREE.Color: Unknown color model ' + style );
  9617. }
  9618. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  9619. // hex color
  9620. const hex = m[ 1 ];
  9621. const size = hex.length;
  9622. if ( size === 3 ) {
  9623. // #ff0
  9624. return this.setRGB(
  9625. parseInt( hex.charAt( 0 ), 16 ) / 15,
  9626. parseInt( hex.charAt( 1 ), 16 ) / 15,
  9627. parseInt( hex.charAt( 2 ), 16 ) / 15,
  9628. colorSpace
  9629. );
  9630. } else if ( size === 6 ) {
  9631. // #ff0000
  9632. return this.setHex( parseInt( hex, 16 ), colorSpace );
  9633. } else {
  9634. console.warn( 'THREE.Color: Invalid hex color ' + style );
  9635. }
  9636. } else if ( style && style.length > 0 ) {
  9637. return this.setColorName( style, colorSpace );
  9638. }
  9639. return this;
  9640. }
  9641. /**
  9642. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  9643. * you don't need the other CSS-style formats.
  9644. *
  9645. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  9646. * ```js
  9647. * Color.NAMES.aliceblue // returns 0xF0F8FF
  9648. * ```
  9649. *
  9650. * @param {string} style - The color name.
  9651. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9652. * @return {Color} A reference to this color.
  9653. */
  9654. setColorName( style, colorSpace = SRGBColorSpace ) {
  9655. // color keywords
  9656. const hex = _colorKeywords[ style.toLowerCase() ];
  9657. if ( hex !== undefined ) {
  9658. // red
  9659. this.setHex( hex, colorSpace );
  9660. } else {
  9661. // unknown color
  9662. console.warn( 'THREE.Color: Unknown color ' + style );
  9663. }
  9664. return this;
  9665. }
  9666. /**
  9667. * Returns a new color with copied values from this instance.
  9668. *
  9669. * @return {Color} A clone of this instance.
  9670. */
  9671. clone() {
  9672. return new this.constructor( this.r, this.g, this.b );
  9673. }
  9674. /**
  9675. * Copies the values of the given color to this instance.
  9676. *
  9677. * @param {Color} color - The color to copy.
  9678. * @return {Color} A reference to this color.
  9679. */
  9680. copy( color ) {
  9681. this.r = color.r;
  9682. this.g = color.g;
  9683. this.b = color.b;
  9684. return this;
  9685. }
  9686. /**
  9687. * Copies the given color into this color, and then converts this color from
  9688. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9689. *
  9690. * @param {Color} color - The color to copy/convert.
  9691. * @return {Color} A reference to this color.
  9692. */
  9693. copySRGBToLinear( color ) {
  9694. this.r = SRGBToLinear( color.r );
  9695. this.g = SRGBToLinear( color.g );
  9696. this.b = SRGBToLinear( color.b );
  9697. return this;
  9698. }
  9699. /**
  9700. * Copies the given color into this color, and then converts this color from
  9701. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9702. *
  9703. * @param {Color} color - The color to copy/convert.
  9704. * @return {Color} A reference to this color.
  9705. */
  9706. copyLinearToSRGB( color ) {
  9707. this.r = LinearToSRGB( color.r );
  9708. this.g = LinearToSRGB( color.g );
  9709. this.b = LinearToSRGB( color.b );
  9710. return this;
  9711. }
  9712. /**
  9713. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9714. *
  9715. * @return {Color} A reference to this color.
  9716. */
  9717. convertSRGBToLinear() {
  9718. this.copySRGBToLinear( this );
  9719. return this;
  9720. }
  9721. /**
  9722. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9723. *
  9724. * @return {Color} A reference to this color.
  9725. */
  9726. convertLinearToSRGB() {
  9727. this.copyLinearToSRGB( this );
  9728. return this;
  9729. }
  9730. /**
  9731. * Returns the hexadecimal value of this color.
  9732. *
  9733. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9734. * @return {number} The hexadecimal value.
  9735. */
  9736. getHex( colorSpace = SRGBColorSpace ) {
  9737. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9738. 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 ) );
  9739. }
  9740. /**
  9741. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  9742. *
  9743. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9744. * @return {string} The hexadecimal value as a string.
  9745. */
  9746. getHexString( colorSpace = SRGBColorSpace ) {
  9747. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  9748. }
  9749. /**
  9750. * Converts the colors RGB values into the HSL format and stores them into the
  9751. * given target object.
  9752. *
  9753. * @param {{h:0,s:0,l:0}} target - The target object that is used to store the method's result.
  9754. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9755. * @return {{h:0,s:0,l:0}} The HSL representation of this color.
  9756. */
  9757. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  9758. // h,s,l ranges are in 0.0 - 1.0
  9759. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9760. const r = _color.r, g = _color.g, b = _color.b;
  9761. const max = Math.max( r, g, b );
  9762. const min = Math.min( r, g, b );
  9763. let hue, saturation;
  9764. const lightness = ( min + max ) / 2.0;
  9765. if ( min === max ) {
  9766. hue = 0;
  9767. saturation = 0;
  9768. } else {
  9769. const delta = max - min;
  9770. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  9771. switch ( max ) {
  9772. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  9773. case g: hue = ( b - r ) / delta + 2; break;
  9774. case b: hue = ( r - g ) / delta + 4; break;
  9775. }
  9776. hue /= 6;
  9777. }
  9778. target.h = hue;
  9779. target.s = saturation;
  9780. target.l = lightness;
  9781. return target;
  9782. }
  9783. /**
  9784. * Returns the RGB values of this color and stores them into the given target object.
  9785. *
  9786. * @param {Color} target - The target color that is used to store the method's result.
  9787. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9788. * @return {Color} The RGB representation of this color.
  9789. */
  9790. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  9791. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9792. target.r = _color.r;
  9793. target.g = _color.g;
  9794. target.b = _color.b;
  9795. return target;
  9796. }
  9797. /**
  9798. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  9799. *
  9800. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9801. * @return {string} The CSS representation of this color.
  9802. */
  9803. getStyle( colorSpace = SRGBColorSpace ) {
  9804. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9805. const r = _color.r, g = _color.g, b = _color.b;
  9806. if ( colorSpace !== SRGBColorSpace ) {
  9807. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  9808. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  9809. }
  9810. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  9811. }
  9812. /**
  9813. * Adds the given HSL values to this color's values.
  9814. * Internally, this converts the color's RGB values to HSL, adds HSL
  9815. * and then converts the color back to RGB.
  9816. *
  9817. * @param {number} h - Hue value between `0.0` and `1.0`.
  9818. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9819. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9820. * @return {Color} A reference to this color.
  9821. */
  9822. offsetHSL( h, s, l ) {
  9823. this.getHSL( _hslA );
  9824. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  9825. }
  9826. /**
  9827. * Adds the RGB values of the given color to the RGB values of this color.
  9828. *
  9829. * @param {Color} color - The color to add.
  9830. * @return {Color} A reference to this color.
  9831. */
  9832. add( color ) {
  9833. this.r += color.r;
  9834. this.g += color.g;
  9835. this.b += color.b;
  9836. return this;
  9837. }
  9838. /**
  9839. * Adds the RGB values of the given colors and stores the result in this instance.
  9840. *
  9841. * @param {Color} color1 - The first color.
  9842. * @param {Color} color2 - The second color.
  9843. * @return {Color} A reference to this color.
  9844. */
  9845. addColors( color1, color2 ) {
  9846. this.r = color1.r + color2.r;
  9847. this.g = color1.g + color2.g;
  9848. this.b = color1.b + color2.b;
  9849. return this;
  9850. }
  9851. /**
  9852. * Adds the given scalar value to the RGB values of this color.
  9853. *
  9854. * @param {number} s - The scalar to add.
  9855. * @return {Color} A reference to this color.
  9856. */
  9857. addScalar( s ) {
  9858. this.r += s;
  9859. this.g += s;
  9860. this.b += s;
  9861. return this;
  9862. }
  9863. /**
  9864. * Subtracts the RGB values of the given color from the RGB values of this color.
  9865. *
  9866. * @param {Color} color - The color to subtract.
  9867. * @return {Color} A reference to this color.
  9868. */
  9869. sub( color ) {
  9870. this.r = Math.max( 0, this.r - color.r );
  9871. this.g = Math.max( 0, this.g - color.g );
  9872. this.b = Math.max( 0, this.b - color.b );
  9873. return this;
  9874. }
  9875. /**
  9876. * Multiplies the RGB values of the given color with the RGB values of this color.
  9877. *
  9878. * @param {Color} color - The color to multiply.
  9879. * @return {Color} A reference to this color.
  9880. */
  9881. multiply( color ) {
  9882. this.r *= color.r;
  9883. this.g *= color.g;
  9884. this.b *= color.b;
  9885. return this;
  9886. }
  9887. /**
  9888. * Multiplies the given scalar value with the RGB values of this color.
  9889. *
  9890. * @param {number} s - The scalar to multiply.
  9891. * @return {Color} A reference to this color.
  9892. */
  9893. multiplyScalar( s ) {
  9894. this.r *= s;
  9895. this.g *= s;
  9896. this.b *= s;
  9897. return this;
  9898. }
  9899. /**
  9900. * Linearly interpolates this color's RGB values toward the RGB values of the
  9901. * given color. The alpha argument can be thought of as the ratio between
  9902. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  9903. *
  9904. * @param {Color} color - The color to converge on.
  9905. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9906. * @return {Color} A reference to this color.
  9907. */
  9908. lerp( color, alpha ) {
  9909. this.r += ( color.r - this.r ) * alpha;
  9910. this.g += ( color.g - this.g ) * alpha;
  9911. this.b += ( color.b - this.b ) * alpha;
  9912. return this;
  9913. }
  9914. /**
  9915. * Linearly interpolates between the given colors and stores the result in this instance.
  9916. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  9917. * is the first and `1.0` is the second color.
  9918. *
  9919. * @param {Color} color1 - The first color.
  9920. * @param {Color} color2 - The second color.
  9921. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9922. * @return {Color} A reference to this color.
  9923. */
  9924. lerpColors( color1, color2, alpha ) {
  9925. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  9926. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  9927. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  9928. return this;
  9929. }
  9930. /**
  9931. * Linearly interpolates this color's HSL values toward the HSL values of the
  9932. * given color. It differs from {@link Color#lerp} by not interpolating straight
  9933. * from one color to the other, but instead going through all the hues in between
  9934. * those two colors. The alpha argument can be thought of as the ratio between
  9935. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  9936. *
  9937. * @param {Color} color - The color to converge on.
  9938. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9939. * @return {Color} A reference to this color.
  9940. */
  9941. lerpHSL( color, alpha ) {
  9942. this.getHSL( _hslA );
  9943. color.getHSL( _hslB );
  9944. const h = lerp( _hslA.h, _hslB.h, alpha );
  9945. const s = lerp( _hslA.s, _hslB.s, alpha );
  9946. const l = lerp( _hslA.l, _hslB.l, alpha );
  9947. this.setHSL( h, s, l );
  9948. return this;
  9949. }
  9950. /**
  9951. * Sets the color's RGB components from the given 3D vector.
  9952. *
  9953. * @param {Vector3} v - The vector to set.
  9954. * @return {Color} A reference to this color.
  9955. */
  9956. setFromVector3( v ) {
  9957. this.r = v.x;
  9958. this.g = v.y;
  9959. this.b = v.z;
  9960. return this;
  9961. }
  9962. /**
  9963. * Transforms this color with the given 3x3 matrix.
  9964. *
  9965. * @param {Matrix3} m - The matrix.
  9966. * @return {Color} A reference to this color.
  9967. */
  9968. applyMatrix3( m ) {
  9969. const r = this.r, g = this.g, b = this.b;
  9970. const e = m.elements;
  9971. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  9972. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  9973. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  9974. return this;
  9975. }
  9976. /**
  9977. * Returns `true` if this color is equal with the given one.
  9978. *
  9979. * @param {Color} c - The color to test for equality.
  9980. * @return {boolean} Whether this bounding color is equal with the given one.
  9981. */
  9982. equals( c ) {
  9983. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  9984. }
  9985. /**
  9986. * Sets this color's RGB components from the given array.
  9987. *
  9988. * @param {Array<number>} array - An array holding the RGB values.
  9989. * @param {number} [offset=0] - The offset into the array.
  9990. * @return {Color} A reference to this color.
  9991. */
  9992. fromArray( array, offset = 0 ) {
  9993. this.r = array[ offset ];
  9994. this.g = array[ offset + 1 ];
  9995. this.b = array[ offset + 2 ];
  9996. return this;
  9997. }
  9998. /**
  9999. * Writes the RGB components of this color to the given array. If no array is provided,
  10000. * the method returns a new instance.
  10001. *
  10002. * @param {Array<number>} [array=[]] - The target array holding the color components.
  10003. * @param {number} [offset=0] - Index of the first element in the array.
  10004. * @return {Array<number>} The color components.
  10005. */
  10006. toArray( array = [], offset = 0 ) {
  10007. array[ offset ] = this.r;
  10008. array[ offset + 1 ] = this.g;
  10009. array[ offset + 2 ] = this.b;
  10010. return array;
  10011. }
  10012. /**
  10013. * Sets the components of this color from the given buffer attribute.
  10014. *
  10015. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  10016. * @param {number} index - The index into the attribute.
  10017. * @return {Color} A reference to this color.
  10018. */
  10019. fromBufferAttribute( attribute, index ) {
  10020. this.r = attribute.getX( index );
  10021. this.g = attribute.getY( index );
  10022. this.b = attribute.getZ( index );
  10023. return this;
  10024. }
  10025. /**
  10026. * This methods defines the serialization result of this class. Returns the color
  10027. * as a hexadecimal value.
  10028. *
  10029. * @return {number} The hexadecimal value.
  10030. */
  10031. toJSON() {
  10032. return this.getHex();
  10033. }
  10034. *[ Symbol.iterator ]() {
  10035. yield this.r;
  10036. yield this.g;
  10037. yield this.b;
  10038. }
  10039. }
  10040. const _color = /*@__PURE__*/ new Color();
  10041. /**
  10042. * A dictionary with X11 color names.
  10043. *
  10044. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  10045. *
  10046. * @static
  10047. * @type {Object}
  10048. */
  10049. Color.NAMES = _colorKeywords;
  10050. let _materialId = 0;
  10051. /**
  10052. * Abstract base class for materials.
  10053. *
  10054. * Materials define the appearance of renderable 3D objects.
  10055. *
  10056. * @abstract
  10057. * @augments EventDispatcher
  10058. */
  10059. class Material extends EventDispatcher {
  10060. /**
  10061. * Constructs a new material.
  10062. */
  10063. constructor() {
  10064. super();
  10065. /**
  10066. * This flag can be used for type testing.
  10067. *
  10068. * @type {boolean}
  10069. * @readonly
  10070. * @default true
  10071. */
  10072. this.isMaterial = true;
  10073. /**
  10074. * The ID of the material.
  10075. *
  10076. * @name Material#id
  10077. * @type {number}
  10078. * @readonly
  10079. */
  10080. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  10081. /**
  10082. * The UUID of the material.
  10083. *
  10084. * @type {string}
  10085. * @readonly
  10086. */
  10087. this.uuid = generateUUID();
  10088. /**
  10089. * The name of the material.
  10090. *
  10091. * @type {string}
  10092. */
  10093. this.name = '';
  10094. /**
  10095. * The type property is used for detecting the object type
  10096. * in context of serialization/deserialization.
  10097. *
  10098. * @type {string}
  10099. * @readonly
  10100. */
  10101. this.type = 'Material';
  10102. /**
  10103. * Defines the blending type of the material.
  10104. *
  10105. * It must be set to `CustomBlending` if custom blending properties like
  10106. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  10107. * should have any effect.
  10108. *
  10109. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  10110. * @default NormalBlending
  10111. */
  10112. this.blending = NormalBlending;
  10113. /**
  10114. * Defines which side of faces will be rendered - front, back or both.
  10115. *
  10116. * @type {(FrontSide|BackSide|DoubleSide)}
  10117. * @default FrontSide
  10118. */
  10119. this.side = FrontSide;
  10120. /**
  10121. * If set to `true`, vertex colors should be used.
  10122. *
  10123. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  10124. * four (RGBA) component color buffer attribute is used.
  10125. *
  10126. * @type {boolean}
  10127. * @default false
  10128. */
  10129. this.vertexColors = false;
  10130. /**
  10131. * Defines how transparent the material is.
  10132. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  10133. *
  10134. * If the {@link Material#transparent} is not set to `true`,
  10135. * the material will remain fully opaque and this value will only affect its color.
  10136. *
  10137. * @type {number}
  10138. * @default 1
  10139. */
  10140. this.opacity = 1;
  10141. /**
  10142. * Defines whether this material is transparent. This has an effect on
  10143. * rendering as transparent objects need special treatment and are rendered
  10144. * after non-transparent objects.
  10145. *
  10146. * When set to true, the extent to which the material is transparent is
  10147. * controlled by {@link Material#opacity}.
  10148. *
  10149. * @type {boolean}
  10150. * @default false
  10151. */
  10152. this.transparent = false;
  10153. /**
  10154. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  10155. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  10156. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  10157. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  10158. *
  10159. * @type {boolean}
  10160. * @default false
  10161. */
  10162. this.alphaHash = false;
  10163. /**
  10164. * Defines the blending source factor.
  10165. *
  10166. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10167. * @default SrcAlphaFactor
  10168. */
  10169. this.blendSrc = SrcAlphaFactor;
  10170. /**
  10171. * Defines the blending destination factor.
  10172. *
  10173. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10174. * @default OneMinusSrcAlphaFactor
  10175. */
  10176. this.blendDst = OneMinusSrcAlphaFactor;
  10177. /**
  10178. * Defines the blending equation.
  10179. *
  10180. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10181. * @default OneMinusSrcAlphaFactor
  10182. */
  10183. this.blendEquation = AddEquation;
  10184. /**
  10185. * Defines the blending source alpha factor.
  10186. *
  10187. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10188. * @default null
  10189. */
  10190. this.blendSrcAlpha = null;
  10191. /**
  10192. * Defines the blending destination alpha factor.
  10193. *
  10194. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10195. * @default null
  10196. */
  10197. this.blendDstAlpha = null;
  10198. /**
  10199. * Defines the blending equation of the alpha channel.
  10200. *
  10201. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10202. * @default OneMinusSrcAlphaFactor
  10203. */
  10204. this.blendEquationAlpha = null;
  10205. /**
  10206. * Represents the RGB values of the constant blend color.
  10207. *
  10208. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  10209. *
  10210. * @type {Color}
  10211. * @default (0,0,0)
  10212. */
  10213. this.blendColor = new Color( 0, 0, 0 );
  10214. /**
  10215. * Represents the alpha value of the constant blend color.
  10216. *
  10217. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  10218. *
  10219. * @type {number}
  10220. * @default 0
  10221. */
  10222. this.blendAlpha = 0;
  10223. /**
  10224. * Defines the depth function.
  10225. *
  10226. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  10227. * @default LessEqualDepth
  10228. */
  10229. this.depthFunc = LessEqualDepth;
  10230. /**
  10231. * Whether to have depth test enabled when rendering this material.
  10232. * When the depth test is disabled, the depth write will also be implicitly disabled.
  10233. *
  10234. * @type {boolean}
  10235. * @default true
  10236. */
  10237. this.depthTest = true;
  10238. /**
  10239. * Whether rendering this material has any effect on the depth buffer.
  10240. *
  10241. * When drawing 2D overlays it can be useful to disable the depth writing in
  10242. * order to layer several things together without creating z-index artifacts.
  10243. *
  10244. * @type {boolean}
  10245. * @default true
  10246. */
  10247. this.depthWrite = true;
  10248. /**
  10249. * The bit mask to use when writing to the stencil buffer.
  10250. *
  10251. * @type {number}
  10252. * @default 0xff
  10253. */
  10254. this.stencilWriteMask = 0xff;
  10255. /**
  10256. * The stencil comparison function to use.
  10257. *
  10258. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  10259. * @default AlwaysStencilFunc
  10260. */
  10261. this.stencilFunc = AlwaysStencilFunc;
  10262. /**
  10263. * The value to use when performing stencil comparisons or stencil operations.
  10264. *
  10265. * @type {number}
  10266. * @default 0
  10267. */
  10268. this.stencilRef = 0;
  10269. /**
  10270. * The bit mask to use when comparing against the stencil buffer.
  10271. *
  10272. * @type {number}
  10273. * @default 0xff
  10274. */
  10275. this.stencilFuncMask = 0xff;
  10276. /**
  10277. * Which stencil operation to perform when the comparison function returns `false`.
  10278. *
  10279. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10280. * @default KeepStencilOp
  10281. */
  10282. this.stencilFail = KeepStencilOp;
  10283. /**
  10284. * Which stencil operation to perform when the comparison function returns
  10285. * `true` but the depth test fails.
  10286. *
  10287. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10288. * @default KeepStencilOp
  10289. */
  10290. this.stencilZFail = KeepStencilOp;
  10291. /**
  10292. * Which stencil operation to perform when the comparison function returns
  10293. * `true` and the depth test passes.
  10294. *
  10295. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10296. * @default KeepStencilOp
  10297. */
  10298. this.stencilZPass = KeepStencilOp;
  10299. /**
  10300. * Whether stencil operations are performed against the stencil buffer. In
  10301. * order to perform writes or comparisons against the stencil buffer this
  10302. * value must be `true`.
  10303. *
  10304. * @type {boolean}
  10305. * @default false
  10306. */
  10307. this.stencilWrite = false;
  10308. /**
  10309. * User-defined clipping planes specified as THREE.Plane objects in world
  10310. * space. These planes apply to the objects this material is attached to.
  10311. * Points in space whose signed distance to the plane is negative are clipped
  10312. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  10313. * be `true`.
  10314. *
  10315. * @type {?Array<Plane>}
  10316. * @default null
  10317. */
  10318. this.clippingPlanes = null;
  10319. /**
  10320. * Changes the behavior of clipping planes so that only their intersection is
  10321. * clipped, rather than their union.
  10322. *
  10323. * @type {boolean}
  10324. * @default false
  10325. */
  10326. this.clipIntersection = false;
  10327. /**
  10328. * Defines whether to clip shadows according to the clipping planes specified
  10329. * on this material.
  10330. *
  10331. * @type {boolean}
  10332. * @default false
  10333. */
  10334. this.clipShadows = false;
  10335. /**
  10336. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  10337. * is determined as follows:
  10338. *
  10339. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  10340. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  10341. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  10342. *
  10343. * @type {?(FrontSide|BackSide|DoubleSide)}
  10344. * @default null
  10345. */
  10346. this.shadowSide = null;
  10347. /**
  10348. * Whether to render the material's color.
  10349. *
  10350. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  10351. * objects that occlude other objects.
  10352. *
  10353. * @type {boolean}
  10354. * @default true
  10355. */
  10356. this.colorWrite = true;
  10357. /**
  10358. * Override the renderer's default precision for this material.
  10359. *
  10360. * @type {?('highp'|'mediump'|'lowp')}
  10361. * @default null
  10362. */
  10363. this.precision = null;
  10364. /**
  10365. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  10366. * be offset after it is interpolated from the depth values of the appropriate vertices.
  10367. * The offset is added before the depth test is performed and before the value is written
  10368. * into the depth buffer.
  10369. *
  10370. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  10371. * rendering solids with highlighted edges.
  10372. *
  10373. * @type {boolean}
  10374. * @default false
  10375. */
  10376. this.polygonOffset = false;
  10377. /**
  10378. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  10379. *
  10380. * @type {number}
  10381. * @default 0
  10382. */
  10383. this.polygonOffsetFactor = 0;
  10384. /**
  10385. * Is multiplied by an implementation-specific value to create a constant depth offset.
  10386. *
  10387. * @type {number}
  10388. * @default 0
  10389. */
  10390. this.polygonOffsetUnits = 0;
  10391. /**
  10392. * Whether to apply dithering to the color to remove the appearance of banding.
  10393. *
  10394. * @type {boolean}
  10395. * @default false
  10396. */
  10397. this.dithering = false;
  10398. /**
  10399. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  10400. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  10401. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  10402. *
  10403. * @type {boolean}
  10404. * @default false
  10405. */
  10406. this.alphaToCoverage = false;
  10407. /**
  10408. * Whether to premultiply the alpha (transparency) value.
  10409. *
  10410. * @type {boolean}
  10411. * @default false
  10412. */
  10413. this.premultipliedAlpha = false;
  10414. /**
  10415. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  10416. *
  10417. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  10418. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  10419. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  10420. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  10421. * disable the two pass rendering to avoid performance issues.
  10422. *
  10423. * @type {boolean}
  10424. * @default false
  10425. */
  10426. this.forceSinglePass = false;
  10427. /**
  10428. * Defines whether 3D objects using this material are visible.
  10429. *
  10430. * @type {boolean}
  10431. * @default true
  10432. */
  10433. this.visible = true;
  10434. /**
  10435. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  10436. *
  10437. * It is ignored when rendering to a render target or using post processing or when using
  10438. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  10439. *
  10440. * @type {boolean}
  10441. * @default true
  10442. */
  10443. this.toneMapped = true;
  10444. /**
  10445. * An object that can be used to store custom data about the Material. It
  10446. * should not hold references to functions as these will not be cloned.
  10447. *
  10448. * @type {Object}
  10449. */
  10450. this.userData = {};
  10451. /**
  10452. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  10453. *
  10454. * @type {number}
  10455. * @readonly
  10456. * @default 0
  10457. */
  10458. this.version = 0;
  10459. this._alphaTest = 0;
  10460. }
  10461. /**
  10462. * Sets the alpha value to be used when running an alpha test. The material
  10463. * will not be rendered if the opacity is lower than this value.
  10464. *
  10465. * @type {number}
  10466. * @readonly
  10467. * @default 0
  10468. */
  10469. get alphaTest() {
  10470. return this._alphaTest;
  10471. }
  10472. set alphaTest( value ) {
  10473. if ( this._alphaTest > 0 !== value > 0 ) {
  10474. this.version ++;
  10475. }
  10476. this._alphaTest = value;
  10477. }
  10478. /**
  10479. * An optional callback that is executed immediately before the material is used to render a 3D object.
  10480. *
  10481. * This method can only be used when rendering with {@link WebGLRenderer}.
  10482. *
  10483. * @param {WebGLRenderer} renderer - The renderer.
  10484. * @param {Scene} scene - The scene.
  10485. * @param {Camera} camera - The camera that is used to render the scene.
  10486. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10487. * @param {Object3D} object - The 3D object.
  10488. * @param {Object} group - The geometry group data.
  10489. */
  10490. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  10491. /**
  10492. * An optional callback that is executed immediately before the shader
  10493. * program is compiled. This function is called with the shader source code
  10494. * as a parameter. Useful for the modification of built-in materials.
  10495. *
  10496. * This method can only be used when rendering with {@link WebGLRenderer}. The
  10497. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  10498. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  10499. *
  10500. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  10501. * @param {WebGLRenderer} renderer - A reference to the renderer.
  10502. */
  10503. onBeforeCompile( /* shaderobject, renderer */ ) {}
  10504. /**
  10505. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  10506. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  10507. * shader or recompile the shader for this material as needed.
  10508. *
  10509. * This method can only be used when rendering with {@link WebGLRenderer}.
  10510. *
  10511. * @return {string} The custom program cache key.
  10512. */
  10513. customProgramCacheKey() {
  10514. return this.onBeforeCompile.toString();
  10515. }
  10516. setValues( values ) {
  10517. if ( values === undefined ) return;
  10518. for ( const key in values ) {
  10519. const newValue = values[ key ];
  10520. if ( newValue === undefined ) {
  10521. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  10522. continue;
  10523. }
  10524. const currentValue = this[ key ];
  10525. if ( currentValue === undefined ) {
  10526. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  10527. continue;
  10528. }
  10529. if ( currentValue && currentValue.isColor ) {
  10530. currentValue.set( newValue );
  10531. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10532. currentValue.copy( newValue );
  10533. } else {
  10534. this[ key ] = newValue;
  10535. }
  10536. }
  10537. }
  10538. /**
  10539. * Serializes the material into JSON.
  10540. *
  10541. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10542. * @return {Object} A JSON object representing the serialized material.
  10543. * @see {@link ObjectLoader#parse}
  10544. */
  10545. toJSON( meta ) {
  10546. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10547. if ( isRootObject ) {
  10548. meta = {
  10549. textures: {},
  10550. images: {}
  10551. };
  10552. }
  10553. const data = {
  10554. metadata: {
  10555. version: 4.6,
  10556. type: 'Material',
  10557. generator: 'Material.toJSON'
  10558. }
  10559. };
  10560. // standard Material serialization
  10561. data.uuid = this.uuid;
  10562. data.type = this.type;
  10563. if ( this.name !== '' ) data.name = this.name;
  10564. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  10565. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  10566. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  10567. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  10568. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  10569. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  10570. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  10571. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  10572. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  10573. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  10574. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  10575. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  10576. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  10577. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  10578. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  10579. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  10580. }
  10581. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  10582. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  10583. }
  10584. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10585. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10586. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10587. }
  10588. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  10589. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  10590. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  10591. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  10592. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  10593. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  10594. }
  10595. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  10596. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  10597. }
  10598. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  10599. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  10600. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  10601. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  10602. }
  10603. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  10604. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  10605. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  10606. if ( this.lightMap && this.lightMap.isTexture ) {
  10607. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  10608. data.lightMapIntensity = this.lightMapIntensity;
  10609. }
  10610. if ( this.aoMap && this.aoMap.isTexture ) {
  10611. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10612. data.aoMapIntensity = this.aoMapIntensity;
  10613. }
  10614. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10615. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10616. data.bumpScale = this.bumpScale;
  10617. }
  10618. if ( this.normalMap && this.normalMap.isTexture ) {
  10619. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10620. data.normalMapType = this.normalMapType;
  10621. data.normalScale = this.normalScale.toArray();
  10622. }
  10623. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10624. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10625. data.displacementScale = this.displacementScale;
  10626. data.displacementBias = this.displacementBias;
  10627. }
  10628. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  10629. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  10630. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  10631. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  10632. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  10633. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  10634. if ( this.envMap && this.envMap.isTexture ) {
  10635. data.envMap = this.envMap.toJSON( meta ).uuid;
  10636. if ( this.combine !== undefined ) data.combine = this.combine;
  10637. }
  10638. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  10639. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  10640. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  10641. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  10642. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10643. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10644. }
  10645. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  10646. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  10647. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  10648. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  10649. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  10650. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  10651. if ( this.size !== undefined ) data.size = this.size;
  10652. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  10653. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  10654. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  10655. if ( this.side !== FrontSide ) data.side = this.side;
  10656. if ( this.vertexColors === true ) data.vertexColors = true;
  10657. if ( this.opacity < 1 ) data.opacity = this.opacity;
  10658. if ( this.transparent === true ) data.transparent = true;
  10659. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  10660. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  10661. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  10662. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  10663. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  10664. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  10665. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  10666. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  10667. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  10668. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  10669. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  10670. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  10671. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  10672. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  10673. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  10674. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  10675. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  10676. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  10677. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  10678. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  10679. // rotation (SpriteMaterial)
  10680. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  10681. if ( this.polygonOffset === true ) data.polygonOffset = true;
  10682. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  10683. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  10684. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  10685. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  10686. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  10687. if ( this.scale !== undefined ) data.scale = this.scale;
  10688. if ( this.dithering === true ) data.dithering = true;
  10689. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  10690. if ( this.alphaHash === true ) data.alphaHash = true;
  10691. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  10692. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  10693. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  10694. if ( this.wireframe === true ) data.wireframe = true;
  10695. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  10696. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  10697. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  10698. if ( this.flatShading === true ) data.flatShading = true;
  10699. if ( this.visible === false ) data.visible = false;
  10700. if ( this.toneMapped === false ) data.toneMapped = false;
  10701. if ( this.fog === false ) data.fog = false;
  10702. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  10703. // TODO: Copied from Object3D.toJSON
  10704. function extractFromCache( cache ) {
  10705. const values = [];
  10706. for ( const key in cache ) {
  10707. const data = cache[ key ];
  10708. delete data.metadata;
  10709. values.push( data );
  10710. }
  10711. return values;
  10712. }
  10713. if ( isRootObject ) {
  10714. const textures = extractFromCache( meta.textures );
  10715. const images = extractFromCache( meta.images );
  10716. if ( textures.length > 0 ) data.textures = textures;
  10717. if ( images.length > 0 ) data.images = images;
  10718. }
  10719. return data;
  10720. }
  10721. /**
  10722. * Returns a new material with copied values from this instance.
  10723. *
  10724. * @return {Material} A clone of this instance.
  10725. */
  10726. clone() {
  10727. return new this.constructor().copy( this );
  10728. }
  10729. /**
  10730. * Copies the values of the given material to this instance.
  10731. *
  10732. * @param {Material} source - The material to copy.
  10733. * @return {Material} A reference to this instance.
  10734. */
  10735. copy( source ) {
  10736. this.name = source.name;
  10737. this.blending = source.blending;
  10738. this.side = source.side;
  10739. this.vertexColors = source.vertexColors;
  10740. this.opacity = source.opacity;
  10741. this.transparent = source.transparent;
  10742. this.blendSrc = source.blendSrc;
  10743. this.blendDst = source.blendDst;
  10744. this.blendEquation = source.blendEquation;
  10745. this.blendSrcAlpha = source.blendSrcAlpha;
  10746. this.blendDstAlpha = source.blendDstAlpha;
  10747. this.blendEquationAlpha = source.blendEquationAlpha;
  10748. this.blendColor.copy( source.blendColor );
  10749. this.blendAlpha = source.blendAlpha;
  10750. this.depthFunc = source.depthFunc;
  10751. this.depthTest = source.depthTest;
  10752. this.depthWrite = source.depthWrite;
  10753. this.stencilWriteMask = source.stencilWriteMask;
  10754. this.stencilFunc = source.stencilFunc;
  10755. this.stencilRef = source.stencilRef;
  10756. this.stencilFuncMask = source.stencilFuncMask;
  10757. this.stencilFail = source.stencilFail;
  10758. this.stencilZFail = source.stencilZFail;
  10759. this.stencilZPass = source.stencilZPass;
  10760. this.stencilWrite = source.stencilWrite;
  10761. const srcPlanes = source.clippingPlanes;
  10762. let dstPlanes = null;
  10763. if ( srcPlanes !== null ) {
  10764. const n = srcPlanes.length;
  10765. dstPlanes = new Array( n );
  10766. for ( let i = 0; i !== n; ++ i ) {
  10767. dstPlanes[ i ] = srcPlanes[ i ].clone();
  10768. }
  10769. }
  10770. this.clippingPlanes = dstPlanes;
  10771. this.clipIntersection = source.clipIntersection;
  10772. this.clipShadows = source.clipShadows;
  10773. this.shadowSide = source.shadowSide;
  10774. this.colorWrite = source.colorWrite;
  10775. this.precision = source.precision;
  10776. this.polygonOffset = source.polygonOffset;
  10777. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10778. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10779. this.dithering = source.dithering;
  10780. this.alphaTest = source.alphaTest;
  10781. this.alphaHash = source.alphaHash;
  10782. this.alphaToCoverage = source.alphaToCoverage;
  10783. this.premultipliedAlpha = source.premultipliedAlpha;
  10784. this.forceSinglePass = source.forceSinglePass;
  10785. this.visible = source.visible;
  10786. this.toneMapped = source.toneMapped;
  10787. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10788. return this;
  10789. }
  10790. /**
  10791. * Frees the GPU-related resources allocated by this instance. Call this
  10792. * method whenever this instance is no longer used in your app.
  10793. *
  10794. * @fires Material#dispose
  10795. */
  10796. dispose() {
  10797. /**
  10798. * Fires when the material has been disposed of.
  10799. *
  10800. * @event Material#dispose
  10801. * @type {Object}
  10802. */
  10803. this.dispatchEvent( { type: 'dispose' } );
  10804. }
  10805. /**
  10806. * Setting this property to `true` indicates the engine the material
  10807. * needs to be recompiled.
  10808. *
  10809. * @type {boolean}
  10810. * @default false
  10811. * @param {boolean} value
  10812. */
  10813. set needsUpdate( value ) {
  10814. if ( value === true ) this.version ++;
  10815. }
  10816. onBuild( /* shaderobject, renderer */ ) {
  10817. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  10818. }
  10819. }
  10820. class MeshBasicMaterial extends Material {
  10821. constructor( parameters ) {
  10822. super();
  10823. this.isMeshBasicMaterial = true;
  10824. this.type = 'MeshBasicMaterial';
  10825. this.color = new Color( 0xffffff ); // emissive
  10826. this.map = null;
  10827. this.lightMap = null;
  10828. this.lightMapIntensity = 1.0;
  10829. this.aoMap = null;
  10830. this.aoMapIntensity = 1.0;
  10831. this.specularMap = null;
  10832. this.alphaMap = null;
  10833. this.envMap = null;
  10834. this.envMapRotation = new Euler();
  10835. this.combine = MultiplyOperation;
  10836. this.reflectivity = 1;
  10837. this.refractionRatio = 0.98;
  10838. this.wireframe = false;
  10839. this.wireframeLinewidth = 1;
  10840. this.wireframeLinecap = 'round';
  10841. this.wireframeLinejoin = 'round';
  10842. this.fog = true;
  10843. this.setValues( parameters );
  10844. }
  10845. copy( source ) {
  10846. super.copy( source );
  10847. this.color.copy( source.color );
  10848. this.map = source.map;
  10849. this.lightMap = source.lightMap;
  10850. this.lightMapIntensity = source.lightMapIntensity;
  10851. this.aoMap = source.aoMap;
  10852. this.aoMapIntensity = source.aoMapIntensity;
  10853. this.specularMap = source.specularMap;
  10854. this.alphaMap = source.alphaMap;
  10855. this.envMap = source.envMap;
  10856. this.envMapRotation.copy( source.envMapRotation );
  10857. this.combine = source.combine;
  10858. this.reflectivity = source.reflectivity;
  10859. this.refractionRatio = source.refractionRatio;
  10860. this.wireframe = source.wireframe;
  10861. this.wireframeLinewidth = source.wireframeLinewidth;
  10862. this.wireframeLinecap = source.wireframeLinecap;
  10863. this.wireframeLinejoin = source.wireframeLinejoin;
  10864. this.fog = source.fog;
  10865. return this;
  10866. }
  10867. }
  10868. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  10869. const _tables = /*@__PURE__*/ _generateTables();
  10870. function _generateTables() {
  10871. // float32 to float16 helpers
  10872. const buffer = new ArrayBuffer( 4 );
  10873. const floatView = new Float32Array( buffer );
  10874. const uint32View = new Uint32Array( buffer );
  10875. const baseTable = new Uint32Array( 512 );
  10876. const shiftTable = new Uint32Array( 512 );
  10877. for ( let i = 0; i < 256; ++ i ) {
  10878. const e = i - 127;
  10879. // very small number (0, -0)
  10880. if ( e < -27 ) {
  10881. baseTable[ i ] = 0x0000;
  10882. baseTable[ i | 0x100 ] = 0x8000;
  10883. shiftTable[ i ] = 24;
  10884. shiftTable[ i | 0x100 ] = 24;
  10885. // small number (denorm)
  10886. } else if ( e < -14 ) {
  10887. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  10888. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  10889. shiftTable[ i ] = - e - 1;
  10890. shiftTable[ i | 0x100 ] = - e - 1;
  10891. // normal number
  10892. } else if ( e <= 15 ) {
  10893. baseTable[ i ] = ( e + 15 ) << 10;
  10894. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  10895. shiftTable[ i ] = 13;
  10896. shiftTable[ i | 0x100 ] = 13;
  10897. // large number (Infinity, -Infinity)
  10898. } else if ( e < 128 ) {
  10899. baseTable[ i ] = 0x7c00;
  10900. baseTable[ i | 0x100 ] = 0xfc00;
  10901. shiftTable[ i ] = 24;
  10902. shiftTable[ i | 0x100 ] = 24;
  10903. // stay (NaN, Infinity, -Infinity)
  10904. } else {
  10905. baseTable[ i ] = 0x7c00;
  10906. baseTable[ i | 0x100 ] = 0xfc00;
  10907. shiftTable[ i ] = 13;
  10908. shiftTable[ i | 0x100 ] = 13;
  10909. }
  10910. }
  10911. // float16 to float32 helpers
  10912. const mantissaTable = new Uint32Array( 2048 );
  10913. const exponentTable = new Uint32Array( 64 );
  10914. const offsetTable = new Uint32Array( 64 );
  10915. for ( let i = 1; i < 1024; ++ i ) {
  10916. let m = i << 13; // zero pad mantissa bits
  10917. let e = 0; // zero exponent
  10918. // normalized
  10919. while ( ( m & 0x00800000 ) === 0 ) {
  10920. m <<= 1;
  10921. e -= 0x00800000; // decrement exponent
  10922. }
  10923. m &= -8388609; // clear leading 1 bit
  10924. e += 0x38800000; // adjust bias
  10925. mantissaTable[ i ] = m | e;
  10926. }
  10927. for ( let i = 1024; i < 2048; ++ i ) {
  10928. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  10929. }
  10930. for ( let i = 1; i < 31; ++ i ) {
  10931. exponentTable[ i ] = i << 23;
  10932. }
  10933. exponentTable[ 31 ] = 0x47800000;
  10934. exponentTable[ 32 ] = 0x80000000;
  10935. for ( let i = 33; i < 63; ++ i ) {
  10936. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  10937. }
  10938. exponentTable[ 63 ] = 0xc7800000;
  10939. for ( let i = 1; i < 64; ++ i ) {
  10940. if ( i !== 32 ) {
  10941. offsetTable[ i ] = 1024;
  10942. }
  10943. }
  10944. return {
  10945. floatView: floatView,
  10946. uint32View: uint32View,
  10947. baseTable: baseTable,
  10948. shiftTable: shiftTable,
  10949. mantissaTable: mantissaTable,
  10950. exponentTable: exponentTable,
  10951. offsetTable: offsetTable
  10952. };
  10953. }
  10954. /**
  10955. * Returns a half precision floating point value (FP16) from the given single
  10956. * precision floating point value (FP32).
  10957. *
  10958. * @param {number} val - A single precision floating point value.
  10959. * @return {number} The FP16 value.
  10960. */
  10961. function toHalfFloat( val ) {
  10962. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  10963. val = clamp( val, -65504, 65504 );
  10964. _tables.floatView[ 0 ] = val;
  10965. const f = _tables.uint32View[ 0 ];
  10966. const e = ( f >> 23 ) & 0x1ff;
  10967. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  10968. }
  10969. /**
  10970. * Returns a single precision floating point value (FP32) from the given half
  10971. * precision floating point value (FP16).
  10972. *
  10973. * @param {number} val - A half precision floating point value.
  10974. * @return {number} The FP32 value.
  10975. */
  10976. function fromHalfFloat( val ) {
  10977. const m = val >> 10;
  10978. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  10979. return _tables.floatView[ 0 ];
  10980. }
  10981. /**
  10982. * A class containing utility functions for data.
  10983. *
  10984. * @hideconstructor
  10985. */
  10986. class DataUtils {
  10987. /**
  10988. * Returns a half precision floating point value (FP16) from the given single
  10989. * precision floating point value (FP32).
  10990. *
  10991. * @param {number} val - A single precision floating point value.
  10992. * @return {number} The FP16 value.
  10993. */
  10994. static toHalfFloat( val ) {
  10995. return toHalfFloat( val );
  10996. }
  10997. /**
  10998. * Returns a single precision floating point value (FP32) from the given half
  10999. * precision floating point value (FP16).
  11000. *
  11001. * @param {number} val - A half precision floating point value.
  11002. * @return {number} The FP32 value.
  11003. */
  11004. static fromHalfFloat( val ) {
  11005. return fromHalfFloat( val );
  11006. }
  11007. }
  11008. const _vector$9 = /*@__PURE__*/ new Vector3();
  11009. const _vector2$1 = /*@__PURE__*/ new Vector2();
  11010. let _id$3 = 0;
  11011. class BufferAttribute {
  11012. constructor( array, itemSize, normalized = false ) {
  11013. if ( Array.isArray( array ) ) {
  11014. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11015. }
  11016. this.isBufferAttribute = true;
  11017. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  11018. this.name = '';
  11019. this.array = array;
  11020. this.itemSize = itemSize;
  11021. this.count = array !== undefined ? array.length / itemSize : 0;
  11022. this.normalized = normalized;
  11023. this.usage = StaticDrawUsage;
  11024. this.updateRanges = [];
  11025. this.gpuType = FloatType;
  11026. this.version = 0;
  11027. }
  11028. onUploadCallback() {}
  11029. set needsUpdate( value ) {
  11030. if ( value === true ) this.version ++;
  11031. }
  11032. setUsage( value ) {
  11033. this.usage = value;
  11034. return this;
  11035. }
  11036. addUpdateRange( start, count ) {
  11037. this.updateRanges.push( { start, count } );
  11038. }
  11039. clearUpdateRanges() {
  11040. this.updateRanges.length = 0;
  11041. }
  11042. copy( source ) {
  11043. this.name = source.name;
  11044. this.array = new source.array.constructor( source.array );
  11045. this.itemSize = source.itemSize;
  11046. this.count = source.count;
  11047. this.normalized = source.normalized;
  11048. this.usage = source.usage;
  11049. this.gpuType = source.gpuType;
  11050. return this;
  11051. }
  11052. copyAt( index1, attribute, index2 ) {
  11053. index1 *= this.itemSize;
  11054. index2 *= attribute.itemSize;
  11055. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  11056. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11057. }
  11058. return this;
  11059. }
  11060. copyArray( array ) {
  11061. this.array.set( array );
  11062. return this;
  11063. }
  11064. applyMatrix3( m ) {
  11065. if ( this.itemSize === 2 ) {
  11066. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11067. _vector2$1.fromBufferAttribute( this, i );
  11068. _vector2$1.applyMatrix3( m );
  11069. this.setXY( i, _vector2$1.x, _vector2$1.y );
  11070. }
  11071. } else if ( this.itemSize === 3 ) {
  11072. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11073. _vector$9.fromBufferAttribute( this, i );
  11074. _vector$9.applyMatrix3( m );
  11075. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11076. }
  11077. }
  11078. return this;
  11079. }
  11080. applyMatrix4( m ) {
  11081. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11082. _vector$9.fromBufferAttribute( this, i );
  11083. _vector$9.applyMatrix4( m );
  11084. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11085. }
  11086. return this;
  11087. }
  11088. applyNormalMatrix( m ) {
  11089. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11090. _vector$9.fromBufferAttribute( this, i );
  11091. _vector$9.applyNormalMatrix( m );
  11092. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11093. }
  11094. return this;
  11095. }
  11096. transformDirection( m ) {
  11097. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11098. _vector$9.fromBufferAttribute( this, i );
  11099. _vector$9.transformDirection( m );
  11100. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11101. }
  11102. return this;
  11103. }
  11104. set( value, offset = 0 ) {
  11105. // Matching BufferAttribute constructor, do not normalize the array.
  11106. this.array.set( value, offset );
  11107. return this;
  11108. }
  11109. getComponent( index, component ) {
  11110. let value = this.array[ index * this.itemSize + component ];
  11111. if ( this.normalized ) value = denormalize( value, this.array );
  11112. return value;
  11113. }
  11114. setComponent( index, component, value ) {
  11115. if ( this.normalized ) value = normalize( value, this.array );
  11116. this.array[ index * this.itemSize + component ] = value;
  11117. return this;
  11118. }
  11119. getX( index ) {
  11120. let x = this.array[ index * this.itemSize ];
  11121. if ( this.normalized ) x = denormalize( x, this.array );
  11122. return x;
  11123. }
  11124. setX( index, x ) {
  11125. if ( this.normalized ) x = normalize( x, this.array );
  11126. this.array[ index * this.itemSize ] = x;
  11127. return this;
  11128. }
  11129. getY( index ) {
  11130. let y = this.array[ index * this.itemSize + 1 ];
  11131. if ( this.normalized ) y = denormalize( y, this.array );
  11132. return y;
  11133. }
  11134. setY( index, y ) {
  11135. if ( this.normalized ) y = normalize( y, this.array );
  11136. this.array[ index * this.itemSize + 1 ] = y;
  11137. return this;
  11138. }
  11139. getZ( index ) {
  11140. let z = this.array[ index * this.itemSize + 2 ];
  11141. if ( this.normalized ) z = denormalize( z, this.array );
  11142. return z;
  11143. }
  11144. setZ( index, z ) {
  11145. if ( this.normalized ) z = normalize( z, this.array );
  11146. this.array[ index * this.itemSize + 2 ] = z;
  11147. return this;
  11148. }
  11149. getW( index ) {
  11150. let w = this.array[ index * this.itemSize + 3 ];
  11151. if ( this.normalized ) w = denormalize( w, this.array );
  11152. return w;
  11153. }
  11154. setW( index, w ) {
  11155. if ( this.normalized ) w = normalize( w, this.array );
  11156. this.array[ index * this.itemSize + 3 ] = w;
  11157. return this;
  11158. }
  11159. setXY( index, x, y ) {
  11160. index *= this.itemSize;
  11161. if ( this.normalized ) {
  11162. x = normalize( x, this.array );
  11163. y = normalize( y, this.array );
  11164. }
  11165. this.array[ index + 0 ] = x;
  11166. this.array[ index + 1 ] = y;
  11167. return this;
  11168. }
  11169. setXYZ( index, x, y, z ) {
  11170. index *= this.itemSize;
  11171. if ( this.normalized ) {
  11172. x = normalize( x, this.array );
  11173. y = normalize( y, this.array );
  11174. z = normalize( z, this.array );
  11175. }
  11176. this.array[ index + 0 ] = x;
  11177. this.array[ index + 1 ] = y;
  11178. this.array[ index + 2 ] = z;
  11179. return this;
  11180. }
  11181. setXYZW( index, x, y, z, w ) {
  11182. index *= this.itemSize;
  11183. if ( this.normalized ) {
  11184. x = normalize( x, this.array );
  11185. y = normalize( y, this.array );
  11186. z = normalize( z, this.array );
  11187. w = normalize( w, this.array );
  11188. }
  11189. this.array[ index + 0 ] = x;
  11190. this.array[ index + 1 ] = y;
  11191. this.array[ index + 2 ] = z;
  11192. this.array[ index + 3 ] = w;
  11193. return this;
  11194. }
  11195. onUpload( callback ) {
  11196. this.onUploadCallback = callback;
  11197. return this;
  11198. }
  11199. clone() {
  11200. return new this.constructor( this.array, this.itemSize ).copy( this );
  11201. }
  11202. toJSON() {
  11203. const data = {
  11204. itemSize: this.itemSize,
  11205. type: this.array.constructor.name,
  11206. array: Array.from( this.array ),
  11207. normalized: this.normalized
  11208. };
  11209. if ( this.name !== '' ) data.name = this.name;
  11210. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  11211. return data;
  11212. }
  11213. }
  11214. //
  11215. class Int8BufferAttribute extends BufferAttribute {
  11216. constructor( array, itemSize, normalized ) {
  11217. super( new Int8Array( array ), itemSize, normalized );
  11218. }
  11219. }
  11220. class Uint8BufferAttribute extends BufferAttribute {
  11221. constructor( array, itemSize, normalized ) {
  11222. super( new Uint8Array( array ), itemSize, normalized );
  11223. }
  11224. }
  11225. class Uint8ClampedBufferAttribute extends BufferAttribute {
  11226. constructor( array, itemSize, normalized ) {
  11227. super( new Uint8ClampedArray( array ), itemSize, normalized );
  11228. }
  11229. }
  11230. class Int16BufferAttribute extends BufferAttribute {
  11231. constructor( array, itemSize, normalized ) {
  11232. super( new Int16Array( array ), itemSize, normalized );
  11233. }
  11234. }
  11235. class Uint16BufferAttribute extends BufferAttribute {
  11236. constructor( array, itemSize, normalized ) {
  11237. super( new Uint16Array( array ), itemSize, normalized );
  11238. }
  11239. }
  11240. class Int32BufferAttribute extends BufferAttribute {
  11241. constructor( array, itemSize, normalized ) {
  11242. super( new Int32Array( array ), itemSize, normalized );
  11243. }
  11244. }
  11245. class Uint32BufferAttribute extends BufferAttribute {
  11246. constructor( array, itemSize, normalized ) {
  11247. super( new Uint32Array( array ), itemSize, normalized );
  11248. }
  11249. }
  11250. class Float16BufferAttribute extends BufferAttribute {
  11251. constructor( array, itemSize, normalized ) {
  11252. super( new Uint16Array( array ), itemSize, normalized );
  11253. this.isFloat16BufferAttribute = true;
  11254. }
  11255. getX( index ) {
  11256. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  11257. if ( this.normalized ) x = denormalize( x, this.array );
  11258. return x;
  11259. }
  11260. setX( index, x ) {
  11261. if ( this.normalized ) x = normalize( x, this.array );
  11262. this.array[ index * this.itemSize ] = toHalfFloat( x );
  11263. return this;
  11264. }
  11265. getY( index ) {
  11266. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  11267. if ( this.normalized ) y = denormalize( y, this.array );
  11268. return y;
  11269. }
  11270. setY( index, y ) {
  11271. if ( this.normalized ) y = normalize( y, this.array );
  11272. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  11273. return this;
  11274. }
  11275. getZ( index ) {
  11276. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  11277. if ( this.normalized ) z = denormalize( z, this.array );
  11278. return z;
  11279. }
  11280. setZ( index, z ) {
  11281. if ( this.normalized ) z = normalize( z, this.array );
  11282. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  11283. return this;
  11284. }
  11285. getW( index ) {
  11286. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  11287. if ( this.normalized ) w = denormalize( w, this.array );
  11288. return w;
  11289. }
  11290. setW( index, w ) {
  11291. if ( this.normalized ) w = normalize( w, this.array );
  11292. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  11293. return this;
  11294. }
  11295. setXY( index, x, y ) {
  11296. index *= this.itemSize;
  11297. if ( this.normalized ) {
  11298. x = normalize( x, this.array );
  11299. y = normalize( y, this.array );
  11300. }
  11301. this.array[ index + 0 ] = toHalfFloat( x );
  11302. this.array[ index + 1 ] = toHalfFloat( y );
  11303. return this;
  11304. }
  11305. setXYZ( index, x, y, z ) {
  11306. index *= this.itemSize;
  11307. if ( this.normalized ) {
  11308. x = normalize( x, this.array );
  11309. y = normalize( y, this.array );
  11310. z = normalize( z, this.array );
  11311. }
  11312. this.array[ index + 0 ] = toHalfFloat( x );
  11313. this.array[ index + 1 ] = toHalfFloat( y );
  11314. this.array[ index + 2 ] = toHalfFloat( z );
  11315. return this;
  11316. }
  11317. setXYZW( index, x, y, z, w ) {
  11318. index *= this.itemSize;
  11319. if ( this.normalized ) {
  11320. x = normalize( x, this.array );
  11321. y = normalize( y, this.array );
  11322. z = normalize( z, this.array );
  11323. w = normalize( w, this.array );
  11324. }
  11325. this.array[ index + 0 ] = toHalfFloat( x );
  11326. this.array[ index + 1 ] = toHalfFloat( y );
  11327. this.array[ index + 2 ] = toHalfFloat( z );
  11328. this.array[ index + 3 ] = toHalfFloat( w );
  11329. return this;
  11330. }
  11331. }
  11332. class Float32BufferAttribute extends BufferAttribute {
  11333. constructor( array, itemSize, normalized ) {
  11334. super( new Float32Array( array ), itemSize, normalized );
  11335. }
  11336. }
  11337. let _id$2 = 0;
  11338. const _m1$2 = /*@__PURE__*/ new Matrix4();
  11339. const _obj = /*@__PURE__*/ new Object3D();
  11340. const _offset = /*@__PURE__*/ new Vector3();
  11341. const _box$2 = /*@__PURE__*/ new Box3();
  11342. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  11343. const _vector$8 = /*@__PURE__*/ new Vector3();
  11344. class BufferGeometry extends EventDispatcher {
  11345. constructor() {
  11346. super();
  11347. this.isBufferGeometry = true;
  11348. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  11349. this.uuid = generateUUID();
  11350. this.name = '';
  11351. this.type = 'BufferGeometry';
  11352. this.index = null;
  11353. this.indirect = null;
  11354. this.attributes = {};
  11355. this.morphAttributes = {};
  11356. this.morphTargetsRelative = false;
  11357. this.groups = [];
  11358. this.boundingBox = null;
  11359. this.boundingSphere = null;
  11360. this.drawRange = { start: 0, count: Infinity };
  11361. this.userData = {};
  11362. }
  11363. getIndex() {
  11364. return this.index;
  11365. }
  11366. setIndex( index ) {
  11367. if ( Array.isArray( index ) ) {
  11368. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11369. } else {
  11370. this.index = index;
  11371. }
  11372. return this;
  11373. }
  11374. setIndirect( indirect ) {
  11375. this.indirect = indirect;
  11376. return this;
  11377. }
  11378. getIndirect() {
  11379. return this.indirect;
  11380. }
  11381. getAttribute( name ) {
  11382. return this.attributes[ name ];
  11383. }
  11384. setAttribute( name, attribute ) {
  11385. this.attributes[ name ] = attribute;
  11386. return this;
  11387. }
  11388. deleteAttribute( name ) {
  11389. delete this.attributes[ name ];
  11390. return this;
  11391. }
  11392. hasAttribute( name ) {
  11393. return this.attributes[ name ] !== undefined;
  11394. }
  11395. addGroup( start, count, materialIndex = 0 ) {
  11396. this.groups.push( {
  11397. start: start,
  11398. count: count,
  11399. materialIndex: materialIndex
  11400. } );
  11401. }
  11402. clearGroups() {
  11403. this.groups = [];
  11404. }
  11405. setDrawRange( start, count ) {
  11406. this.drawRange.start = start;
  11407. this.drawRange.count = count;
  11408. }
  11409. applyMatrix4( matrix ) {
  11410. const position = this.attributes.position;
  11411. if ( position !== undefined ) {
  11412. position.applyMatrix4( matrix );
  11413. position.needsUpdate = true;
  11414. }
  11415. const normal = this.attributes.normal;
  11416. if ( normal !== undefined ) {
  11417. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11418. normal.applyNormalMatrix( normalMatrix );
  11419. normal.needsUpdate = true;
  11420. }
  11421. const tangent = this.attributes.tangent;
  11422. if ( tangent !== undefined ) {
  11423. tangent.transformDirection( matrix );
  11424. tangent.needsUpdate = true;
  11425. }
  11426. if ( this.boundingBox !== null ) {
  11427. this.computeBoundingBox();
  11428. }
  11429. if ( this.boundingSphere !== null ) {
  11430. this.computeBoundingSphere();
  11431. }
  11432. return this;
  11433. }
  11434. applyQuaternion( q ) {
  11435. _m1$2.makeRotationFromQuaternion( q );
  11436. this.applyMatrix4( _m1$2 );
  11437. return this;
  11438. }
  11439. rotateX( angle ) {
  11440. // rotate geometry around world x-axis
  11441. _m1$2.makeRotationX( angle );
  11442. this.applyMatrix4( _m1$2 );
  11443. return this;
  11444. }
  11445. rotateY( angle ) {
  11446. // rotate geometry around world y-axis
  11447. _m1$2.makeRotationY( angle );
  11448. this.applyMatrix4( _m1$2 );
  11449. return this;
  11450. }
  11451. rotateZ( angle ) {
  11452. // rotate geometry around world z-axis
  11453. _m1$2.makeRotationZ( angle );
  11454. this.applyMatrix4( _m1$2 );
  11455. return this;
  11456. }
  11457. translate( x, y, z ) {
  11458. // translate geometry
  11459. _m1$2.makeTranslation( x, y, z );
  11460. this.applyMatrix4( _m1$2 );
  11461. return this;
  11462. }
  11463. scale( x, y, z ) {
  11464. // scale geometry
  11465. _m1$2.makeScale( x, y, z );
  11466. this.applyMatrix4( _m1$2 );
  11467. return this;
  11468. }
  11469. lookAt( vector ) {
  11470. _obj.lookAt( vector );
  11471. _obj.updateMatrix();
  11472. this.applyMatrix4( _obj.matrix );
  11473. return this;
  11474. }
  11475. center() {
  11476. this.computeBoundingBox();
  11477. this.boundingBox.getCenter( _offset ).negate();
  11478. this.translate( _offset.x, _offset.y, _offset.z );
  11479. return this;
  11480. }
  11481. setFromPoints( points ) {
  11482. const positionAttribute = this.getAttribute( 'position' );
  11483. if ( positionAttribute === undefined ) {
  11484. const position = [];
  11485. for ( let i = 0, l = points.length; i < l; i ++ ) {
  11486. const point = points[ i ];
  11487. position.push( point.x, point.y, point.z || 0 );
  11488. }
  11489. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11490. } else {
  11491. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  11492. for ( let i = 0; i < l; i ++ ) {
  11493. const point = points[ i ];
  11494. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  11495. }
  11496. if ( points.length > positionAttribute.count ) {
  11497. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  11498. }
  11499. positionAttribute.needsUpdate = true;
  11500. }
  11501. return this;
  11502. }
  11503. computeBoundingBox() {
  11504. if ( this.boundingBox === null ) {
  11505. this.boundingBox = new Box3();
  11506. }
  11507. const position = this.attributes.position;
  11508. const morphAttributesPosition = this.morphAttributes.position;
  11509. if ( position && position.isGLBufferAttribute ) {
  11510. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  11511. this.boundingBox.set(
  11512. new Vector3( - Infinity, - Infinity, - Infinity ),
  11513. new Vector3( + Infinity, + Infinity, + Infinity )
  11514. );
  11515. return;
  11516. }
  11517. if ( position !== undefined ) {
  11518. this.boundingBox.setFromBufferAttribute( position );
  11519. // process morph attributes if present
  11520. if ( morphAttributesPosition ) {
  11521. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11522. const morphAttribute = morphAttributesPosition[ i ];
  11523. _box$2.setFromBufferAttribute( morphAttribute );
  11524. if ( this.morphTargetsRelative ) {
  11525. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  11526. this.boundingBox.expandByPoint( _vector$8 );
  11527. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  11528. this.boundingBox.expandByPoint( _vector$8 );
  11529. } else {
  11530. this.boundingBox.expandByPoint( _box$2.min );
  11531. this.boundingBox.expandByPoint( _box$2.max );
  11532. }
  11533. }
  11534. }
  11535. } else {
  11536. this.boundingBox.makeEmpty();
  11537. }
  11538. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11539. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11540. }
  11541. }
  11542. computeBoundingSphere() {
  11543. if ( this.boundingSphere === null ) {
  11544. this.boundingSphere = new Sphere();
  11545. }
  11546. const position = this.attributes.position;
  11547. const morphAttributesPosition = this.morphAttributes.position;
  11548. if ( position && position.isGLBufferAttribute ) {
  11549. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  11550. this.boundingSphere.set( new Vector3(), Infinity );
  11551. return;
  11552. }
  11553. if ( position ) {
  11554. // first, find the center of the bounding sphere
  11555. const center = this.boundingSphere.center;
  11556. _box$2.setFromBufferAttribute( position );
  11557. // process morph attributes if present
  11558. if ( morphAttributesPosition ) {
  11559. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11560. const morphAttribute = morphAttributesPosition[ i ];
  11561. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11562. if ( this.morphTargetsRelative ) {
  11563. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  11564. _box$2.expandByPoint( _vector$8 );
  11565. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  11566. _box$2.expandByPoint( _vector$8 );
  11567. } else {
  11568. _box$2.expandByPoint( _boxMorphTargets.min );
  11569. _box$2.expandByPoint( _boxMorphTargets.max );
  11570. }
  11571. }
  11572. }
  11573. _box$2.getCenter( center );
  11574. // second, try to find a boundingSphere with a radius smaller than the
  11575. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11576. let maxRadiusSq = 0;
  11577. for ( let i = 0, il = position.count; i < il; i ++ ) {
  11578. _vector$8.fromBufferAttribute( position, i );
  11579. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11580. }
  11581. // process morph attributes if present
  11582. if ( morphAttributesPosition ) {
  11583. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11584. const morphAttribute = morphAttributesPosition[ i ];
  11585. const morphTargetsRelative = this.morphTargetsRelative;
  11586. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11587. _vector$8.fromBufferAttribute( morphAttribute, j );
  11588. if ( morphTargetsRelative ) {
  11589. _offset.fromBufferAttribute( position, j );
  11590. _vector$8.add( _offset );
  11591. }
  11592. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11593. }
  11594. }
  11595. }
  11596. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11597. if ( isNaN( this.boundingSphere.radius ) ) {
  11598. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11599. }
  11600. }
  11601. }
  11602. computeTangents() {
  11603. const index = this.index;
  11604. const attributes = this.attributes;
  11605. // based on http://www.terathon.com/code/tangent.html
  11606. // (per vertex tangents)
  11607. if ( index === null ||
  11608. attributes.position === undefined ||
  11609. attributes.normal === undefined ||
  11610. attributes.uv === undefined ) {
  11611. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  11612. return;
  11613. }
  11614. const positionAttribute = attributes.position;
  11615. const normalAttribute = attributes.normal;
  11616. const uvAttribute = attributes.uv;
  11617. if ( this.hasAttribute( 'tangent' ) === false ) {
  11618. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  11619. }
  11620. const tangentAttribute = this.getAttribute( 'tangent' );
  11621. const tan1 = [], tan2 = [];
  11622. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  11623. tan1[ i ] = new Vector3();
  11624. tan2[ i ] = new Vector3();
  11625. }
  11626. const vA = new Vector3(),
  11627. vB = new Vector3(),
  11628. vC = new Vector3(),
  11629. uvA = new Vector2(),
  11630. uvB = new Vector2(),
  11631. uvC = new Vector2(),
  11632. sdir = new Vector3(),
  11633. tdir = new Vector3();
  11634. function handleTriangle( a, b, c ) {
  11635. vA.fromBufferAttribute( positionAttribute, a );
  11636. vB.fromBufferAttribute( positionAttribute, b );
  11637. vC.fromBufferAttribute( positionAttribute, c );
  11638. uvA.fromBufferAttribute( uvAttribute, a );
  11639. uvB.fromBufferAttribute( uvAttribute, b );
  11640. uvC.fromBufferAttribute( uvAttribute, c );
  11641. vB.sub( vA );
  11642. vC.sub( vA );
  11643. uvB.sub( uvA );
  11644. uvC.sub( uvA );
  11645. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  11646. // silently ignore degenerate uv triangles having coincident or colinear vertices
  11647. if ( ! isFinite( r ) ) return;
  11648. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  11649. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  11650. tan1[ a ].add( sdir );
  11651. tan1[ b ].add( sdir );
  11652. tan1[ c ].add( sdir );
  11653. tan2[ a ].add( tdir );
  11654. tan2[ b ].add( tdir );
  11655. tan2[ c ].add( tdir );
  11656. }
  11657. let groups = this.groups;
  11658. if ( groups.length === 0 ) {
  11659. groups = [ {
  11660. start: 0,
  11661. count: index.count
  11662. } ];
  11663. }
  11664. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11665. const group = groups[ i ];
  11666. const start = group.start;
  11667. const count = group.count;
  11668. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11669. handleTriangle(
  11670. index.getX( j + 0 ),
  11671. index.getX( j + 1 ),
  11672. index.getX( j + 2 )
  11673. );
  11674. }
  11675. }
  11676. const tmp = new Vector3(), tmp2 = new Vector3();
  11677. const n = new Vector3(), n2 = new Vector3();
  11678. function handleVertex( v ) {
  11679. n.fromBufferAttribute( normalAttribute, v );
  11680. n2.copy( n );
  11681. const t = tan1[ v ];
  11682. // Gram-Schmidt orthogonalize
  11683. tmp.copy( t );
  11684. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  11685. // Calculate handedness
  11686. tmp2.crossVectors( n2, t );
  11687. const test = tmp2.dot( tan2[ v ] );
  11688. const w = ( test < 0.0 ) ? -1 : 1.0;
  11689. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  11690. }
  11691. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11692. const group = groups[ i ];
  11693. const start = group.start;
  11694. const count = group.count;
  11695. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11696. handleVertex( index.getX( j + 0 ) );
  11697. handleVertex( index.getX( j + 1 ) );
  11698. handleVertex( index.getX( j + 2 ) );
  11699. }
  11700. }
  11701. }
  11702. computeVertexNormals() {
  11703. const index = this.index;
  11704. const positionAttribute = this.getAttribute( 'position' );
  11705. if ( positionAttribute !== undefined ) {
  11706. let normalAttribute = this.getAttribute( 'normal' );
  11707. if ( normalAttribute === undefined ) {
  11708. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  11709. this.setAttribute( 'normal', normalAttribute );
  11710. } else {
  11711. // reset existing normals to zero
  11712. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  11713. normalAttribute.setXYZ( i, 0, 0, 0 );
  11714. }
  11715. }
  11716. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11717. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  11718. const cb = new Vector3(), ab = new Vector3();
  11719. // indexed elements
  11720. if ( index ) {
  11721. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  11722. const vA = index.getX( i + 0 );
  11723. const vB = index.getX( i + 1 );
  11724. const vC = index.getX( i + 2 );
  11725. pA.fromBufferAttribute( positionAttribute, vA );
  11726. pB.fromBufferAttribute( positionAttribute, vB );
  11727. pC.fromBufferAttribute( positionAttribute, vC );
  11728. cb.subVectors( pC, pB );
  11729. ab.subVectors( pA, pB );
  11730. cb.cross( ab );
  11731. nA.fromBufferAttribute( normalAttribute, vA );
  11732. nB.fromBufferAttribute( normalAttribute, vB );
  11733. nC.fromBufferAttribute( normalAttribute, vC );
  11734. nA.add( cb );
  11735. nB.add( cb );
  11736. nC.add( cb );
  11737. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  11738. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  11739. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  11740. }
  11741. } else {
  11742. // non-indexed elements (unconnected triangle soup)
  11743. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  11744. pA.fromBufferAttribute( positionAttribute, i + 0 );
  11745. pB.fromBufferAttribute( positionAttribute, i + 1 );
  11746. pC.fromBufferAttribute( positionAttribute, i + 2 );
  11747. cb.subVectors( pC, pB );
  11748. ab.subVectors( pA, pB );
  11749. cb.cross( ab );
  11750. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  11751. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  11752. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  11753. }
  11754. }
  11755. this.normalizeNormals();
  11756. normalAttribute.needsUpdate = true;
  11757. }
  11758. }
  11759. normalizeNormals() {
  11760. const normals = this.attributes.normal;
  11761. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  11762. _vector$8.fromBufferAttribute( normals, i );
  11763. _vector$8.normalize();
  11764. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  11765. }
  11766. }
  11767. toNonIndexed() {
  11768. function convertBufferAttribute( attribute, indices ) {
  11769. const array = attribute.array;
  11770. const itemSize = attribute.itemSize;
  11771. const normalized = attribute.normalized;
  11772. const array2 = new array.constructor( indices.length * itemSize );
  11773. let index = 0, index2 = 0;
  11774. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  11775. if ( attribute.isInterleavedBufferAttribute ) {
  11776. index = indices[ i ] * attribute.data.stride + attribute.offset;
  11777. } else {
  11778. index = indices[ i ] * itemSize;
  11779. }
  11780. for ( let j = 0; j < itemSize; j ++ ) {
  11781. array2[ index2 ++ ] = array[ index ++ ];
  11782. }
  11783. }
  11784. return new BufferAttribute( array2, itemSize, normalized );
  11785. }
  11786. //
  11787. if ( this.index === null ) {
  11788. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  11789. return this;
  11790. }
  11791. const geometry2 = new BufferGeometry();
  11792. const indices = this.index.array;
  11793. const attributes = this.attributes;
  11794. // attributes
  11795. for ( const name in attributes ) {
  11796. const attribute = attributes[ name ];
  11797. const newAttribute = convertBufferAttribute( attribute, indices );
  11798. geometry2.setAttribute( name, newAttribute );
  11799. }
  11800. // morph attributes
  11801. const morphAttributes = this.morphAttributes;
  11802. for ( const name in morphAttributes ) {
  11803. const morphArray = [];
  11804. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11805. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11806. const attribute = morphAttribute[ i ];
  11807. const newAttribute = convertBufferAttribute( attribute, indices );
  11808. morphArray.push( newAttribute );
  11809. }
  11810. geometry2.morphAttributes[ name ] = morphArray;
  11811. }
  11812. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  11813. // groups
  11814. const groups = this.groups;
  11815. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11816. const group = groups[ i ];
  11817. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11818. }
  11819. return geometry2;
  11820. }
  11821. toJSON() {
  11822. const data = {
  11823. metadata: {
  11824. version: 4.6,
  11825. type: 'BufferGeometry',
  11826. generator: 'BufferGeometry.toJSON'
  11827. }
  11828. };
  11829. // standard BufferGeometry serialization
  11830. data.uuid = this.uuid;
  11831. data.type = this.type;
  11832. if ( this.name !== '' ) data.name = this.name;
  11833. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11834. if ( this.parameters !== undefined ) {
  11835. const parameters = this.parameters;
  11836. for ( const key in parameters ) {
  11837. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11838. }
  11839. return data;
  11840. }
  11841. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  11842. data.data = { attributes: {} };
  11843. const index = this.index;
  11844. if ( index !== null ) {
  11845. data.data.index = {
  11846. type: index.array.constructor.name,
  11847. array: Array.prototype.slice.call( index.array )
  11848. };
  11849. }
  11850. const attributes = this.attributes;
  11851. for ( const key in attributes ) {
  11852. const attribute = attributes[ key ];
  11853. data.data.attributes[ key ] = attribute.toJSON( data.data );
  11854. }
  11855. const morphAttributes = {};
  11856. let hasMorphAttributes = false;
  11857. for ( const key in this.morphAttributes ) {
  11858. const attributeArray = this.morphAttributes[ key ];
  11859. const array = [];
  11860. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  11861. const attribute = attributeArray[ i ];
  11862. array.push( attribute.toJSON( data.data ) );
  11863. }
  11864. if ( array.length > 0 ) {
  11865. morphAttributes[ key ] = array;
  11866. hasMorphAttributes = true;
  11867. }
  11868. }
  11869. if ( hasMorphAttributes ) {
  11870. data.data.morphAttributes = morphAttributes;
  11871. data.data.morphTargetsRelative = this.morphTargetsRelative;
  11872. }
  11873. const groups = this.groups;
  11874. if ( groups.length > 0 ) {
  11875. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11876. }
  11877. const boundingSphere = this.boundingSphere;
  11878. if ( boundingSphere !== null ) {
  11879. data.data.boundingSphere = {
  11880. center: boundingSphere.center.toArray(),
  11881. radius: boundingSphere.radius
  11882. };
  11883. }
  11884. return data;
  11885. }
  11886. clone() {
  11887. return new this.constructor().copy( this );
  11888. }
  11889. copy( source ) {
  11890. // reset
  11891. this.index = null;
  11892. this.attributes = {};
  11893. this.morphAttributes = {};
  11894. this.groups = [];
  11895. this.boundingBox = null;
  11896. this.boundingSphere = null;
  11897. // used for storing cloned, shared data
  11898. const data = {};
  11899. // name
  11900. this.name = source.name;
  11901. // index
  11902. const index = source.index;
  11903. if ( index !== null ) {
  11904. this.setIndex( index.clone( data ) );
  11905. }
  11906. // attributes
  11907. const attributes = source.attributes;
  11908. for ( const name in attributes ) {
  11909. const attribute = attributes[ name ];
  11910. this.setAttribute( name, attribute.clone( data ) );
  11911. }
  11912. // morph attributes
  11913. const morphAttributes = source.morphAttributes;
  11914. for ( const name in morphAttributes ) {
  11915. const array = [];
  11916. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11917. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11918. array.push( morphAttribute[ i ].clone( data ) );
  11919. }
  11920. this.morphAttributes[ name ] = array;
  11921. }
  11922. this.morphTargetsRelative = source.morphTargetsRelative;
  11923. // groups
  11924. const groups = source.groups;
  11925. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11926. const group = groups[ i ];
  11927. this.addGroup( group.start, group.count, group.materialIndex );
  11928. }
  11929. // bounding box
  11930. const boundingBox = source.boundingBox;
  11931. if ( boundingBox !== null ) {
  11932. this.boundingBox = boundingBox.clone();
  11933. }
  11934. // bounding sphere
  11935. const boundingSphere = source.boundingSphere;
  11936. if ( boundingSphere !== null ) {
  11937. this.boundingSphere = boundingSphere.clone();
  11938. }
  11939. // draw range
  11940. this.drawRange.start = source.drawRange.start;
  11941. this.drawRange.count = source.drawRange.count;
  11942. // user data
  11943. this.userData = source.userData;
  11944. return this;
  11945. }
  11946. dispose() {
  11947. this.dispatchEvent( { type: 'dispose' } );
  11948. }
  11949. }
  11950. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  11951. const _ray$3 = /*@__PURE__*/ new Ray();
  11952. const _sphere$6 = /*@__PURE__*/ new Sphere();
  11953. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  11954. const _vA$1 = /*@__PURE__*/ new Vector3();
  11955. const _vB$1 = /*@__PURE__*/ new Vector3();
  11956. const _vC$1 = /*@__PURE__*/ new Vector3();
  11957. const _tempA = /*@__PURE__*/ new Vector3();
  11958. const _morphA = /*@__PURE__*/ new Vector3();
  11959. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  11960. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  11961. class Mesh extends Object3D {
  11962. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  11963. super();
  11964. this.isMesh = true;
  11965. this.type = 'Mesh';
  11966. this.geometry = geometry;
  11967. this.material = material;
  11968. this.updateMorphTargets();
  11969. }
  11970. copy( source, recursive ) {
  11971. super.copy( source, recursive );
  11972. if ( source.morphTargetInfluences !== undefined ) {
  11973. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  11974. }
  11975. if ( source.morphTargetDictionary !== undefined ) {
  11976. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  11977. }
  11978. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  11979. this.geometry = source.geometry;
  11980. return this;
  11981. }
  11982. updateMorphTargets() {
  11983. const geometry = this.geometry;
  11984. const morphAttributes = geometry.morphAttributes;
  11985. const keys = Object.keys( morphAttributes );
  11986. if ( keys.length > 0 ) {
  11987. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  11988. if ( morphAttribute !== undefined ) {
  11989. this.morphTargetInfluences = [];
  11990. this.morphTargetDictionary = {};
  11991. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  11992. const name = morphAttribute[ m ].name || String( m );
  11993. this.morphTargetInfluences.push( 0 );
  11994. this.morphTargetDictionary[ name ] = m;
  11995. }
  11996. }
  11997. }
  11998. }
  11999. getVertexPosition( index, target ) {
  12000. const geometry = this.geometry;
  12001. const position = geometry.attributes.position;
  12002. const morphPosition = geometry.morphAttributes.position;
  12003. const morphTargetsRelative = geometry.morphTargetsRelative;
  12004. target.fromBufferAttribute( position, index );
  12005. const morphInfluences = this.morphTargetInfluences;
  12006. if ( morphPosition && morphInfluences ) {
  12007. _morphA.set( 0, 0, 0 );
  12008. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  12009. const influence = morphInfluences[ i ];
  12010. const morphAttribute = morphPosition[ i ];
  12011. if ( influence === 0 ) continue;
  12012. _tempA.fromBufferAttribute( morphAttribute, index );
  12013. if ( morphTargetsRelative ) {
  12014. _morphA.addScaledVector( _tempA, influence );
  12015. } else {
  12016. _morphA.addScaledVector( _tempA.sub( target ), influence );
  12017. }
  12018. }
  12019. target.add( _morphA );
  12020. }
  12021. return target;
  12022. }
  12023. raycast( raycaster, intersects ) {
  12024. const geometry = this.geometry;
  12025. const material = this.material;
  12026. const matrixWorld = this.matrixWorld;
  12027. if ( material === undefined ) return;
  12028. // test with bounding sphere in world space
  12029. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12030. _sphere$6.copy( geometry.boundingSphere );
  12031. _sphere$6.applyMatrix4( matrixWorld );
  12032. // check distance from ray origin to bounding sphere
  12033. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  12034. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  12035. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  12036. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  12037. }
  12038. // convert ray to local space of mesh
  12039. _inverseMatrix$3.copy( matrixWorld ).invert();
  12040. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  12041. // test with bounding box in local space
  12042. if ( geometry.boundingBox !== null ) {
  12043. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  12044. }
  12045. // test for intersections with geometry
  12046. this._computeIntersections( raycaster, intersects, _ray$3 );
  12047. }
  12048. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  12049. let intersection;
  12050. const geometry = this.geometry;
  12051. const material = this.material;
  12052. const index = geometry.index;
  12053. const position = geometry.attributes.position;
  12054. const uv = geometry.attributes.uv;
  12055. const uv1 = geometry.attributes.uv1;
  12056. const normal = geometry.attributes.normal;
  12057. const groups = geometry.groups;
  12058. const drawRange = geometry.drawRange;
  12059. if ( index !== null ) {
  12060. // indexed buffer geometry
  12061. if ( Array.isArray( material ) ) {
  12062. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12063. const group = groups[ i ];
  12064. const groupMaterial = material[ group.materialIndex ];
  12065. const start = Math.max( group.start, drawRange.start );
  12066. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12067. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12068. const a = index.getX( j );
  12069. const b = index.getX( j + 1 );
  12070. const c = index.getX( j + 2 );
  12071. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12072. if ( intersection ) {
  12073. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12074. intersection.face.materialIndex = group.materialIndex;
  12075. intersects.push( intersection );
  12076. }
  12077. }
  12078. }
  12079. } else {
  12080. const start = Math.max( 0, drawRange.start );
  12081. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12082. for ( let i = start, il = end; i < il; i += 3 ) {
  12083. const a = index.getX( i );
  12084. const b = index.getX( i + 1 );
  12085. const c = index.getX( i + 2 );
  12086. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12087. if ( intersection ) {
  12088. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12089. intersects.push( intersection );
  12090. }
  12091. }
  12092. }
  12093. } else if ( position !== undefined ) {
  12094. // non-indexed buffer geometry
  12095. if ( Array.isArray( material ) ) {
  12096. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12097. const group = groups[ i ];
  12098. const groupMaterial = material[ group.materialIndex ];
  12099. const start = Math.max( group.start, drawRange.start );
  12100. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12101. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12102. const a = j;
  12103. const b = j + 1;
  12104. const c = j + 2;
  12105. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12106. if ( intersection ) {
  12107. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12108. intersection.face.materialIndex = group.materialIndex;
  12109. intersects.push( intersection );
  12110. }
  12111. }
  12112. }
  12113. } else {
  12114. const start = Math.max( 0, drawRange.start );
  12115. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12116. for ( let i = start, il = end; i < il; i += 3 ) {
  12117. const a = i;
  12118. const b = i + 1;
  12119. const c = i + 2;
  12120. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12121. if ( intersection ) {
  12122. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12123. intersects.push( intersection );
  12124. }
  12125. }
  12126. }
  12127. }
  12128. }
  12129. }
  12130. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  12131. let intersect;
  12132. if ( material.side === BackSide ) {
  12133. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12134. } else {
  12135. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  12136. }
  12137. if ( intersect === null ) return null;
  12138. _intersectionPointWorld.copy( point );
  12139. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12140. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12141. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12142. return {
  12143. distance: distance,
  12144. point: _intersectionPointWorld.clone(),
  12145. object: object
  12146. };
  12147. }
  12148. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  12149. object.getVertexPosition( a, _vA$1 );
  12150. object.getVertexPosition( b, _vB$1 );
  12151. object.getVertexPosition( c, _vC$1 );
  12152. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  12153. if ( intersection ) {
  12154. const barycoord = new Vector3();
  12155. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  12156. if ( uv ) {
  12157. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  12158. }
  12159. if ( uv1 ) {
  12160. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  12161. }
  12162. if ( normal ) {
  12163. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  12164. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  12165. intersection.normal.multiplyScalar( -1 );
  12166. }
  12167. }
  12168. const face = {
  12169. a: a,
  12170. b: b,
  12171. c: c,
  12172. normal: new Vector3(),
  12173. materialIndex: 0
  12174. };
  12175. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  12176. intersection.face = face;
  12177. intersection.barycoord = barycoord;
  12178. }
  12179. return intersection;
  12180. }
  12181. class BoxGeometry extends BufferGeometry {
  12182. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  12183. super();
  12184. this.type = 'BoxGeometry';
  12185. this.parameters = {
  12186. width: width,
  12187. height: height,
  12188. depth: depth,
  12189. widthSegments: widthSegments,
  12190. heightSegments: heightSegments,
  12191. depthSegments: depthSegments
  12192. };
  12193. const scope = this;
  12194. // segments
  12195. widthSegments = Math.floor( widthSegments );
  12196. heightSegments = Math.floor( heightSegments );
  12197. depthSegments = Math.floor( depthSegments );
  12198. // buffers
  12199. const indices = [];
  12200. const vertices = [];
  12201. const normals = [];
  12202. const uvs = [];
  12203. // helper variables
  12204. let numberOfVertices = 0;
  12205. let groupStart = 0;
  12206. // build each side of the box geometry
  12207. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  12208. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  12209. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  12210. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  12211. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  12212. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  12213. // build geometry
  12214. this.setIndex( indices );
  12215. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12216. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12217. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12218. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  12219. const segmentWidth = width / gridX;
  12220. const segmentHeight = height / gridY;
  12221. const widthHalf = width / 2;
  12222. const heightHalf = height / 2;
  12223. const depthHalf = depth / 2;
  12224. const gridX1 = gridX + 1;
  12225. const gridY1 = gridY + 1;
  12226. let vertexCounter = 0;
  12227. let groupCount = 0;
  12228. const vector = new Vector3();
  12229. // generate vertices, normals and uvs
  12230. for ( let iy = 0; iy < gridY1; iy ++ ) {
  12231. const y = iy * segmentHeight - heightHalf;
  12232. for ( let ix = 0; ix < gridX1; ix ++ ) {
  12233. const x = ix * segmentWidth - widthHalf;
  12234. // set values to correct vector component
  12235. vector[ u ] = x * udir;
  12236. vector[ v ] = y * vdir;
  12237. vector[ w ] = depthHalf;
  12238. // now apply vector to vertex buffer
  12239. vertices.push( vector.x, vector.y, vector.z );
  12240. // set values to correct vector component
  12241. vector[ u ] = 0;
  12242. vector[ v ] = 0;
  12243. vector[ w ] = depth > 0 ? 1 : -1;
  12244. // now apply vector to normal buffer
  12245. normals.push( vector.x, vector.y, vector.z );
  12246. // uvs
  12247. uvs.push( ix / gridX );
  12248. uvs.push( 1 - ( iy / gridY ) );
  12249. // counters
  12250. vertexCounter += 1;
  12251. }
  12252. }
  12253. // indices
  12254. // 1. you need three indices to draw a single face
  12255. // 2. a single segment consists of two faces
  12256. // 3. so we need to generate six (2*3) indices per segment
  12257. for ( let iy = 0; iy < gridY; iy ++ ) {
  12258. for ( let ix = 0; ix < gridX; ix ++ ) {
  12259. const a = numberOfVertices + ix + gridX1 * iy;
  12260. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  12261. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  12262. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  12263. // faces
  12264. indices.push( a, b, d );
  12265. indices.push( b, c, d );
  12266. // increase counter
  12267. groupCount += 6;
  12268. }
  12269. }
  12270. // add a group to the geometry. this will ensure multi material support
  12271. scope.addGroup( groupStart, groupCount, materialIndex );
  12272. // calculate new start value for groups
  12273. groupStart += groupCount;
  12274. // update total number of vertices
  12275. numberOfVertices += vertexCounter;
  12276. }
  12277. }
  12278. copy( source ) {
  12279. super.copy( source );
  12280. this.parameters = Object.assign( {}, source.parameters );
  12281. return this;
  12282. }
  12283. static fromJSON( data ) {
  12284. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  12285. }
  12286. }
  12287. /**
  12288. * Uniform Utilities
  12289. */
  12290. function cloneUniforms( src ) {
  12291. const dst = {};
  12292. for ( const u in src ) {
  12293. dst[ u ] = {};
  12294. for ( const p in src[ u ] ) {
  12295. const property = src[ u ][ p ];
  12296. if ( property && ( property.isColor ||
  12297. property.isMatrix3 || property.isMatrix4 ||
  12298. property.isVector2 || property.isVector3 || property.isVector4 ||
  12299. property.isTexture || property.isQuaternion ) ) {
  12300. if ( property.isRenderTargetTexture ) {
  12301. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  12302. dst[ u ][ p ] = null;
  12303. } else {
  12304. dst[ u ][ p ] = property.clone();
  12305. }
  12306. } else if ( Array.isArray( property ) ) {
  12307. dst[ u ][ p ] = property.slice();
  12308. } else {
  12309. dst[ u ][ p ] = property;
  12310. }
  12311. }
  12312. }
  12313. return dst;
  12314. }
  12315. function mergeUniforms( uniforms ) {
  12316. const merged = {};
  12317. for ( let u = 0; u < uniforms.length; u ++ ) {
  12318. const tmp = cloneUniforms( uniforms[ u ] );
  12319. for ( const p in tmp ) {
  12320. merged[ p ] = tmp[ p ];
  12321. }
  12322. }
  12323. return merged;
  12324. }
  12325. function cloneUniformsGroups( src ) {
  12326. const dst = [];
  12327. for ( let u = 0; u < src.length; u ++ ) {
  12328. dst.push( src[ u ].clone() );
  12329. }
  12330. return dst;
  12331. }
  12332. function getUnlitUniformColorSpace( renderer ) {
  12333. const currentRenderTarget = renderer.getRenderTarget();
  12334. if ( currentRenderTarget === null ) {
  12335. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  12336. return renderer.outputColorSpace;
  12337. }
  12338. // https://github.com/mrdoob/three.js/issues/27868
  12339. if ( currentRenderTarget.isXRRenderTarget === true ) {
  12340. return currentRenderTarget.texture.colorSpace;
  12341. }
  12342. return ColorManagement.workingColorSpace;
  12343. }
  12344. // Legacy
  12345. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  12346. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12347. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12348. class ShaderMaterial extends Material {
  12349. constructor( parameters ) {
  12350. super();
  12351. this.isShaderMaterial = true;
  12352. this.type = 'ShaderMaterial';
  12353. this.defines = {};
  12354. this.uniforms = {};
  12355. this.uniformsGroups = [];
  12356. this.vertexShader = default_vertex;
  12357. this.fragmentShader = default_fragment;
  12358. this.linewidth = 1;
  12359. this.wireframe = false;
  12360. this.wireframeLinewidth = 1;
  12361. this.fog = false; // set to use scene fog
  12362. this.lights = false; // set to use scene lights
  12363. this.clipping = false; // set to use user-defined clipping planes
  12364. this.forceSinglePass = true;
  12365. this.extensions = {
  12366. clipCullDistance: false, // set to use vertex shader clipping
  12367. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  12368. };
  12369. // When rendered geometry doesn't include these attributes but the material does,
  12370. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12371. this.defaultAttributeValues = {
  12372. 'color': [ 1, 1, 1 ],
  12373. 'uv': [ 0, 0 ],
  12374. 'uv1': [ 0, 0 ]
  12375. };
  12376. this.index0AttributeName = undefined;
  12377. this.uniformsNeedUpdate = false;
  12378. this.glslVersion = null;
  12379. if ( parameters !== undefined ) {
  12380. this.setValues( parameters );
  12381. }
  12382. }
  12383. copy( source ) {
  12384. super.copy( source );
  12385. this.fragmentShader = source.fragmentShader;
  12386. this.vertexShader = source.vertexShader;
  12387. this.uniforms = cloneUniforms( source.uniforms );
  12388. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  12389. this.defines = Object.assign( {}, source.defines );
  12390. this.wireframe = source.wireframe;
  12391. this.wireframeLinewidth = source.wireframeLinewidth;
  12392. this.fog = source.fog;
  12393. this.lights = source.lights;
  12394. this.clipping = source.clipping;
  12395. this.extensions = Object.assign( {}, source.extensions );
  12396. this.glslVersion = source.glslVersion;
  12397. return this;
  12398. }
  12399. toJSON( meta ) {
  12400. const data = super.toJSON( meta );
  12401. data.glslVersion = this.glslVersion;
  12402. data.uniforms = {};
  12403. for ( const name in this.uniforms ) {
  12404. const uniform = this.uniforms[ name ];
  12405. const value = uniform.value;
  12406. if ( value && value.isTexture ) {
  12407. data.uniforms[ name ] = {
  12408. type: 't',
  12409. value: value.toJSON( meta ).uuid
  12410. };
  12411. } else if ( value && value.isColor ) {
  12412. data.uniforms[ name ] = {
  12413. type: 'c',
  12414. value: value.getHex()
  12415. };
  12416. } else if ( value && value.isVector2 ) {
  12417. data.uniforms[ name ] = {
  12418. type: 'v2',
  12419. value: value.toArray()
  12420. };
  12421. } else if ( value && value.isVector3 ) {
  12422. data.uniforms[ name ] = {
  12423. type: 'v3',
  12424. value: value.toArray()
  12425. };
  12426. } else if ( value && value.isVector4 ) {
  12427. data.uniforms[ name ] = {
  12428. type: 'v4',
  12429. value: value.toArray()
  12430. };
  12431. } else if ( value && value.isMatrix3 ) {
  12432. data.uniforms[ name ] = {
  12433. type: 'm3',
  12434. value: value.toArray()
  12435. };
  12436. } else if ( value && value.isMatrix4 ) {
  12437. data.uniforms[ name ] = {
  12438. type: 'm4',
  12439. value: value.toArray()
  12440. };
  12441. } else {
  12442. data.uniforms[ name ] = {
  12443. value: value
  12444. };
  12445. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12446. }
  12447. }
  12448. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  12449. data.vertexShader = this.vertexShader;
  12450. data.fragmentShader = this.fragmentShader;
  12451. data.lights = this.lights;
  12452. data.clipping = this.clipping;
  12453. const extensions = {};
  12454. for ( const key in this.extensions ) {
  12455. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  12456. }
  12457. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  12458. return data;
  12459. }
  12460. }
  12461. /**
  12462. * Abstract base class for cameras. This class should always be inherited
  12463. * when you build a new camera.
  12464. *
  12465. * @abstract
  12466. * @augments Object3D
  12467. */
  12468. class Camera extends Object3D {
  12469. /**
  12470. * Constructs a new camera.
  12471. */
  12472. constructor() {
  12473. super();
  12474. /**
  12475. * This flag can be used for type testing.
  12476. *
  12477. * @type {boolean}
  12478. * @readonly
  12479. * @default true
  12480. */
  12481. this.isCamera = true;
  12482. this.type = 'Camera';
  12483. /**
  12484. * The inverse of the camera's world matrix.
  12485. *
  12486. * @type {Matrix4}
  12487. */
  12488. this.matrixWorldInverse = new Matrix4();
  12489. /**
  12490. * The camera's projection matrix.
  12491. *
  12492. * @type {Matrix4}
  12493. */
  12494. this.projectionMatrix = new Matrix4();
  12495. /**
  12496. * The inverse of the camera's prjection matrix.
  12497. *
  12498. * @type {Matrix4}
  12499. */
  12500. this.projectionMatrixInverse = new Matrix4();
  12501. /**
  12502. * The coordinate system in which the camrea is used.
  12503. *
  12504. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  12505. */
  12506. this.coordinateSystem = WebGLCoordinateSystem;
  12507. }
  12508. copy( source, recursive ) {
  12509. super.copy( source, recursive );
  12510. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  12511. this.projectionMatrix.copy( source.projectionMatrix );
  12512. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  12513. this.coordinateSystem = source.coordinateSystem;
  12514. return this;
  12515. }
  12516. /**
  12517. * Returns a vector representing the ("look") direction of the 3D object in world space.
  12518. *
  12519. * This method is overwritten since cameras have a different forward vector compared to other
  12520. * 3D objects. A camera looks down its local, negative z-axis by default.
  12521. *
  12522. * @param {Vector3} target - The target vector the result is stored to.
  12523. * @return {Vector3} The 3D object's direction in world space.
  12524. */
  12525. getWorldDirection( target ) {
  12526. return super.getWorldDirection( target ).negate();
  12527. }
  12528. updateMatrixWorld( force ) {
  12529. super.updateMatrixWorld( force );
  12530. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12531. }
  12532. updateWorldMatrix( updateParents, updateChildren ) {
  12533. super.updateWorldMatrix( updateParents, updateChildren );
  12534. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12535. }
  12536. clone() {
  12537. return new this.constructor().copy( this );
  12538. }
  12539. }
  12540. const _v3$1 = /*@__PURE__*/ new Vector3();
  12541. const _minTarget = /*@__PURE__*/ new Vector2();
  12542. const _maxTarget = /*@__PURE__*/ new Vector2();
  12543. /**
  12544. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  12545. *
  12546. * This projection mode is designed to mimic the way the human eye sees. It
  12547. * is the most common projection mode used for rendering a 3D scene.
  12548. *
  12549. * @augments Camera
  12550. */
  12551. class PerspectiveCamera extends Camera {
  12552. /**
  12553. * Constructs a new perspective camera.
  12554. *
  12555. * @param {number} [fov=50] - The vertical field of view.
  12556. * @param {number} [aspect=1] - The aspect ratio.
  12557. * @param {number} [near=0.1] - The camera's near plane.
  12558. * @param {number} [far=2000] - The camera's far plane.
  12559. */
  12560. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  12561. super();
  12562. /**
  12563. * This flag can be used for type testing.
  12564. *
  12565. * @type {boolean}
  12566. * @readonly
  12567. * @default true
  12568. */
  12569. this.isPerspectiveCamera = true;
  12570. this.type = 'PerspectiveCamera';
  12571. /**
  12572. * The vertical field of view, from bottom to top of view,
  12573. * in degrees.
  12574. *
  12575. * @type {number}
  12576. * @default 50
  12577. */
  12578. this.fov = fov;
  12579. /**
  12580. * The zoom factor of the camera.
  12581. *
  12582. * @type {number}
  12583. * @default 1
  12584. */
  12585. this.zoom = 1;
  12586. /**
  12587. * The camera's near plane. The valid range is greater than `0`
  12588. * and less than the current value of {@link PerspectiveCamera#far}.
  12589. *
  12590. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  12591. * valid value for a perspective camera's near plane.
  12592. *
  12593. * @type {number}
  12594. * @default 0.1
  12595. */
  12596. this.near = near;
  12597. /**
  12598. * The camera's far plane. Must be greater than the
  12599. * current value of {@link PerspectiveCamera#near}.
  12600. *
  12601. * @type {number}
  12602. * @default 2000
  12603. */
  12604. this.far = far;
  12605. /**
  12606. * Object distance used for stereoscopy and depth-of-field effects. This
  12607. * parameter does not influence the projection matrix unless a
  12608. * {@link StereoCamera} is being used.
  12609. *
  12610. * @type {number}
  12611. * @default 10
  12612. */
  12613. this.focus = 10;
  12614. /**
  12615. * The aspect ratio, usually the canvas width / canvas height.
  12616. *
  12617. * @type {number}
  12618. * @default 1
  12619. */
  12620. this.aspect = aspect;
  12621. /**
  12622. * Represents the frustum window specification. This property should not be edited
  12623. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  12624. *
  12625. * @type {?Object}
  12626. * @default null
  12627. */
  12628. this.view = null;
  12629. /**
  12630. * Film size used for the larger axis. Default is `35` (millimeters). This
  12631. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  12632. * is set to a nonzero value.
  12633. *
  12634. * @type {number}
  12635. * @default 35
  12636. */
  12637. this.filmGauge = 35;
  12638. /**
  12639. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  12640. *
  12641. * @type {number}
  12642. * @default 0
  12643. */
  12644. this.filmOffset = 0;
  12645. this.updateProjectionMatrix();
  12646. }
  12647. copy( source, recursive ) {
  12648. super.copy( source, recursive );
  12649. this.fov = source.fov;
  12650. this.zoom = source.zoom;
  12651. this.near = source.near;
  12652. this.far = source.far;
  12653. this.focus = source.focus;
  12654. this.aspect = source.aspect;
  12655. this.view = source.view === null ? null : Object.assign( {}, source.view );
  12656. this.filmGauge = source.filmGauge;
  12657. this.filmOffset = source.filmOffset;
  12658. return this;
  12659. }
  12660. /**
  12661. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  12662. *
  12663. * The default film gauge is 35, so that the focal length can be specified for
  12664. * a 35mm (full frame) camera.
  12665. *
  12666. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  12667. */
  12668. setFocalLength( focalLength ) {
  12669. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  12670. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  12671. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  12672. this.updateProjectionMatrix();
  12673. }
  12674. /**
  12675. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  12676. * {@link PerspectiveCamera#filmGauge}.
  12677. *
  12678. * @return {number} The computed focal length.
  12679. */
  12680. getFocalLength() {
  12681. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  12682. return 0.5 * this.getFilmHeight() / vExtentSlope;
  12683. }
  12684. /**
  12685. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  12686. *
  12687. * @return {number} The effective FOV.
  12688. */
  12689. getEffectiveFOV() {
  12690. return RAD2DEG * 2 * Math.atan(
  12691. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  12692. }
  12693. /**
  12694. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12695. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12696. *
  12697. * @return {number} The film width.
  12698. */
  12699. getFilmWidth() {
  12700. // film not completely covered in portrait format (aspect < 1)
  12701. return this.filmGauge * Math.min( this.aspect, 1 );
  12702. }
  12703. /**
  12704. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12705. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12706. *
  12707. * @return {number} The film width.
  12708. */
  12709. getFilmHeight() {
  12710. // film not completely covered in landscape format (aspect > 1)
  12711. return this.filmGauge / Math.max( this.aspect, 1 );
  12712. }
  12713. /**
  12714. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  12715. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  12716. *
  12717. * @param {number} distance - The viewing distance.
  12718. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  12719. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  12720. */
  12721. getViewBounds( distance, minTarget, maxTarget ) {
  12722. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12723. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12724. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12725. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12726. }
  12727. /**
  12728. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  12729. *
  12730. * @param {number} distance - The viewing distance.
  12731. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  12732. * @returns {Vector2} The view size.
  12733. */
  12734. getViewSize( distance, target ) {
  12735. this.getViewBounds( distance, _minTarget, _maxTarget );
  12736. return target.subVectors( _maxTarget, _minTarget );
  12737. }
  12738. /**
  12739. * Sets an offset in a larger frustum. This is useful for multi-window or
  12740. * multi-monitor/multi-machine setups.
  12741. *
  12742. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  12743. * the monitors are in grid like this
  12744. *```
  12745. * +---+---+---+
  12746. * | A | B | C |
  12747. * +---+---+---+
  12748. * | D | E | F |
  12749. * +---+---+---+
  12750. *```
  12751. * then for each monitor you would call it like this:
  12752. *```js
  12753. * const w = 1920;
  12754. * const h = 1080;
  12755. * const fullWidth = w * 3;
  12756. * const fullHeight = h * 2;
  12757. *
  12758. * // --A--
  12759. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  12760. * // --B--
  12761. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  12762. * // --C--
  12763. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  12764. * // --D--
  12765. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  12766. * // --E--
  12767. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  12768. * // --F--
  12769. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  12770. * ```
  12771. *
  12772. * Note there is no reason monitors have to be the same size or in a grid.
  12773. *
  12774. * @param {number} fullWidth - The full width of multiview setup.
  12775. * @param {number} fullHeight - The full height of multiview setup.
  12776. * @param {number} x - The horizontal offset of the subcamera.
  12777. * @param {number} y - The vertical offset of the subcamera.
  12778. * @param {number} width - The width of subcamera.
  12779. * @param {number} height - The height of subcamera.
  12780. */
  12781. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  12782. this.aspect = fullWidth / fullHeight;
  12783. if ( this.view === null ) {
  12784. this.view = {
  12785. enabled: true,
  12786. fullWidth: 1,
  12787. fullHeight: 1,
  12788. offsetX: 0,
  12789. offsetY: 0,
  12790. width: 1,
  12791. height: 1
  12792. };
  12793. }
  12794. this.view.enabled = true;
  12795. this.view.fullWidth = fullWidth;
  12796. this.view.fullHeight = fullHeight;
  12797. this.view.offsetX = x;
  12798. this.view.offsetY = y;
  12799. this.view.width = width;
  12800. this.view.height = height;
  12801. this.updateProjectionMatrix();
  12802. }
  12803. /**
  12804. * Removes the view offset from the projection matrix.
  12805. */
  12806. clearViewOffset() {
  12807. if ( this.view !== null ) {
  12808. this.view.enabled = false;
  12809. }
  12810. this.updateProjectionMatrix();
  12811. }
  12812. /**
  12813. * Updates the camera's projection matrix. Must be called after any change of
  12814. * camera properties.
  12815. */
  12816. updateProjectionMatrix() {
  12817. const near = this.near;
  12818. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  12819. let height = 2 * top;
  12820. let width = this.aspect * height;
  12821. let left = -0.5 * width;
  12822. const view = this.view;
  12823. if ( this.view !== null && this.view.enabled ) {
  12824. const fullWidth = view.fullWidth,
  12825. fullHeight = view.fullHeight;
  12826. left += view.offsetX * width / fullWidth;
  12827. top -= view.offsetY * height / fullHeight;
  12828. width *= view.width / fullWidth;
  12829. height *= view.height / fullHeight;
  12830. }
  12831. const skew = this.filmOffset;
  12832. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  12833. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  12834. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  12835. }
  12836. toJSON( meta ) {
  12837. const data = super.toJSON( meta );
  12838. data.object.fov = this.fov;
  12839. data.object.zoom = this.zoom;
  12840. data.object.near = this.near;
  12841. data.object.far = this.far;
  12842. data.object.focus = this.focus;
  12843. data.object.aspect = this.aspect;
  12844. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  12845. data.object.filmGauge = this.filmGauge;
  12846. data.object.filmOffset = this.filmOffset;
  12847. return data;
  12848. }
  12849. }
  12850. const fov = -90; // negative fov is not an error
  12851. const aspect = 1;
  12852. /**
  12853. * A special type of camera that is positioned in 3D space to render its surroundings into a
  12854. * cube render target. The render target can then be used as an environment map for rendering
  12855. * realtime reflections in your scene.
  12856. *
  12857. * ```js
  12858. * // Create cube render target
  12859. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  12860. *
  12861. * // Create cube camera
  12862. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  12863. * scene.add( cubeCamera );
  12864. *
  12865. * // Create car
  12866. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  12867. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  12868. * scene.add( car );
  12869. *
  12870. * // Update the render target cube
  12871. * car.visible = false;
  12872. * cubeCamera.position.copy( car.position );
  12873. * cubeCamera.update( renderer, scene );
  12874. *
  12875. * // Render the scene
  12876. * car.visible = true;
  12877. * renderer.render( scene, camera );
  12878. * ```
  12879. *
  12880. * @augments Object3D
  12881. */
  12882. class CubeCamera extends Object3D {
  12883. /**
  12884. * Constructs a new cube camera.
  12885. *
  12886. * @param {number} near - The camera's near plane.
  12887. * @param {number} far - The camera's far plane.
  12888. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  12889. */
  12890. constructor( near, far, renderTarget ) {
  12891. super();
  12892. this.type = 'CubeCamera';
  12893. /**
  12894. * A reference to the cube render target.
  12895. *
  12896. * @type {WebGLCubeRenderTarget}
  12897. */
  12898. this.renderTarget = renderTarget;
  12899. /**
  12900. * The current active coordinate system.
  12901. *
  12902. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  12903. * @default null
  12904. */
  12905. this.coordinateSystem = null;
  12906. /**
  12907. * The current active mipmap level
  12908. *
  12909. * @type {number}
  12910. * @default 0
  12911. */
  12912. this.activeMipmapLevel = 0;
  12913. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  12914. cameraPX.layers = this.layers;
  12915. this.add( cameraPX );
  12916. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  12917. cameraNX.layers = this.layers;
  12918. this.add( cameraNX );
  12919. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  12920. cameraPY.layers = this.layers;
  12921. this.add( cameraPY );
  12922. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  12923. cameraNY.layers = this.layers;
  12924. this.add( cameraNY );
  12925. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  12926. cameraPZ.layers = this.layers;
  12927. this.add( cameraPZ );
  12928. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  12929. cameraNZ.layers = this.layers;
  12930. this.add( cameraNZ );
  12931. }
  12932. /**
  12933. * Must be called when the coordinate system of the cube camera is changed.
  12934. */
  12935. updateCoordinateSystem() {
  12936. const coordinateSystem = this.coordinateSystem;
  12937. const cameras = this.children.concat();
  12938. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  12939. for ( const camera of cameras ) this.remove( camera );
  12940. if ( coordinateSystem === WebGLCoordinateSystem ) {
  12941. cameraPX.up.set( 0, 1, 0 );
  12942. cameraPX.lookAt( 1, 0, 0 );
  12943. cameraNX.up.set( 0, 1, 0 );
  12944. cameraNX.lookAt( -1, 0, 0 );
  12945. cameraPY.up.set( 0, 0, -1 );
  12946. cameraPY.lookAt( 0, 1, 0 );
  12947. cameraNY.up.set( 0, 0, 1 );
  12948. cameraNY.lookAt( 0, -1, 0 );
  12949. cameraPZ.up.set( 0, 1, 0 );
  12950. cameraPZ.lookAt( 0, 0, 1 );
  12951. cameraNZ.up.set( 0, 1, 0 );
  12952. cameraNZ.lookAt( 0, 0, -1 );
  12953. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  12954. cameraPX.up.set( 0, -1, 0 );
  12955. cameraPX.lookAt( -1, 0, 0 );
  12956. cameraNX.up.set( 0, -1, 0 );
  12957. cameraNX.lookAt( 1, 0, 0 );
  12958. cameraPY.up.set( 0, 0, 1 );
  12959. cameraPY.lookAt( 0, 1, 0 );
  12960. cameraNY.up.set( 0, 0, -1 );
  12961. cameraNY.lookAt( 0, -1, 0 );
  12962. cameraPZ.up.set( 0, -1, 0 );
  12963. cameraPZ.lookAt( 0, 0, 1 );
  12964. cameraNZ.up.set( 0, -1, 0 );
  12965. cameraNZ.lookAt( 0, 0, -1 );
  12966. } else {
  12967. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  12968. }
  12969. for ( const camera of cameras ) {
  12970. this.add( camera );
  12971. camera.updateMatrixWorld();
  12972. }
  12973. }
  12974. /**
  12975. * Calling this method will render the given scene with the given renderer
  12976. * into the cube render target of the camera.
  12977. *
  12978. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  12979. * @param {Scene} scene - The scene to render.
  12980. */
  12981. update( renderer, scene ) {
  12982. if ( this.parent === null ) this.updateMatrixWorld();
  12983. const { renderTarget, activeMipmapLevel } = this;
  12984. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  12985. this.coordinateSystem = renderer.coordinateSystem;
  12986. this.updateCoordinateSystem();
  12987. }
  12988. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  12989. const currentRenderTarget = renderer.getRenderTarget();
  12990. const currentActiveCubeFace = renderer.getActiveCubeFace();
  12991. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  12992. const currentXrEnabled = renderer.xr.enabled;
  12993. renderer.xr.enabled = false;
  12994. const generateMipmaps = renderTarget.texture.generateMipmaps;
  12995. renderTarget.texture.generateMipmaps = false;
  12996. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  12997. renderer.render( scene, cameraPX );
  12998. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  12999. renderer.render( scene, cameraNX );
  13000. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  13001. renderer.render( scene, cameraPY );
  13002. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  13003. renderer.render( scene, cameraNY );
  13004. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  13005. renderer.render( scene, cameraPZ );
  13006. // mipmaps are generated during the last call of render()
  13007. // at this point, all sides of the cube render target are defined
  13008. renderTarget.texture.generateMipmaps = generateMipmaps;
  13009. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  13010. renderer.render( scene, cameraNZ );
  13011. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  13012. renderer.xr.enabled = currentXrEnabled;
  13013. renderTarget.texture.needsPMREMUpdate = true;
  13014. }
  13015. }
  13016. class CubeTexture extends Texture {
  13017. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  13018. images = images !== undefined ? images : [];
  13019. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13020. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  13021. this.isCubeTexture = true;
  13022. this.flipY = false;
  13023. }
  13024. get images() {
  13025. return this.image;
  13026. }
  13027. set images( value ) {
  13028. this.image = value;
  13029. }
  13030. }
  13031. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  13032. constructor( size = 1, options = {} ) {
  13033. super( size, size, options );
  13034. this.isWebGLCubeRenderTarget = true;
  13035. const image = { width: size, height: size, depth: 1 };
  13036. const images = [ image, image, image, image, image, image ];
  13037. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  13038. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  13039. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  13040. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  13041. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  13042. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  13043. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  13044. this.texture.isRenderTargetTexture = true;
  13045. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  13046. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  13047. }
  13048. fromEquirectangularTexture( renderer, texture ) {
  13049. this.texture.type = texture.type;
  13050. this.texture.colorSpace = texture.colorSpace;
  13051. this.texture.generateMipmaps = texture.generateMipmaps;
  13052. this.texture.minFilter = texture.minFilter;
  13053. this.texture.magFilter = texture.magFilter;
  13054. const shader = {
  13055. uniforms: {
  13056. tEquirect: { value: null },
  13057. },
  13058. vertexShader: /* glsl */`
  13059. varying vec3 vWorldDirection;
  13060. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  13061. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  13062. }
  13063. void main() {
  13064. vWorldDirection = transformDirection( position, modelMatrix );
  13065. #include <begin_vertex>
  13066. #include <project_vertex>
  13067. }
  13068. `,
  13069. fragmentShader: /* glsl */`
  13070. uniform sampler2D tEquirect;
  13071. varying vec3 vWorldDirection;
  13072. #include <common>
  13073. void main() {
  13074. vec3 direction = normalize( vWorldDirection );
  13075. vec2 sampleUV = equirectUv( direction );
  13076. gl_FragColor = texture2D( tEquirect, sampleUV );
  13077. }
  13078. `
  13079. };
  13080. const geometry = new BoxGeometry( 5, 5, 5 );
  13081. const material = new ShaderMaterial( {
  13082. name: 'CubemapFromEquirect',
  13083. uniforms: cloneUniforms( shader.uniforms ),
  13084. vertexShader: shader.vertexShader,
  13085. fragmentShader: shader.fragmentShader,
  13086. side: BackSide,
  13087. blending: NoBlending
  13088. } );
  13089. material.uniforms.tEquirect.value = texture;
  13090. const mesh = new Mesh( geometry, material );
  13091. const currentMinFilter = texture.minFilter;
  13092. // Avoid blurred poles
  13093. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  13094. const camera = new CubeCamera( 1, 10, this );
  13095. camera.update( renderer, mesh );
  13096. texture.minFilter = currentMinFilter;
  13097. mesh.geometry.dispose();
  13098. mesh.material.dispose();
  13099. return this;
  13100. }
  13101. clear( renderer, color, depth, stencil ) {
  13102. const currentRenderTarget = renderer.getRenderTarget();
  13103. for ( let i = 0; i < 6; i ++ ) {
  13104. renderer.setRenderTarget( this, i );
  13105. renderer.clear( color, depth, stencil );
  13106. }
  13107. renderer.setRenderTarget( currentRenderTarget );
  13108. }
  13109. }
  13110. class Group extends Object3D {
  13111. constructor() {
  13112. super();
  13113. this.isGroup = true;
  13114. this.type = 'Group';
  13115. }
  13116. }
  13117. const _moveEvent = { type: 'move' };
  13118. class WebXRController {
  13119. constructor() {
  13120. this._targetRay = null;
  13121. this._grip = null;
  13122. this._hand = null;
  13123. }
  13124. getHandSpace() {
  13125. if ( this._hand === null ) {
  13126. this._hand = new Group();
  13127. this._hand.matrixAutoUpdate = false;
  13128. this._hand.visible = false;
  13129. this._hand.joints = {};
  13130. this._hand.inputState = { pinching: false };
  13131. }
  13132. return this._hand;
  13133. }
  13134. getTargetRaySpace() {
  13135. if ( this._targetRay === null ) {
  13136. this._targetRay = new Group();
  13137. this._targetRay.matrixAutoUpdate = false;
  13138. this._targetRay.visible = false;
  13139. this._targetRay.hasLinearVelocity = false;
  13140. this._targetRay.linearVelocity = new Vector3();
  13141. this._targetRay.hasAngularVelocity = false;
  13142. this._targetRay.angularVelocity = new Vector3();
  13143. }
  13144. return this._targetRay;
  13145. }
  13146. getGripSpace() {
  13147. if ( this._grip === null ) {
  13148. this._grip = new Group();
  13149. this._grip.matrixAutoUpdate = false;
  13150. this._grip.visible = false;
  13151. this._grip.hasLinearVelocity = false;
  13152. this._grip.linearVelocity = new Vector3();
  13153. this._grip.hasAngularVelocity = false;
  13154. this._grip.angularVelocity = new Vector3();
  13155. }
  13156. return this._grip;
  13157. }
  13158. dispatchEvent( event ) {
  13159. if ( this._targetRay !== null ) {
  13160. this._targetRay.dispatchEvent( event );
  13161. }
  13162. if ( this._grip !== null ) {
  13163. this._grip.dispatchEvent( event );
  13164. }
  13165. if ( this._hand !== null ) {
  13166. this._hand.dispatchEvent( event );
  13167. }
  13168. return this;
  13169. }
  13170. connect( inputSource ) {
  13171. if ( inputSource && inputSource.hand ) {
  13172. const hand = this._hand;
  13173. if ( hand ) {
  13174. for ( const inputjoint of inputSource.hand.values() ) {
  13175. // Initialize hand with joints when connected
  13176. this._getHandJoint( hand, inputjoint );
  13177. }
  13178. }
  13179. }
  13180. this.dispatchEvent( { type: 'connected', data: inputSource } );
  13181. return this;
  13182. }
  13183. disconnect( inputSource ) {
  13184. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13185. if ( this._targetRay !== null ) {
  13186. this._targetRay.visible = false;
  13187. }
  13188. if ( this._grip !== null ) {
  13189. this._grip.visible = false;
  13190. }
  13191. if ( this._hand !== null ) {
  13192. this._hand.visible = false;
  13193. }
  13194. return this;
  13195. }
  13196. update( inputSource, frame, referenceSpace ) {
  13197. let inputPose = null;
  13198. let gripPose = null;
  13199. let handPose = null;
  13200. const targetRay = this._targetRay;
  13201. const grip = this._grip;
  13202. const hand = this._hand;
  13203. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13204. if ( hand && inputSource.hand ) {
  13205. handPose = true;
  13206. for ( const inputjoint of inputSource.hand.values() ) {
  13207. // Update the joints groups with the XRJoint poses
  13208. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13209. // The transform of this joint will be updated with the joint pose on each frame
  13210. const joint = this._getHandJoint( hand, inputjoint );
  13211. if ( jointPose !== null ) {
  13212. joint.matrix.fromArray( jointPose.transform.matrix );
  13213. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13214. joint.matrixWorldNeedsUpdate = true;
  13215. joint.jointRadius = jointPose.radius;
  13216. }
  13217. joint.visible = jointPose !== null;
  13218. }
  13219. // Custom events
  13220. // Check pinchz
  13221. const indexTip = hand.joints[ 'index-finger-tip' ];
  13222. const thumbTip = hand.joints[ 'thumb-tip' ];
  13223. const distance = indexTip.position.distanceTo( thumbTip.position );
  13224. const distanceToPinch = 0.02;
  13225. const threshold = 0.005;
  13226. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13227. hand.inputState.pinching = false;
  13228. this.dispatchEvent( {
  13229. type: 'pinchend',
  13230. handedness: inputSource.handedness,
  13231. target: this
  13232. } );
  13233. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13234. hand.inputState.pinching = true;
  13235. this.dispatchEvent( {
  13236. type: 'pinchstart',
  13237. handedness: inputSource.handedness,
  13238. target: this
  13239. } );
  13240. }
  13241. } else {
  13242. if ( grip !== null && inputSource.gripSpace ) {
  13243. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13244. if ( gripPose !== null ) {
  13245. grip.matrix.fromArray( gripPose.transform.matrix );
  13246. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13247. grip.matrixWorldNeedsUpdate = true;
  13248. if ( gripPose.linearVelocity ) {
  13249. grip.hasLinearVelocity = true;
  13250. grip.linearVelocity.copy( gripPose.linearVelocity );
  13251. } else {
  13252. grip.hasLinearVelocity = false;
  13253. }
  13254. if ( gripPose.angularVelocity ) {
  13255. grip.hasAngularVelocity = true;
  13256. grip.angularVelocity.copy( gripPose.angularVelocity );
  13257. } else {
  13258. grip.hasAngularVelocity = false;
  13259. }
  13260. }
  13261. }
  13262. }
  13263. if ( targetRay !== null ) {
  13264. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13265. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  13266. if ( inputPose === null && gripPose !== null ) {
  13267. inputPose = gripPose;
  13268. }
  13269. if ( inputPose !== null ) {
  13270. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13271. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13272. targetRay.matrixWorldNeedsUpdate = true;
  13273. if ( inputPose.linearVelocity ) {
  13274. targetRay.hasLinearVelocity = true;
  13275. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13276. } else {
  13277. targetRay.hasLinearVelocity = false;
  13278. }
  13279. if ( inputPose.angularVelocity ) {
  13280. targetRay.hasAngularVelocity = true;
  13281. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13282. } else {
  13283. targetRay.hasAngularVelocity = false;
  13284. }
  13285. this.dispatchEvent( _moveEvent );
  13286. }
  13287. }
  13288. }
  13289. if ( targetRay !== null ) {
  13290. targetRay.visible = ( inputPose !== null );
  13291. }
  13292. if ( grip !== null ) {
  13293. grip.visible = ( gripPose !== null );
  13294. }
  13295. if ( hand !== null ) {
  13296. hand.visible = ( handPose !== null );
  13297. }
  13298. return this;
  13299. }
  13300. // private method
  13301. _getHandJoint( hand, inputjoint ) {
  13302. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13303. const joint = new Group();
  13304. joint.matrixAutoUpdate = false;
  13305. joint.visible = false;
  13306. hand.joints[ inputjoint.jointName ] = joint;
  13307. hand.add( joint );
  13308. }
  13309. return hand.joints[ inputjoint.jointName ];
  13310. }
  13311. }
  13312. /**
  13313. * This class can be used to define an exponential squared fog,
  13314. * which gives a clear view near the camera and a faster than exponentially
  13315. * densening fog farther from the camera.
  13316. *
  13317. * ```js
  13318. * const scene = new THREE.Scene();
  13319. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  13320. * ```
  13321. */
  13322. class FogExp2 {
  13323. /**
  13324. * Constructs a new fog.
  13325. *
  13326. * @param {number|Color} color - The fog's color.
  13327. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  13328. */
  13329. constructor( color, density = 0.00025 ) {
  13330. /**
  13331. * This flag can be used for type testing.
  13332. *
  13333. * @type {boolean}
  13334. * @readonly
  13335. * @default true
  13336. */
  13337. this.isFogExp2 = true;
  13338. /**
  13339. * The name of the fog.
  13340. *
  13341. * @type {string}
  13342. */
  13343. this.name = '';
  13344. /**
  13345. * The fog's color.
  13346. *
  13347. * @type {Color}
  13348. */
  13349. this.color = new Color( color );
  13350. /**
  13351. * Defines how fast the fog will grow dense.
  13352. *
  13353. * @type {number}
  13354. * @default 0.00025
  13355. */
  13356. this.density = density;
  13357. }
  13358. /**
  13359. * Returns a new fog with copied values from this instance.
  13360. *
  13361. * @return {FogExp2} A clone of this instance.
  13362. */
  13363. clone() {
  13364. return new FogExp2( this.color, this.density );
  13365. }
  13366. /**
  13367. * Serializes the fog into JSON.
  13368. *
  13369. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13370. * @return {Object} A JSON object representing the serialized fog
  13371. */
  13372. toJSON( /* meta */ ) {
  13373. return {
  13374. type: 'FogExp2',
  13375. name: this.name,
  13376. color: this.color.getHex(),
  13377. density: this.density
  13378. };
  13379. }
  13380. }
  13381. /**
  13382. * This class can be used to define a linear fog that grows linearly denser
  13383. * with the distance.
  13384. *
  13385. * ```js
  13386. * const scene = new THREE.Scene();
  13387. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  13388. * ```
  13389. */
  13390. class Fog {
  13391. /**
  13392. * Constructs a new fog.
  13393. *
  13394. * @param {number|Color} color - The fog's color.
  13395. * @param {number} [near=1] - The minimum distance to start applying fog.
  13396. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  13397. */
  13398. constructor( color, near = 1, far = 1000 ) {
  13399. /**
  13400. * This flag can be used for type testing.
  13401. *
  13402. * @type {boolean}
  13403. * @readonly
  13404. * @default true
  13405. */
  13406. this.isFog = true;
  13407. /**
  13408. * The name of the fog.
  13409. *
  13410. * @type {string}
  13411. */
  13412. this.name = '';
  13413. /**
  13414. * The fog's color.
  13415. *
  13416. * @type {Color}
  13417. */
  13418. this.color = new Color( color );
  13419. /**
  13420. * The minimum distance to start applying fog. Objects that are less than
  13421. * `near` units from the active camera won't be affected by fog.
  13422. *
  13423. * @type {number}
  13424. * @default 1
  13425. */
  13426. this.near = near;
  13427. /**
  13428. * The maximum distance at which fog stops being calculated and applied.
  13429. * Objects that are more than `far` units away from the active camera won't
  13430. * be affected by fog.
  13431. *
  13432. * @type {number}
  13433. * @default 1000
  13434. */
  13435. this.far = far;
  13436. }
  13437. /**
  13438. * Returns a new fog with copied values from this instance.
  13439. *
  13440. * @return {Fog} A clone of this instance.
  13441. */
  13442. clone() {
  13443. return new Fog( this.color, this.near, this.far );
  13444. }
  13445. /**
  13446. * Serializes the fog into JSON.
  13447. *
  13448. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13449. * @return {Object} A JSON object representing the serialized fog
  13450. */
  13451. toJSON( /* meta */ ) {
  13452. return {
  13453. type: 'Fog',
  13454. name: this.name,
  13455. color: this.color.getHex(),
  13456. near: this.near,
  13457. far: this.far
  13458. };
  13459. }
  13460. }
  13461. /**
  13462. * Scenes allow you to set up what is to be rendered and where by three.js.
  13463. * This is where you place 3D objects like meshes, lines or lights.
  13464. *
  13465. * @augments Object3D
  13466. */
  13467. class Scene extends Object3D {
  13468. /**
  13469. * Constructs a new scene.
  13470. */
  13471. constructor() {
  13472. super();
  13473. /**
  13474. * This flag can be used for type testing.
  13475. *
  13476. * @type {boolean}
  13477. * @readonly
  13478. * @default true
  13479. */
  13480. this.isScene = true;
  13481. this.type = 'Scene';
  13482. /**
  13483. * Defines the background of the scene. Valid inputs are:
  13484. *
  13485. * - A color for defining a uniform colored background.
  13486. * - A texture for defining a (flat) textured background.
  13487. * - Cube textures or equirectangular textures for defining a skybox.
  13488. *
  13489. * @type {?(Color|Texture)}
  13490. * @default null
  13491. */
  13492. this.background = null;
  13493. /**
  13494. * Sets the environment map for all physical materials in the scene. However,
  13495. * it's not possible to overwrite an existing texture assigned to the `envMap`
  13496. * material property.
  13497. *
  13498. * @type {?Texture}
  13499. * @default null
  13500. */
  13501. this.environment = null;
  13502. /**
  13503. * A fog instance defining the type of fog that affects everything
  13504. * rendered in the scene.
  13505. *
  13506. * @type {?(Fog|FogExp2)}
  13507. * @default null
  13508. */
  13509. this.fog = null;
  13510. /**
  13511. * Sets the blurriness of the background. Only influences environment maps
  13512. * assigned to {@link Scene#background}. Valid input is a float between `0`
  13513. * and `1`.
  13514. *
  13515. * @type {number}
  13516. * @default 0
  13517. */
  13518. this.backgroundBlurriness = 0;
  13519. /**
  13520. * Attenuates the color of the background. Only applies to background textures.
  13521. *
  13522. * @type {number}
  13523. * @default 1
  13524. */
  13525. this.backgroundIntensity = 1;
  13526. /**
  13527. * The rotation of the background in radians. Only influences environment maps
  13528. * assigned to {@link Scene#background}.
  13529. *
  13530. * @type {Euler}
  13531. * @default (0,0,0)
  13532. */
  13533. this.backgroundRotation = new Euler();
  13534. /**
  13535. * Attenuates the color of the environment. Only influences environment maps
  13536. * assigned to {@link Scene#environment}.
  13537. *
  13538. * @type {number}
  13539. * @default 1
  13540. */
  13541. this.environmentIntensity = 1;
  13542. /**
  13543. * The rotation of the environment map in radians. Only influences physical materials
  13544. * in the scene when {@link Scene#environment} is used.
  13545. *
  13546. * @type {Euler}
  13547. * @default (0,0,0)
  13548. */
  13549. this.environmentRotation = new Euler();
  13550. /**
  13551. * Forces everything in the scene to be rendered with the defined material.
  13552. *
  13553. * @type {?Material}
  13554. * @default null
  13555. */
  13556. this.overrideMaterial = null;
  13557. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  13558. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  13559. }
  13560. }
  13561. copy( source, recursive ) {
  13562. super.copy( source, recursive );
  13563. if ( source.background !== null ) this.background = source.background.clone();
  13564. if ( source.environment !== null ) this.environment = source.environment.clone();
  13565. if ( source.fog !== null ) this.fog = source.fog.clone();
  13566. this.backgroundBlurriness = source.backgroundBlurriness;
  13567. this.backgroundIntensity = source.backgroundIntensity;
  13568. this.backgroundRotation.copy( source.backgroundRotation );
  13569. this.environmentIntensity = source.environmentIntensity;
  13570. this.environmentRotation.copy( source.environmentRotation );
  13571. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13572. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13573. return this;
  13574. }
  13575. toJSON( meta ) {
  13576. const data = super.toJSON( meta );
  13577. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13578. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  13579. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  13580. data.object.backgroundRotation = this.backgroundRotation.toArray();
  13581. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  13582. data.object.environmentRotation = this.environmentRotation.toArray();
  13583. return data;
  13584. }
  13585. }
  13586. class InterleavedBuffer {
  13587. constructor( array, stride ) {
  13588. this.isInterleavedBuffer = true;
  13589. this.array = array;
  13590. this.stride = stride;
  13591. this.count = array !== undefined ? array.length / stride : 0;
  13592. this.usage = StaticDrawUsage;
  13593. this.updateRanges = [];
  13594. this.version = 0;
  13595. this.uuid = generateUUID();
  13596. }
  13597. onUploadCallback() {}
  13598. set needsUpdate( value ) {
  13599. if ( value === true ) this.version ++;
  13600. }
  13601. setUsage( value ) {
  13602. this.usage = value;
  13603. return this;
  13604. }
  13605. addUpdateRange( start, count ) {
  13606. this.updateRanges.push( { start, count } );
  13607. }
  13608. clearUpdateRanges() {
  13609. this.updateRanges.length = 0;
  13610. }
  13611. copy( source ) {
  13612. this.array = new source.array.constructor( source.array );
  13613. this.count = source.count;
  13614. this.stride = source.stride;
  13615. this.usage = source.usage;
  13616. return this;
  13617. }
  13618. copyAt( index1, attribute, index2 ) {
  13619. index1 *= this.stride;
  13620. index2 *= attribute.stride;
  13621. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  13622. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13623. }
  13624. return this;
  13625. }
  13626. set( value, offset = 0 ) {
  13627. this.array.set( value, offset );
  13628. return this;
  13629. }
  13630. clone( data ) {
  13631. if ( data.arrayBuffers === undefined ) {
  13632. data.arrayBuffers = {};
  13633. }
  13634. if ( this.array.buffer._uuid === undefined ) {
  13635. this.array.buffer._uuid = generateUUID();
  13636. }
  13637. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13638. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  13639. }
  13640. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  13641. const ib = new this.constructor( array, this.stride );
  13642. ib.setUsage( this.usage );
  13643. return ib;
  13644. }
  13645. onUpload( callback ) {
  13646. this.onUploadCallback = callback;
  13647. return this;
  13648. }
  13649. toJSON( data ) {
  13650. if ( data.arrayBuffers === undefined ) {
  13651. data.arrayBuffers = {};
  13652. }
  13653. // generate UUID for array buffer if necessary
  13654. if ( this.array.buffer._uuid === undefined ) {
  13655. this.array.buffer._uuid = generateUUID();
  13656. }
  13657. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13658. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  13659. }
  13660. //
  13661. return {
  13662. uuid: this.uuid,
  13663. buffer: this.array.buffer._uuid,
  13664. type: this.array.constructor.name,
  13665. stride: this.stride
  13666. };
  13667. }
  13668. }
  13669. const _vector$7 = /*@__PURE__*/ new Vector3();
  13670. class InterleavedBufferAttribute {
  13671. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  13672. this.isInterleavedBufferAttribute = true;
  13673. this.name = '';
  13674. this.data = interleavedBuffer;
  13675. this.itemSize = itemSize;
  13676. this.offset = offset;
  13677. this.normalized = normalized;
  13678. }
  13679. get count() {
  13680. return this.data.count;
  13681. }
  13682. get array() {
  13683. return this.data.array;
  13684. }
  13685. set needsUpdate( value ) {
  13686. this.data.needsUpdate = value;
  13687. }
  13688. applyMatrix4( m ) {
  13689. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  13690. _vector$7.fromBufferAttribute( this, i );
  13691. _vector$7.applyMatrix4( m );
  13692. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13693. }
  13694. return this;
  13695. }
  13696. applyNormalMatrix( m ) {
  13697. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13698. _vector$7.fromBufferAttribute( this, i );
  13699. _vector$7.applyNormalMatrix( m );
  13700. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13701. }
  13702. return this;
  13703. }
  13704. transformDirection( m ) {
  13705. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13706. _vector$7.fromBufferAttribute( this, i );
  13707. _vector$7.transformDirection( m );
  13708. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13709. }
  13710. return this;
  13711. }
  13712. getComponent( index, component ) {
  13713. let value = this.array[ index * this.data.stride + this.offset + component ];
  13714. if ( this.normalized ) value = denormalize( value, this.array );
  13715. return value;
  13716. }
  13717. setComponent( index, component, value ) {
  13718. if ( this.normalized ) value = normalize( value, this.array );
  13719. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  13720. return this;
  13721. }
  13722. setX( index, x ) {
  13723. if ( this.normalized ) x = normalize( x, this.array );
  13724. this.data.array[ index * this.data.stride + this.offset ] = x;
  13725. return this;
  13726. }
  13727. setY( index, y ) {
  13728. if ( this.normalized ) y = normalize( y, this.array );
  13729. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  13730. return this;
  13731. }
  13732. setZ( index, z ) {
  13733. if ( this.normalized ) z = normalize( z, this.array );
  13734. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  13735. return this;
  13736. }
  13737. setW( index, w ) {
  13738. if ( this.normalized ) w = normalize( w, this.array );
  13739. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  13740. return this;
  13741. }
  13742. getX( index ) {
  13743. let x = this.data.array[ index * this.data.stride + this.offset ];
  13744. if ( this.normalized ) x = denormalize( x, this.array );
  13745. return x;
  13746. }
  13747. getY( index ) {
  13748. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  13749. if ( this.normalized ) y = denormalize( y, this.array );
  13750. return y;
  13751. }
  13752. getZ( index ) {
  13753. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  13754. if ( this.normalized ) z = denormalize( z, this.array );
  13755. return z;
  13756. }
  13757. getW( index ) {
  13758. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  13759. if ( this.normalized ) w = denormalize( w, this.array );
  13760. return w;
  13761. }
  13762. setXY( index, x, y ) {
  13763. index = index * this.data.stride + this.offset;
  13764. if ( this.normalized ) {
  13765. x = normalize( x, this.array );
  13766. y = normalize( y, this.array );
  13767. }
  13768. this.data.array[ index + 0 ] = x;
  13769. this.data.array[ index + 1 ] = y;
  13770. return this;
  13771. }
  13772. setXYZ( index, x, y, z ) {
  13773. index = index * this.data.stride + this.offset;
  13774. if ( this.normalized ) {
  13775. x = normalize( x, this.array );
  13776. y = normalize( y, this.array );
  13777. z = normalize( z, this.array );
  13778. }
  13779. this.data.array[ index + 0 ] = x;
  13780. this.data.array[ index + 1 ] = y;
  13781. this.data.array[ index + 2 ] = z;
  13782. return this;
  13783. }
  13784. setXYZW( index, x, y, z, w ) {
  13785. index = index * this.data.stride + this.offset;
  13786. if ( this.normalized ) {
  13787. x = normalize( x, this.array );
  13788. y = normalize( y, this.array );
  13789. z = normalize( z, this.array );
  13790. w = normalize( w, this.array );
  13791. }
  13792. this.data.array[ index + 0 ] = x;
  13793. this.data.array[ index + 1 ] = y;
  13794. this.data.array[ index + 2 ] = z;
  13795. this.data.array[ index + 3 ] = w;
  13796. return this;
  13797. }
  13798. clone( data ) {
  13799. if ( data === undefined ) {
  13800. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  13801. const array = [];
  13802. for ( let i = 0; i < this.count; i ++ ) {
  13803. const index = i * this.data.stride + this.offset;
  13804. for ( let j = 0; j < this.itemSize; j ++ ) {
  13805. array.push( this.data.array[ index + j ] );
  13806. }
  13807. }
  13808. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  13809. } else {
  13810. if ( data.interleavedBuffers === undefined ) {
  13811. data.interleavedBuffers = {};
  13812. }
  13813. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13814. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  13815. }
  13816. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  13817. }
  13818. }
  13819. toJSON( data ) {
  13820. if ( data === undefined ) {
  13821. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  13822. const array = [];
  13823. for ( let i = 0; i < this.count; i ++ ) {
  13824. const index = i * this.data.stride + this.offset;
  13825. for ( let j = 0; j < this.itemSize; j ++ ) {
  13826. array.push( this.data.array[ index + j ] );
  13827. }
  13828. }
  13829. // de-interleave data and save it as an ordinary buffer attribute for now
  13830. return {
  13831. itemSize: this.itemSize,
  13832. type: this.array.constructor.name,
  13833. array: array,
  13834. normalized: this.normalized
  13835. };
  13836. } else {
  13837. // save as true interleaved attribute
  13838. if ( data.interleavedBuffers === undefined ) {
  13839. data.interleavedBuffers = {};
  13840. }
  13841. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13842. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  13843. }
  13844. return {
  13845. isInterleavedBufferAttribute: true,
  13846. itemSize: this.itemSize,
  13847. data: this.data.uuid,
  13848. offset: this.offset,
  13849. normalized: this.normalized
  13850. };
  13851. }
  13852. }
  13853. }
  13854. class SpriteMaterial extends Material {
  13855. constructor( parameters ) {
  13856. super();
  13857. this.isSpriteMaterial = true;
  13858. this.type = 'SpriteMaterial';
  13859. this.color = new Color( 0xffffff );
  13860. this.map = null;
  13861. this.alphaMap = null;
  13862. this.rotation = 0;
  13863. this.sizeAttenuation = true;
  13864. this.transparent = true;
  13865. this.fog = true;
  13866. this.setValues( parameters );
  13867. }
  13868. copy( source ) {
  13869. super.copy( source );
  13870. this.color.copy( source.color );
  13871. this.map = source.map;
  13872. this.alphaMap = source.alphaMap;
  13873. this.rotation = source.rotation;
  13874. this.sizeAttenuation = source.sizeAttenuation;
  13875. this.fog = source.fog;
  13876. return this;
  13877. }
  13878. }
  13879. let _geometry;
  13880. const _intersectPoint = /*@__PURE__*/ new Vector3();
  13881. const _worldScale = /*@__PURE__*/ new Vector3();
  13882. const _mvPosition = /*@__PURE__*/ new Vector3();
  13883. const _alignedPosition = /*@__PURE__*/ new Vector2();
  13884. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  13885. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  13886. const _vA = /*@__PURE__*/ new Vector3();
  13887. const _vB = /*@__PURE__*/ new Vector3();
  13888. const _vC = /*@__PURE__*/ new Vector3();
  13889. const _uvA = /*@__PURE__*/ new Vector2();
  13890. const _uvB = /*@__PURE__*/ new Vector2();
  13891. const _uvC = /*@__PURE__*/ new Vector2();
  13892. class Sprite extends Object3D {
  13893. constructor( material = new SpriteMaterial() ) {
  13894. super();
  13895. this.isSprite = true;
  13896. this.type = 'Sprite';
  13897. if ( _geometry === undefined ) {
  13898. _geometry = new BufferGeometry();
  13899. const float32Array = new Float32Array( [
  13900. -0.5, -0.5, 0, 0, 0,
  13901. 0.5, -0.5, 0, 1, 0,
  13902. 0.5, 0.5, 0, 1, 1,
  13903. -0.5, 0.5, 0, 0, 1
  13904. ] );
  13905. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  13906. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  13907. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  13908. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  13909. }
  13910. this.geometry = _geometry;
  13911. this.material = material;
  13912. this.center = new Vector2( 0.5, 0.5 );
  13913. }
  13914. raycast( raycaster, intersects ) {
  13915. if ( raycaster.camera === null ) {
  13916. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  13917. }
  13918. _worldScale.setFromMatrixScale( this.matrixWorld );
  13919. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  13920. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  13921. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  13922. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  13923. _worldScale.multiplyScalar( - _mvPosition.z );
  13924. }
  13925. const rotation = this.material.rotation;
  13926. let sin, cos;
  13927. if ( rotation !== 0 ) {
  13928. cos = Math.cos( rotation );
  13929. sin = Math.sin( rotation );
  13930. }
  13931. const center = this.center;
  13932. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13933. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13934. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13935. _uvA.set( 0, 0 );
  13936. _uvB.set( 1, 0 );
  13937. _uvC.set( 1, 1 );
  13938. // check first triangle
  13939. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  13940. if ( intersect === null ) {
  13941. // check second triangle
  13942. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13943. _uvB.set( 0, 1 );
  13944. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  13945. if ( intersect === null ) {
  13946. return;
  13947. }
  13948. }
  13949. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  13950. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13951. intersects.push( {
  13952. distance: distance,
  13953. point: _intersectPoint.clone(),
  13954. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  13955. face: null,
  13956. object: this
  13957. } );
  13958. }
  13959. copy( source, recursive ) {
  13960. super.copy( source, recursive );
  13961. if ( source.center !== undefined ) this.center.copy( source.center );
  13962. this.material = source.material;
  13963. return this;
  13964. }
  13965. }
  13966. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  13967. // compute position in camera space
  13968. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  13969. // to check if rotation is not zero
  13970. if ( sin !== undefined ) {
  13971. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  13972. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  13973. } else {
  13974. _rotatedPosition.copy( _alignedPosition );
  13975. }
  13976. vertexPosition.copy( mvPosition );
  13977. vertexPosition.x += _rotatedPosition.x;
  13978. vertexPosition.y += _rotatedPosition.y;
  13979. // transform to world space
  13980. vertexPosition.applyMatrix4( _viewWorldMatrix );
  13981. }
  13982. const _v1$2 = /*@__PURE__*/ new Vector3();
  13983. const _v2$1 = /*@__PURE__*/ new Vector3();
  13984. class LOD extends Object3D {
  13985. constructor() {
  13986. super();
  13987. this._currentLevel = 0;
  13988. this.type = 'LOD';
  13989. Object.defineProperties( this, {
  13990. levels: {
  13991. enumerable: true,
  13992. value: []
  13993. },
  13994. isLOD: {
  13995. value: true,
  13996. }
  13997. } );
  13998. this.autoUpdate = true;
  13999. }
  14000. copy( source ) {
  14001. super.copy( source, false );
  14002. const levels = source.levels;
  14003. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14004. const level = levels[ i ];
  14005. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  14006. }
  14007. this.autoUpdate = source.autoUpdate;
  14008. return this;
  14009. }
  14010. addLevel( object, distance = 0, hysteresis = 0 ) {
  14011. distance = Math.abs( distance );
  14012. const levels = this.levels;
  14013. let l;
  14014. for ( l = 0; l < levels.length; l ++ ) {
  14015. if ( distance < levels[ l ].distance ) {
  14016. break;
  14017. }
  14018. }
  14019. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  14020. this.add( object );
  14021. return this;
  14022. }
  14023. removeLevel( distance ) {
  14024. const levels = this.levels;
  14025. for ( let i = 0; i < levels.length; i ++ ) {
  14026. if ( levels[ i ].distance === distance ) {
  14027. const removedElements = levels.splice( i, 1 );
  14028. this.remove( removedElements[ 0 ].object );
  14029. return true;
  14030. }
  14031. }
  14032. return false;
  14033. }
  14034. getCurrentLevel() {
  14035. return this._currentLevel;
  14036. }
  14037. getObjectForDistance( distance ) {
  14038. const levels = this.levels;
  14039. if ( levels.length > 0 ) {
  14040. let i, l;
  14041. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14042. let levelDistance = levels[ i ].distance;
  14043. if ( levels[ i ].object.visible ) {
  14044. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14045. }
  14046. if ( distance < levelDistance ) {
  14047. break;
  14048. }
  14049. }
  14050. return levels[ i - 1 ].object;
  14051. }
  14052. return null;
  14053. }
  14054. raycast( raycaster, intersects ) {
  14055. const levels = this.levels;
  14056. if ( levels.length > 0 ) {
  14057. _v1$2.setFromMatrixPosition( this.matrixWorld );
  14058. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  14059. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14060. }
  14061. }
  14062. update( camera ) {
  14063. const levels = this.levels;
  14064. if ( levels.length > 1 ) {
  14065. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  14066. _v2$1.setFromMatrixPosition( this.matrixWorld );
  14067. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  14068. levels[ 0 ].object.visible = true;
  14069. let i, l;
  14070. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14071. let levelDistance = levels[ i ].distance;
  14072. if ( levels[ i ].object.visible ) {
  14073. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14074. }
  14075. if ( distance >= levelDistance ) {
  14076. levels[ i - 1 ].object.visible = false;
  14077. levels[ i ].object.visible = true;
  14078. } else {
  14079. break;
  14080. }
  14081. }
  14082. this._currentLevel = i - 1;
  14083. for ( ; i < l; i ++ ) {
  14084. levels[ i ].object.visible = false;
  14085. }
  14086. }
  14087. }
  14088. toJSON( meta ) {
  14089. const data = super.toJSON( meta );
  14090. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  14091. data.object.levels = [];
  14092. const levels = this.levels;
  14093. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14094. const level = levels[ i ];
  14095. data.object.levels.push( {
  14096. object: level.object.uuid,
  14097. distance: level.distance,
  14098. hysteresis: level.hysteresis
  14099. } );
  14100. }
  14101. return data;
  14102. }
  14103. }
  14104. const _basePosition = /*@__PURE__*/ new Vector3();
  14105. const _skinIndex = /*@__PURE__*/ new Vector4();
  14106. const _skinWeight = /*@__PURE__*/ new Vector4();
  14107. const _vector3 = /*@__PURE__*/ new Vector3();
  14108. const _matrix4 = /*@__PURE__*/ new Matrix4();
  14109. const _vertex = /*@__PURE__*/ new Vector3();
  14110. const _sphere$5 = /*@__PURE__*/ new Sphere();
  14111. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  14112. const _ray$2 = /*@__PURE__*/ new Ray();
  14113. class SkinnedMesh extends Mesh {
  14114. constructor( geometry, material ) {
  14115. super( geometry, material );
  14116. this.isSkinnedMesh = true;
  14117. this.type = 'SkinnedMesh';
  14118. this.bindMode = AttachedBindMode;
  14119. this.bindMatrix = new Matrix4();
  14120. this.bindMatrixInverse = new Matrix4();
  14121. this.boundingBox = null;
  14122. this.boundingSphere = null;
  14123. }
  14124. computeBoundingBox() {
  14125. const geometry = this.geometry;
  14126. if ( this.boundingBox === null ) {
  14127. this.boundingBox = new Box3();
  14128. }
  14129. this.boundingBox.makeEmpty();
  14130. const positionAttribute = geometry.getAttribute( 'position' );
  14131. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14132. this.getVertexPosition( i, _vertex );
  14133. this.boundingBox.expandByPoint( _vertex );
  14134. }
  14135. }
  14136. computeBoundingSphere() {
  14137. const geometry = this.geometry;
  14138. if ( this.boundingSphere === null ) {
  14139. this.boundingSphere = new Sphere();
  14140. }
  14141. this.boundingSphere.makeEmpty();
  14142. const positionAttribute = geometry.getAttribute( 'position' );
  14143. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14144. this.getVertexPosition( i, _vertex );
  14145. this.boundingSphere.expandByPoint( _vertex );
  14146. }
  14147. }
  14148. copy( source, recursive ) {
  14149. super.copy( source, recursive );
  14150. this.bindMode = source.bindMode;
  14151. this.bindMatrix.copy( source.bindMatrix );
  14152. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  14153. this.skeleton = source.skeleton;
  14154. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  14155. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  14156. return this;
  14157. }
  14158. raycast( raycaster, intersects ) {
  14159. const material = this.material;
  14160. const matrixWorld = this.matrixWorld;
  14161. if ( material === undefined ) return;
  14162. // test with bounding sphere in world space
  14163. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  14164. _sphere$5.copy( this.boundingSphere );
  14165. _sphere$5.applyMatrix4( matrixWorld );
  14166. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  14167. // convert ray to local space of skinned mesh
  14168. _inverseMatrix$2.copy( matrixWorld ).invert();
  14169. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  14170. // test with bounding box in local space
  14171. if ( this.boundingBox !== null ) {
  14172. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  14173. }
  14174. // test for intersections with geometry
  14175. this._computeIntersections( raycaster, intersects, _ray$2 );
  14176. }
  14177. getVertexPosition( index, target ) {
  14178. super.getVertexPosition( index, target );
  14179. this.applyBoneTransform( index, target );
  14180. return target;
  14181. }
  14182. bind( skeleton, bindMatrix ) {
  14183. this.skeleton = skeleton;
  14184. if ( bindMatrix === undefined ) {
  14185. this.updateMatrixWorld( true );
  14186. this.skeleton.calculateInverses();
  14187. bindMatrix = this.matrixWorld;
  14188. }
  14189. this.bindMatrix.copy( bindMatrix );
  14190. this.bindMatrixInverse.copy( bindMatrix ).invert();
  14191. }
  14192. pose() {
  14193. this.skeleton.pose();
  14194. }
  14195. normalizeSkinWeights() {
  14196. const vector = new Vector4();
  14197. const skinWeight = this.geometry.attributes.skinWeight;
  14198. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  14199. vector.fromBufferAttribute( skinWeight, i );
  14200. const scale = 1.0 / vector.manhattanLength();
  14201. if ( scale !== Infinity ) {
  14202. vector.multiplyScalar( scale );
  14203. } else {
  14204. vector.set( 1, 0, 0, 0 ); // do something reasonable
  14205. }
  14206. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  14207. }
  14208. }
  14209. updateMatrixWorld( force ) {
  14210. super.updateMatrixWorld( force );
  14211. if ( this.bindMode === AttachedBindMode ) {
  14212. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  14213. } else if ( this.bindMode === DetachedBindMode ) {
  14214. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  14215. } else {
  14216. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14217. }
  14218. }
  14219. applyBoneTransform( index, vector ) {
  14220. const skeleton = this.skeleton;
  14221. const geometry = this.geometry;
  14222. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  14223. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  14224. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  14225. vector.set( 0, 0, 0 );
  14226. for ( let i = 0; i < 4; i ++ ) {
  14227. const weight = _skinWeight.getComponent( i );
  14228. if ( weight !== 0 ) {
  14229. const boneIndex = _skinIndex.getComponent( i );
  14230. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  14231. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  14232. }
  14233. }
  14234. return vector.applyMatrix4( this.bindMatrixInverse );
  14235. }
  14236. }
  14237. class Bone extends Object3D {
  14238. constructor() {
  14239. super();
  14240. this.isBone = true;
  14241. this.type = 'Bone';
  14242. }
  14243. }
  14244. class DataTexture extends Texture {
  14245. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  14246. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  14247. this.isDataTexture = true;
  14248. this.image = { data: data, width: width, height: height };
  14249. this.generateMipmaps = false;
  14250. this.flipY = false;
  14251. this.unpackAlignment = 1;
  14252. }
  14253. }
  14254. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  14255. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  14256. class Skeleton {
  14257. constructor( bones = [], boneInverses = [] ) {
  14258. this.uuid = generateUUID();
  14259. this.bones = bones.slice( 0 );
  14260. this.boneInverses = boneInverses;
  14261. this.boneMatrices = null;
  14262. this.boneTexture = null;
  14263. this.init();
  14264. }
  14265. init() {
  14266. const bones = this.bones;
  14267. const boneInverses = this.boneInverses;
  14268. this.boneMatrices = new Float32Array( bones.length * 16 );
  14269. // calculate inverse bone matrices if necessary
  14270. if ( boneInverses.length === 0 ) {
  14271. this.calculateInverses();
  14272. } else {
  14273. // handle special case
  14274. if ( bones.length !== boneInverses.length ) {
  14275. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  14276. this.boneInverses = [];
  14277. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14278. this.boneInverses.push( new Matrix4() );
  14279. }
  14280. }
  14281. }
  14282. }
  14283. calculateInverses() {
  14284. this.boneInverses.length = 0;
  14285. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14286. const inverse = new Matrix4();
  14287. if ( this.bones[ i ] ) {
  14288. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  14289. }
  14290. this.boneInverses.push( inverse );
  14291. }
  14292. }
  14293. pose() {
  14294. // recover the bind-time world matrices
  14295. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14296. const bone = this.bones[ i ];
  14297. if ( bone ) {
  14298. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  14299. }
  14300. }
  14301. // compute the local matrices, positions, rotations and scales
  14302. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14303. const bone = this.bones[ i ];
  14304. if ( bone ) {
  14305. if ( bone.parent && bone.parent.isBone ) {
  14306. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  14307. bone.matrix.multiply( bone.matrixWorld );
  14308. } else {
  14309. bone.matrix.copy( bone.matrixWorld );
  14310. }
  14311. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14312. }
  14313. }
  14314. }
  14315. update() {
  14316. const bones = this.bones;
  14317. const boneInverses = this.boneInverses;
  14318. const boneMatrices = this.boneMatrices;
  14319. const boneTexture = this.boneTexture;
  14320. // flatten bone matrices to array
  14321. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  14322. // compute the offset between the current and the original transform
  14323. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  14324. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14325. _offsetMatrix.toArray( boneMatrices, i * 16 );
  14326. }
  14327. if ( boneTexture !== null ) {
  14328. boneTexture.needsUpdate = true;
  14329. }
  14330. }
  14331. clone() {
  14332. return new Skeleton( this.bones, this.boneInverses );
  14333. }
  14334. computeBoneTexture() {
  14335. // layout (1 matrix = 4 pixels)
  14336. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14337. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14338. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14339. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14340. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14341. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  14342. size = Math.ceil( size / 4 ) * 4;
  14343. size = Math.max( size, 4 );
  14344. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14345. boneMatrices.set( this.boneMatrices ); // copy current values
  14346. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14347. boneTexture.needsUpdate = true;
  14348. this.boneMatrices = boneMatrices;
  14349. this.boneTexture = boneTexture;
  14350. return this;
  14351. }
  14352. getBoneByName( name ) {
  14353. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14354. const bone = this.bones[ i ];
  14355. if ( bone.name === name ) {
  14356. return bone;
  14357. }
  14358. }
  14359. return undefined;
  14360. }
  14361. dispose( ) {
  14362. if ( this.boneTexture !== null ) {
  14363. this.boneTexture.dispose();
  14364. this.boneTexture = null;
  14365. }
  14366. }
  14367. fromJSON( json, bones ) {
  14368. this.uuid = json.uuid;
  14369. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  14370. const uuid = json.bones[ i ];
  14371. let bone = bones[ uuid ];
  14372. if ( bone === undefined ) {
  14373. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  14374. bone = new Bone();
  14375. }
  14376. this.bones.push( bone );
  14377. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  14378. }
  14379. this.init();
  14380. return this;
  14381. }
  14382. toJSON() {
  14383. const data = {
  14384. metadata: {
  14385. version: 4.6,
  14386. type: 'Skeleton',
  14387. generator: 'Skeleton.toJSON'
  14388. },
  14389. bones: [],
  14390. boneInverses: []
  14391. };
  14392. data.uuid = this.uuid;
  14393. const bones = this.bones;
  14394. const boneInverses = this.boneInverses;
  14395. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  14396. const bone = bones[ i ];
  14397. data.bones.push( bone.uuid );
  14398. const boneInverse = boneInverses[ i ];
  14399. data.boneInverses.push( boneInverse.toArray() );
  14400. }
  14401. return data;
  14402. }
  14403. }
  14404. class InstancedBufferAttribute extends BufferAttribute {
  14405. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  14406. super( array, itemSize, normalized );
  14407. this.isInstancedBufferAttribute = true;
  14408. this.meshPerAttribute = meshPerAttribute;
  14409. }
  14410. copy( source ) {
  14411. super.copy( source );
  14412. this.meshPerAttribute = source.meshPerAttribute;
  14413. return this;
  14414. }
  14415. toJSON() {
  14416. const data = super.toJSON();
  14417. data.meshPerAttribute = this.meshPerAttribute;
  14418. data.isInstancedBufferAttribute = true;
  14419. return data;
  14420. }
  14421. }
  14422. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  14423. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  14424. const _instanceIntersects = [];
  14425. const _box3 = /*@__PURE__*/ new Box3();
  14426. const _identity = /*@__PURE__*/ new Matrix4();
  14427. const _mesh$1 = /*@__PURE__*/ new Mesh();
  14428. const _sphere$4 = /*@__PURE__*/ new Sphere();
  14429. class InstancedMesh extends Mesh {
  14430. constructor( geometry, material, count ) {
  14431. super( geometry, material );
  14432. this.isInstancedMesh = true;
  14433. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  14434. this.instanceColor = null;
  14435. this.morphTexture = null;
  14436. this.count = count;
  14437. this.boundingBox = null;
  14438. this.boundingSphere = null;
  14439. for ( let i = 0; i < count; i ++ ) {
  14440. this.setMatrixAt( i, _identity );
  14441. }
  14442. }
  14443. computeBoundingBox() {
  14444. const geometry = this.geometry;
  14445. const count = this.count;
  14446. if ( this.boundingBox === null ) {
  14447. this.boundingBox = new Box3();
  14448. }
  14449. if ( geometry.boundingBox === null ) {
  14450. geometry.computeBoundingBox();
  14451. }
  14452. this.boundingBox.makeEmpty();
  14453. for ( let i = 0; i < count; i ++ ) {
  14454. this.getMatrixAt( i, _instanceLocalMatrix );
  14455. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  14456. this.boundingBox.union( _box3 );
  14457. }
  14458. }
  14459. computeBoundingSphere() {
  14460. const geometry = this.geometry;
  14461. const count = this.count;
  14462. if ( this.boundingSphere === null ) {
  14463. this.boundingSphere = new Sphere();
  14464. }
  14465. if ( geometry.boundingSphere === null ) {
  14466. geometry.computeBoundingSphere();
  14467. }
  14468. this.boundingSphere.makeEmpty();
  14469. for ( let i = 0; i < count; i ++ ) {
  14470. this.getMatrixAt( i, _instanceLocalMatrix );
  14471. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  14472. this.boundingSphere.union( _sphere$4 );
  14473. }
  14474. }
  14475. copy( source, recursive ) {
  14476. super.copy( source, recursive );
  14477. this.instanceMatrix.copy( source.instanceMatrix );
  14478. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  14479. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  14480. this.count = source.count;
  14481. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  14482. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  14483. return this;
  14484. }
  14485. getColorAt( index, color ) {
  14486. color.fromArray( this.instanceColor.array, index * 3 );
  14487. }
  14488. getMatrixAt( index, matrix ) {
  14489. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  14490. }
  14491. getMorphAt( index, object ) {
  14492. const objectInfluences = object.morphTargetInfluences;
  14493. const array = this.morphTexture.source.data.data;
  14494. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  14495. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  14496. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  14497. objectInfluences[ i ] = array[ dataIndex + i ];
  14498. }
  14499. }
  14500. raycast( raycaster, intersects ) {
  14501. const matrixWorld = this.matrixWorld;
  14502. const raycastTimes = this.count;
  14503. _mesh$1.geometry = this.geometry;
  14504. _mesh$1.material = this.material;
  14505. if ( _mesh$1.material === undefined ) return;
  14506. // test with bounding sphere first
  14507. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  14508. _sphere$4.copy( this.boundingSphere );
  14509. _sphere$4.applyMatrix4( matrixWorld );
  14510. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  14511. // now test each instance
  14512. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  14513. // calculate the world matrix for each instance
  14514. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  14515. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  14516. // the mesh represents this single instance
  14517. _mesh$1.matrixWorld = _instanceWorldMatrix;
  14518. _mesh$1.raycast( raycaster, _instanceIntersects );
  14519. // process the result of raycast
  14520. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  14521. const intersect = _instanceIntersects[ i ];
  14522. intersect.instanceId = instanceId;
  14523. intersect.object = this;
  14524. intersects.push( intersect );
  14525. }
  14526. _instanceIntersects.length = 0;
  14527. }
  14528. }
  14529. setColorAt( index, color ) {
  14530. if ( this.instanceColor === null ) {
  14531. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  14532. }
  14533. color.toArray( this.instanceColor.array, index * 3 );
  14534. }
  14535. setMatrixAt( index, matrix ) {
  14536. matrix.toArray( this.instanceMatrix.array, index * 16 );
  14537. }
  14538. setMorphAt( index, object ) {
  14539. const objectInfluences = object.morphTargetInfluences;
  14540. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  14541. if ( this.morphTexture === null ) {
  14542. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  14543. }
  14544. const array = this.morphTexture.source.data.data;
  14545. let morphInfluencesSum = 0;
  14546. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  14547. morphInfluencesSum += objectInfluences[ i ];
  14548. }
  14549. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  14550. const dataIndex = len * index;
  14551. array[ dataIndex ] = morphBaseInfluence;
  14552. array.set( objectInfluences, dataIndex + 1 );
  14553. }
  14554. updateMorphTargets() {
  14555. }
  14556. dispose() {
  14557. this.dispatchEvent( { type: 'dispose' } );
  14558. if ( this.morphTexture !== null ) {
  14559. this.morphTexture.dispose();
  14560. this.morphTexture = null;
  14561. }
  14562. return this;
  14563. }
  14564. }
  14565. const _vector1 = /*@__PURE__*/ new Vector3();
  14566. const _vector2 = /*@__PURE__*/ new Vector3();
  14567. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  14568. /**
  14569. * A two dimensional surface that extends infinitely in 3D space, represented
  14570. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  14571. * by a unit length normal vector and a constant.
  14572. */
  14573. class Plane {
  14574. /**
  14575. * Constructs a new plane.
  14576. *
  14577. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  14578. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  14579. */
  14580. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  14581. /**
  14582. * This flag can be used for type testing.
  14583. *
  14584. * @type {boolean}
  14585. * @readonly
  14586. * @default true
  14587. */
  14588. this.isPlane = true;
  14589. /**
  14590. * A unit length vector defining the normal of the plane.
  14591. *
  14592. * @type {Vector3}
  14593. */
  14594. this.normal = normal;
  14595. /**
  14596. * The signed distance from the origin to the plane.
  14597. *
  14598. * @type {number}
  14599. * @default 0
  14600. */
  14601. this.constant = constant;
  14602. }
  14603. /**
  14604. * Sets the plane components by copying the given values.
  14605. *
  14606. * @param {Vector3} normal - The normal.
  14607. * @param {number} constant - The constant.
  14608. * @return {Plane} A reference to this plane.
  14609. */
  14610. set( normal, constant ) {
  14611. this.normal.copy( normal );
  14612. this.constant = constant;
  14613. return this;
  14614. }
  14615. /**
  14616. * Sets the plane components by defining `x`, `y`, `z` as the
  14617. * plane normal and `w` as the constant.
  14618. *
  14619. * @param {number} x - The value for the normal's x component.
  14620. * @param {number} y - The value for the normal's y component.
  14621. * @param {number} z - The value for the normal's z component.
  14622. * @param {number} w - The constant value.
  14623. * @return {Plane} A reference to this plane.
  14624. */
  14625. setComponents( x, y, z, w ) {
  14626. this.normal.set( x, y, z );
  14627. this.constant = w;
  14628. return this;
  14629. }
  14630. /**
  14631. * Sets the plane from the given normal and coplanar point (that is a point
  14632. * that lies onto the plane).
  14633. *
  14634. * @param {Vector3} normal - The normal.
  14635. * @param {Vector3} point - A coplanar point.
  14636. * @return {Plane} A reference to this plane.
  14637. */
  14638. setFromNormalAndCoplanarPoint( normal, point ) {
  14639. this.normal.copy( normal );
  14640. this.constant = - point.dot( this.normal );
  14641. return this;
  14642. }
  14643. /**
  14644. * Sets the plane from three coplanar points. The winding order is
  14645. * assumed to be counter-clockwise, and determines the direction of
  14646. * the plane normal.
  14647. *
  14648. * @param {Vector3} a - The first coplanar point.
  14649. * @param {Vector3} b - The second coplanar point.
  14650. * @param {Vector3} c - The third coplanar point.
  14651. * @return {Plane} A reference to this plane.
  14652. */
  14653. setFromCoplanarPoints( a, b, c ) {
  14654. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  14655. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  14656. this.setFromNormalAndCoplanarPoint( normal, a );
  14657. return this;
  14658. }
  14659. /**
  14660. * Copies the values of the given plane to this instance.
  14661. *
  14662. * @param {Plane} plane - The plane to copy.
  14663. * @return {Plane} A reference to this plane.
  14664. */
  14665. copy( plane ) {
  14666. this.normal.copy( plane.normal );
  14667. this.constant = plane.constant;
  14668. return this;
  14669. }
  14670. /**
  14671. * Normalizes the plane normal and adjusts the constant accordingly.
  14672. *
  14673. * @return {Plane} A reference to this plane.
  14674. */
  14675. normalize() {
  14676. // Note: will lead to a divide by zero if the plane is invalid.
  14677. const inverseNormalLength = 1.0 / this.normal.length();
  14678. this.normal.multiplyScalar( inverseNormalLength );
  14679. this.constant *= inverseNormalLength;
  14680. return this;
  14681. }
  14682. /**
  14683. * Negates both the plane normal and the constant.
  14684. *
  14685. * @return {Plane} A reference to this plane.
  14686. */
  14687. negate() {
  14688. this.constant *= -1;
  14689. this.normal.negate();
  14690. return this;
  14691. }
  14692. /**
  14693. * Returns the signed distance from the given point to this plane.
  14694. *
  14695. * @param {Vector3} point - The point to compute the distance for.
  14696. * @return {number} The signed distance.
  14697. */
  14698. distanceToPoint( point ) {
  14699. return this.normal.dot( point ) + this.constant;
  14700. }
  14701. /**
  14702. * Returns the signed distance from the given sphere to this plane.
  14703. *
  14704. * @param {Sphere} sphere - The sphere to compute the distance for.
  14705. * @return {number} The signed distance.
  14706. */
  14707. distanceToSphere( sphere ) {
  14708. return this.distanceToPoint( sphere.center ) - sphere.radius;
  14709. }
  14710. /**
  14711. * Projects a the given point onto the plane.
  14712. *
  14713. * @param {Vector3} point - The point to project.
  14714. * @param {Vector3} target - The target vector that is used to store the method's result.
  14715. * @return {Vector3} The projected point on the plane.
  14716. */
  14717. projectPoint( point, target ) {
  14718. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  14719. }
  14720. /**
  14721. * Returns the intersection point of the passed line and the plane. Returns
  14722. * `null` if the line does not intersect. Returns the line's starting point if
  14723. * the line is coplanar with the plane.
  14724. *
  14725. * @param {Line3} line - The line to compute the intersection for.
  14726. * @param {Vector3} target - The target vector that is used to store the method's result.
  14727. * @return {?Vector3} The intersection point.
  14728. */
  14729. intersectLine( line, target ) {
  14730. const direction = line.delta( _vector1 );
  14731. const denominator = this.normal.dot( direction );
  14732. if ( denominator === 0 ) {
  14733. // line is coplanar, return origin
  14734. if ( this.distanceToPoint( line.start ) === 0 ) {
  14735. return target.copy( line.start );
  14736. }
  14737. // Unsure if this is the correct method to handle this case.
  14738. return null;
  14739. }
  14740. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  14741. if ( t < 0 || t > 1 ) {
  14742. return null;
  14743. }
  14744. return target.copy( line.start ).addScaledVector( direction, t );
  14745. }
  14746. /**
  14747. * Returns `true` if the given line segment intersects with (passes through) the plane.
  14748. *
  14749. * @param {Line3} line - The line to test.
  14750. * @return {boolean} Whether the given line segment intersects with the plane or not.
  14751. */
  14752. intersectsLine( line ) {
  14753. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  14754. const startSign = this.distanceToPoint( line.start );
  14755. const endSign = this.distanceToPoint( line.end );
  14756. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  14757. }
  14758. /**
  14759. * Returns `true` if the given bounding box intersects with the plane.
  14760. *
  14761. * @param {Box3} box - The bounding box to test.
  14762. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  14763. */
  14764. intersectsBox( box ) {
  14765. return box.intersectsPlane( this );
  14766. }
  14767. /**
  14768. * Returns `true` if the given bounding sphere intersects with the plane.
  14769. *
  14770. * @param {Sphere} sphere - The bounding sphere to test.
  14771. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  14772. */
  14773. intersectsSphere( sphere ) {
  14774. return sphere.intersectsPlane( this );
  14775. }
  14776. /**
  14777. * Returns a coplanar vector to the plane, by calculating the
  14778. * projection of the normal at the origin onto the plane.
  14779. *
  14780. * @param {Vector3} target - The target vector that is used to store the method's result.
  14781. * @return {boolean} The coplanar point.
  14782. */
  14783. coplanarPoint( target ) {
  14784. return target.copy( this.normal ).multiplyScalar( - this.constant );
  14785. }
  14786. /**
  14787. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  14788. *
  14789. * The optional normal matrix can be pre-computed like so:
  14790. * ```js
  14791. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  14792. * ```
  14793. *
  14794. * @param {Matrix4} matrix - The transformation matrix.
  14795. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  14796. * @return {Plane} A reference to this plane.
  14797. */
  14798. applyMatrix4( matrix, optionalNormalMatrix ) {
  14799. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  14800. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  14801. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  14802. this.constant = - referencePoint.dot( normal );
  14803. return this;
  14804. }
  14805. /**
  14806. * Translates the plane by the distance defined by the given offset vector.
  14807. * Note that this only affects the plane constant and will not affect the normal vector.
  14808. *
  14809. * @param {Vector3} offset - The offset vector.
  14810. * @return {Plane} A reference to this plane.
  14811. */
  14812. translate( offset ) {
  14813. this.constant -= offset.dot( this.normal );
  14814. return this;
  14815. }
  14816. /**
  14817. * Returns `true` if this plane is equal with the given one.
  14818. *
  14819. * @param {Plane} plane - The plane to test for equality.
  14820. * @return {boolean} Whether this plane is equal with the given one.
  14821. */
  14822. equals( plane ) {
  14823. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  14824. }
  14825. /**
  14826. * Returns a new plane with copied values from this instance.
  14827. *
  14828. * @return {Plane} A clone of this instance.
  14829. */
  14830. clone() {
  14831. return new this.constructor().copy( this );
  14832. }
  14833. }
  14834. const _sphere$3 = /*@__PURE__*/ new Sphere();
  14835. const _vector$6 = /*@__PURE__*/ new Vector3();
  14836. /**
  14837. * Frustums are used to determine what is inside the camera's field of view.
  14838. * They help speed up the rendering process - objects which lie outside a camera's
  14839. * frustum can safely be excluded from rendering.
  14840. *
  14841. * This class is mainly intended for use internally by a renderer.
  14842. */
  14843. class Frustum {
  14844. /**
  14845. * Constructs a new frustum.
  14846. *
  14847. * @param {Plane} [p0] - The first plane that encloses the frustum.
  14848. * @param {Plane} [p1] - The second plane that encloses the frustum.
  14849. * @param {Plane} [p2] - The third plane that encloses the frustum.
  14850. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  14851. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  14852. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  14853. */
  14854. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  14855. /**
  14856. * This array holds the planes that enclose the frustum.
  14857. *
  14858. * @type {Array<Plane>}
  14859. */
  14860. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  14861. }
  14862. /**
  14863. * Sets the frustum planens by copying the given planes.
  14864. *
  14865. * @param {Plane} [p0] - The first plane that encloses the frustum.
  14866. * @param {Plane} [p1] - The second plane that encloses the frustum.
  14867. * @param {Plane} [p2] - The third plane that encloses the frustum.
  14868. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  14869. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  14870. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  14871. * @return {Frustum} A reference to this frustum.
  14872. */
  14873. set( p0, p1, p2, p3, p4, p5 ) {
  14874. const planes = this.planes;
  14875. planes[ 0 ].copy( p0 );
  14876. planes[ 1 ].copy( p1 );
  14877. planes[ 2 ].copy( p2 );
  14878. planes[ 3 ].copy( p3 );
  14879. planes[ 4 ].copy( p4 );
  14880. planes[ 5 ].copy( p5 );
  14881. return this;
  14882. }
  14883. /**
  14884. * Copies the values of the given frustum to this instance.
  14885. *
  14886. * @param {Frustum} frustum - The frustum to copy.
  14887. * @return {Frustum} A reference to this frustum.
  14888. */
  14889. copy( frustum ) {
  14890. const planes = this.planes;
  14891. for ( let i = 0; i < 6; i ++ ) {
  14892. planes[ i ].copy( frustum.planes[ i ] );
  14893. }
  14894. return this;
  14895. }
  14896. /**
  14897. * Sets the frustum planes from the given projection matrix.
  14898. *
  14899. * @param {Matrix4} m - The projection matrix.
  14900. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  14901. * @return {Frustum} A reference to this frustum.
  14902. */
  14903. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  14904. const planes = this.planes;
  14905. const me = m.elements;
  14906. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  14907. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  14908. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  14909. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  14910. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  14911. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  14912. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  14913. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  14914. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  14915. if ( coordinateSystem === WebGLCoordinateSystem ) {
  14916. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  14917. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  14918. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  14919. } else {
  14920. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  14921. }
  14922. return this;
  14923. }
  14924. /**
  14925. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  14926. *
  14927. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  14928. *
  14929. * @param {Object3D} object - The 3D object to test.
  14930. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  14931. */
  14932. intersectsObject( object ) {
  14933. if ( object.boundingSphere !== undefined ) {
  14934. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  14935. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  14936. } else {
  14937. const geometry = object.geometry;
  14938. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14939. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  14940. }
  14941. return this.intersectsSphere( _sphere$3 );
  14942. }
  14943. /**
  14944. * Returns `true` if the given sprite is intersecting this frustum.
  14945. *
  14946. * @param {Sprite} sprite - The sprite to test.
  14947. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  14948. */
  14949. intersectsSprite( sprite ) {
  14950. _sphere$3.center.set( 0, 0, 0 );
  14951. _sphere$3.radius = 0.7071067811865476;
  14952. _sphere$3.applyMatrix4( sprite.matrixWorld );
  14953. return this.intersectsSphere( _sphere$3 );
  14954. }
  14955. /**
  14956. * Returns `true` if the given bounding sphere is intersecting this frustum.
  14957. *
  14958. * @param {Sphere} sphere - The bounding sphere to test.
  14959. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  14960. */
  14961. intersectsSphere( sphere ) {
  14962. const planes = this.planes;
  14963. const center = sphere.center;
  14964. const negRadius = - sphere.radius;
  14965. for ( let i = 0; i < 6; i ++ ) {
  14966. const distance = planes[ i ].distanceToPoint( center );
  14967. if ( distance < negRadius ) {
  14968. return false;
  14969. }
  14970. }
  14971. return true;
  14972. }
  14973. /**
  14974. * Returns `true` if the given bounding box is intersecting this frustum.
  14975. *
  14976. * @param {Box3} box - The bounding box to test.
  14977. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  14978. */
  14979. intersectsBox( box ) {
  14980. const planes = this.planes;
  14981. for ( let i = 0; i < 6; i ++ ) {
  14982. const plane = planes[ i ];
  14983. // corner at max distance
  14984. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  14985. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  14986. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  14987. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  14988. return false;
  14989. }
  14990. }
  14991. return true;
  14992. }
  14993. /**
  14994. * Returns `true` if the given point lies within the frustum.
  14995. *
  14996. * @param {Vector3} point - The point to test.
  14997. * @return {boolean} Whether the point liest within this frustum or not.
  14998. */
  14999. containsPoint( point ) {
  15000. const planes = this.planes;
  15001. for ( let i = 0; i < 6; i ++ ) {
  15002. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  15003. return false;
  15004. }
  15005. }
  15006. return true;
  15007. }
  15008. /**
  15009. * Returns a new frustum with copied values from this instance.
  15010. *
  15011. * @return {Frustum} A clone of this instance.
  15012. */
  15013. clone() {
  15014. return new this.constructor().copy( this );
  15015. }
  15016. }
  15017. function ascIdSort( a, b ) {
  15018. return a - b;
  15019. }
  15020. function sortOpaque( a, b ) {
  15021. return a.z - b.z;
  15022. }
  15023. function sortTransparent( a, b ) {
  15024. return b.z - a.z;
  15025. }
  15026. class MultiDrawRenderList {
  15027. constructor() {
  15028. this.index = 0;
  15029. this.pool = [];
  15030. this.list = [];
  15031. }
  15032. push( start, count, z, index ) {
  15033. const pool = this.pool;
  15034. const list = this.list;
  15035. if ( this.index >= pool.length ) {
  15036. pool.push( {
  15037. start: -1,
  15038. count: -1,
  15039. z: -1,
  15040. index: -1,
  15041. } );
  15042. }
  15043. const item = pool[ this.index ];
  15044. list.push( item );
  15045. this.index ++;
  15046. item.start = start;
  15047. item.count = count;
  15048. item.z = z;
  15049. item.index = index;
  15050. }
  15051. reset() {
  15052. this.list.length = 0;
  15053. this.index = 0;
  15054. }
  15055. }
  15056. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  15057. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  15058. const _frustum = /*@__PURE__*/ new Frustum();
  15059. const _box$1 = /*@__PURE__*/ new Box3();
  15060. const _sphere$2 = /*@__PURE__*/ new Sphere();
  15061. const _vector$5 = /*@__PURE__*/ new Vector3();
  15062. const _forward = /*@__PURE__*/ new Vector3();
  15063. const _temp = /*@__PURE__*/ new Vector3();
  15064. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  15065. const _mesh = /*@__PURE__*/ new Mesh();
  15066. const _batchIntersects = [];
  15067. // copies data from attribute "src" into "target" starting at "targetOffset"
  15068. function copyAttributeData( src, target, targetOffset = 0 ) {
  15069. const itemSize = target.itemSize;
  15070. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  15071. // use the component getters and setters if the array data cannot
  15072. // be copied directly
  15073. const vertexCount = src.count;
  15074. for ( let i = 0; i < vertexCount; i ++ ) {
  15075. for ( let c = 0; c < itemSize; c ++ ) {
  15076. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  15077. }
  15078. }
  15079. } else {
  15080. // faster copy approach using typed array set function
  15081. target.array.set( src.array, targetOffset * itemSize );
  15082. }
  15083. target.needsUpdate = true;
  15084. }
  15085. // safely copies array contents to a potentially smaller array
  15086. function copyArrayContents( src, target ) {
  15087. if ( src.constructor !== target.constructor ) {
  15088. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  15089. const len = Math.min( src.length, target.length );
  15090. for ( let i = 0; i < len; i ++ ) {
  15091. target[ i ] = src[ i ];
  15092. }
  15093. } else {
  15094. // if the arrays use the same data layout we can use a fast block copy
  15095. const len = Math.min( src.length, target.length );
  15096. target.set( new src.constructor( src.buffer, 0, len ) );
  15097. }
  15098. }
  15099. class BatchedMesh extends Mesh {
  15100. get maxInstanceCount() {
  15101. return this._maxInstanceCount;
  15102. }
  15103. get instanceCount() {
  15104. return this._instanceInfo.length - this._availableInstanceIds.length;
  15105. }
  15106. get unusedVertexCount() {
  15107. return this._maxVertexCount - this._nextVertexStart;
  15108. }
  15109. get unusedIndexCount() {
  15110. return this._maxIndexCount - this._nextIndexStart;
  15111. }
  15112. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  15113. super( new BufferGeometry(), material );
  15114. this.isBatchedMesh = true;
  15115. this.perObjectFrustumCulled = true;
  15116. this.sortObjects = true;
  15117. this.boundingBox = null;
  15118. this.boundingSphere = null;
  15119. this.customSort = null;
  15120. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  15121. this._instanceInfo = [];
  15122. this._geometryInfo = [];
  15123. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  15124. this._availableInstanceIds = [];
  15125. this._availableGeometryIds = [];
  15126. // used to track where the next point is that geometry should be inserted
  15127. this._nextIndexStart = 0;
  15128. this._nextVertexStart = 0;
  15129. this._geometryCount = 0;
  15130. // flags
  15131. this._visibilityChanged = true;
  15132. this._geometryInitialized = false;
  15133. // cached user options
  15134. this._maxInstanceCount = maxInstanceCount;
  15135. this._maxVertexCount = maxVertexCount;
  15136. this._maxIndexCount = maxIndexCount;
  15137. // buffers for multi draw
  15138. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  15139. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  15140. this._multiDrawCount = 0;
  15141. this._multiDrawInstances = null;
  15142. // Local matrix per geometry by using data texture
  15143. this._matricesTexture = null;
  15144. this._indirectTexture = null;
  15145. this._colorsTexture = null;
  15146. this._initMatricesTexture();
  15147. this._initIndirectTexture();
  15148. }
  15149. _initMatricesTexture() {
  15150. // layout (1 matrix = 4 pixels)
  15151. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15152. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  15153. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  15154. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  15155. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  15156. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  15157. size = Math.ceil( size / 4 ) * 4;
  15158. size = Math.max( size, 4 );
  15159. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15160. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  15161. this._matricesTexture = matricesTexture;
  15162. }
  15163. _initIndirectTexture() {
  15164. let size = Math.sqrt( this._maxInstanceCount );
  15165. size = Math.ceil( size );
  15166. const indirectArray = new Uint32Array( size * size );
  15167. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  15168. this._indirectTexture = indirectTexture;
  15169. }
  15170. _initColorsTexture() {
  15171. let size = Math.sqrt( this._maxInstanceCount );
  15172. size = Math.ceil( size );
  15173. // 4 floats per RGBA pixel initialized to white
  15174. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  15175. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  15176. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  15177. this._colorsTexture = colorsTexture;
  15178. }
  15179. _initializeGeometry( reference ) {
  15180. const geometry = this.geometry;
  15181. const maxVertexCount = this._maxVertexCount;
  15182. const maxIndexCount = this._maxIndexCount;
  15183. if ( this._geometryInitialized === false ) {
  15184. for ( const attributeName in reference.attributes ) {
  15185. const srcAttribute = reference.getAttribute( attributeName );
  15186. const { array, itemSize, normalized } = srcAttribute;
  15187. const dstArray = new array.constructor( maxVertexCount * itemSize );
  15188. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  15189. geometry.setAttribute( attributeName, dstAttribute );
  15190. }
  15191. if ( reference.getIndex() !== null ) {
  15192. // Reserve last u16 index for primitive restart.
  15193. const indexArray = maxVertexCount > 65535
  15194. ? new Uint32Array( maxIndexCount )
  15195. : new Uint16Array( maxIndexCount );
  15196. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  15197. }
  15198. this._geometryInitialized = true;
  15199. }
  15200. }
  15201. // Make sure the geometry is compatible with the existing combined geometry attributes
  15202. _validateGeometry( geometry ) {
  15203. // check to ensure the geometries are using consistent attributes and indices
  15204. const batchGeometry = this.geometry;
  15205. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  15206. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  15207. }
  15208. for ( const attributeName in batchGeometry.attributes ) {
  15209. if ( ! geometry.hasAttribute( attributeName ) ) {
  15210. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  15211. }
  15212. const srcAttribute = geometry.getAttribute( attributeName );
  15213. const dstAttribute = batchGeometry.getAttribute( attributeName );
  15214. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  15215. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  15216. }
  15217. }
  15218. }
  15219. validateInstanceId( instanceId ) {
  15220. const instanceInfo = this._instanceInfo;
  15221. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  15222. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  15223. }
  15224. }
  15225. validateGeometryId( geometryId ) {
  15226. const geometryInfoList = this._geometryInfo;
  15227. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  15228. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  15229. }
  15230. }
  15231. setCustomSort( func ) {
  15232. this.customSort = func;
  15233. return this;
  15234. }
  15235. computeBoundingBox() {
  15236. if ( this.boundingBox === null ) {
  15237. this.boundingBox = new Box3();
  15238. }
  15239. const boundingBox = this.boundingBox;
  15240. const instanceInfo = this._instanceInfo;
  15241. boundingBox.makeEmpty();
  15242. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15243. if ( instanceInfo[ i ].active === false ) continue;
  15244. const geometryId = instanceInfo[ i ].geometryIndex;
  15245. this.getMatrixAt( i, _matrix$1 );
  15246. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  15247. boundingBox.union( _box$1 );
  15248. }
  15249. }
  15250. computeBoundingSphere() {
  15251. if ( this.boundingSphere === null ) {
  15252. this.boundingSphere = new Sphere();
  15253. }
  15254. const boundingSphere = this.boundingSphere;
  15255. const instanceInfo = this._instanceInfo;
  15256. boundingSphere.makeEmpty();
  15257. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15258. if ( instanceInfo[ i ].active === false ) continue;
  15259. const geometryId = instanceInfo[ i ].geometryIndex;
  15260. this.getMatrixAt( i, _matrix$1 );
  15261. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  15262. boundingSphere.union( _sphere$2 );
  15263. }
  15264. }
  15265. addInstance( geometryId ) {
  15266. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  15267. // ensure we're not over geometry
  15268. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  15269. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  15270. }
  15271. const instanceInfo = {
  15272. visible: true,
  15273. active: true,
  15274. geometryIndex: geometryId,
  15275. };
  15276. let drawId = null;
  15277. // Prioritize using previously freed instance ids
  15278. if ( this._availableInstanceIds.length > 0 ) {
  15279. this._availableInstanceIds.sort( ascIdSort );
  15280. drawId = this._availableInstanceIds.shift();
  15281. this._instanceInfo[ drawId ] = instanceInfo;
  15282. } else {
  15283. drawId = this._instanceInfo.length;
  15284. this._instanceInfo.push( instanceInfo );
  15285. }
  15286. const matricesTexture = this._matricesTexture;
  15287. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  15288. matricesTexture.needsUpdate = true;
  15289. const colorsTexture = this._colorsTexture;
  15290. if ( colorsTexture ) {
  15291. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  15292. colorsTexture.needsUpdate = true;
  15293. }
  15294. this._visibilityChanged = true;
  15295. return drawId;
  15296. }
  15297. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  15298. this._initializeGeometry( geometry );
  15299. this._validateGeometry( geometry );
  15300. const geometryInfo = {
  15301. // geometry information
  15302. vertexStart: -1,
  15303. vertexCount: -1,
  15304. reservedVertexCount: -1,
  15305. indexStart: -1,
  15306. indexCount: -1,
  15307. reservedIndexCount: -1,
  15308. // draw range information
  15309. start: -1,
  15310. count: -1,
  15311. // state
  15312. boundingBox: null,
  15313. boundingSphere: null,
  15314. active: true,
  15315. };
  15316. const geometryInfoList = this._geometryInfo;
  15317. geometryInfo.vertexStart = this._nextVertexStart;
  15318. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  15319. const index = geometry.getIndex();
  15320. const hasIndex = index !== null;
  15321. if ( hasIndex ) {
  15322. geometryInfo.indexStart = this._nextIndexStart;
  15323. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  15324. }
  15325. if (
  15326. geometryInfo.indexStart !== -1 &&
  15327. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  15328. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  15329. ) {
  15330. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  15331. }
  15332. // update id
  15333. let geometryId;
  15334. if ( this._availableGeometryIds.length > 0 ) {
  15335. this._availableGeometryIds.sort( ascIdSort );
  15336. geometryId = this._availableGeometryIds.shift();
  15337. geometryInfoList[ geometryId ] = geometryInfo;
  15338. } else {
  15339. geometryId = this._geometryCount;
  15340. this._geometryCount ++;
  15341. geometryInfoList.push( geometryInfo );
  15342. }
  15343. // update the geometry
  15344. this.setGeometryAt( geometryId, geometry );
  15345. // increment the next geometry position
  15346. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  15347. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  15348. return geometryId;
  15349. }
  15350. setGeometryAt( geometryId, geometry ) {
  15351. if ( geometryId >= this._geometryCount ) {
  15352. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  15353. }
  15354. this._validateGeometry( geometry );
  15355. const batchGeometry = this.geometry;
  15356. const hasIndex = batchGeometry.getIndex() !== null;
  15357. const dstIndex = batchGeometry.getIndex();
  15358. const srcIndex = geometry.getIndex();
  15359. const geometryInfo = this._geometryInfo[ geometryId ];
  15360. if (
  15361. hasIndex &&
  15362. srcIndex.count > geometryInfo.reservedIndexCount ||
  15363. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  15364. ) {
  15365. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  15366. }
  15367. // copy geometry buffer data over
  15368. const vertexStart = geometryInfo.vertexStart;
  15369. const reservedVertexCount = geometryInfo.reservedVertexCount;
  15370. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  15371. for ( const attributeName in batchGeometry.attributes ) {
  15372. // copy attribute data
  15373. const srcAttribute = geometry.getAttribute( attributeName );
  15374. const dstAttribute = batchGeometry.getAttribute( attributeName );
  15375. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  15376. // fill the rest in with zeroes
  15377. const itemSize = srcAttribute.itemSize;
  15378. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  15379. const index = vertexStart + i;
  15380. for ( let c = 0; c < itemSize; c ++ ) {
  15381. dstAttribute.setComponent( index, c, 0 );
  15382. }
  15383. }
  15384. dstAttribute.needsUpdate = true;
  15385. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  15386. }
  15387. // copy index
  15388. if ( hasIndex ) {
  15389. const indexStart = geometryInfo.indexStart;
  15390. const reservedIndexCount = geometryInfo.reservedIndexCount;
  15391. geometryInfo.indexCount = geometry.getIndex().count;
  15392. // copy index data over
  15393. for ( let i = 0; i < srcIndex.count; i ++ ) {
  15394. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  15395. }
  15396. // fill the rest in with zeroes
  15397. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  15398. dstIndex.setX( indexStart + i, vertexStart );
  15399. }
  15400. dstIndex.needsUpdate = true;
  15401. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  15402. }
  15403. // update the draw range
  15404. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  15405. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  15406. // store the bounding boxes
  15407. geometryInfo.boundingBox = null;
  15408. if ( geometry.boundingBox !== null ) {
  15409. geometryInfo.boundingBox = geometry.boundingBox.clone();
  15410. }
  15411. geometryInfo.boundingSphere = null;
  15412. if ( geometry.boundingSphere !== null ) {
  15413. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  15414. }
  15415. this._visibilityChanged = true;
  15416. return geometryId;
  15417. }
  15418. deleteGeometry( geometryId ) {
  15419. const geometryInfoList = this._geometryInfo;
  15420. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  15421. return this;
  15422. }
  15423. // delete any instances associated with this geometry
  15424. const instanceInfo = this._instanceInfo;
  15425. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15426. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  15427. this.deleteInstance( i );
  15428. }
  15429. }
  15430. geometryInfoList[ geometryId ].active = false;
  15431. this._availableGeometryIds.push( geometryId );
  15432. this._visibilityChanged = true;
  15433. return this;
  15434. }
  15435. deleteInstance( instanceId ) {
  15436. this.validateInstanceId( instanceId );
  15437. this._instanceInfo[ instanceId ].active = false;
  15438. this._availableInstanceIds.push( instanceId );
  15439. this._visibilityChanged = true;
  15440. return this;
  15441. }
  15442. optimize() {
  15443. // track the next indices to copy data to
  15444. let nextVertexStart = 0;
  15445. let nextIndexStart = 0;
  15446. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  15447. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  15448. const geometryInfoList = this._geometryInfo;
  15449. const indices = geometryInfoList
  15450. .map( ( e, i ) => i )
  15451. .sort( ( a, b ) => {
  15452. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  15453. } );
  15454. const geometry = this.geometry;
  15455. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  15456. // if a geometry range is inactive then don't copy anything
  15457. const index = indices[ i ];
  15458. const geometryInfo = geometryInfoList[ index ];
  15459. if ( geometryInfo.active === false ) {
  15460. continue;
  15461. }
  15462. // if a geometry contains an index buffer then shift it, as well
  15463. if ( geometry.index !== null ) {
  15464. if ( geometryInfo.indexStart !== nextIndexStart ) {
  15465. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  15466. const index = geometry.index;
  15467. const array = index.array;
  15468. // shift the index pointers based on how the vertex data will shift
  15469. // adjusting the index must happen first so the original vertex start value is available
  15470. const elementDelta = nextVertexStart - vertexStart;
  15471. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  15472. array[ j ] = array[ j ] + elementDelta;
  15473. }
  15474. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  15475. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  15476. geometryInfo.indexStart = nextIndexStart;
  15477. }
  15478. nextIndexStart += geometryInfo.reservedIndexCount;
  15479. }
  15480. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  15481. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  15482. const { vertexStart, reservedVertexCount } = geometryInfo;
  15483. const attributes = geometry.attributes;
  15484. for ( const key in attributes ) {
  15485. const attribute = attributes[ key ];
  15486. const { array, itemSize } = attribute;
  15487. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  15488. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  15489. }
  15490. geometryInfo.vertexStart = nextVertexStart;
  15491. }
  15492. nextVertexStart += geometryInfo.reservedVertexCount;
  15493. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  15494. // step the next geometry points to the shifted position
  15495. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  15496. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  15497. }
  15498. return this;
  15499. }
  15500. // get bounding box and compute it if it doesn't exist
  15501. getBoundingBoxAt( geometryId, target ) {
  15502. if ( geometryId >= this._geometryCount ) {
  15503. return null;
  15504. }
  15505. // compute bounding box
  15506. const geometry = this.geometry;
  15507. const geometryInfo = this._geometryInfo[ geometryId ];
  15508. if ( geometryInfo.boundingBox === null ) {
  15509. const box = new Box3();
  15510. const index = geometry.index;
  15511. const position = geometry.attributes.position;
  15512. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  15513. let iv = i;
  15514. if ( index ) {
  15515. iv = index.getX( iv );
  15516. }
  15517. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  15518. }
  15519. geometryInfo.boundingBox = box;
  15520. }
  15521. target.copy( geometryInfo.boundingBox );
  15522. return target;
  15523. }
  15524. // get bounding sphere and compute it if it doesn't exist
  15525. getBoundingSphereAt( geometryId, target ) {
  15526. if ( geometryId >= this._geometryCount ) {
  15527. return null;
  15528. }
  15529. // compute bounding sphere
  15530. const geometry = this.geometry;
  15531. const geometryInfo = this._geometryInfo[ geometryId ];
  15532. if ( geometryInfo.boundingSphere === null ) {
  15533. const sphere = new Sphere();
  15534. this.getBoundingBoxAt( geometryId, _box$1 );
  15535. _box$1.getCenter( sphere.center );
  15536. const index = geometry.index;
  15537. const position = geometry.attributes.position;
  15538. let maxRadiusSq = 0;
  15539. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  15540. let iv = i;
  15541. if ( index ) {
  15542. iv = index.getX( iv );
  15543. }
  15544. _vector$5.fromBufferAttribute( position, iv );
  15545. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  15546. }
  15547. sphere.radius = Math.sqrt( maxRadiusSq );
  15548. geometryInfo.boundingSphere = sphere;
  15549. }
  15550. target.copy( geometryInfo.boundingSphere );
  15551. return target;
  15552. }
  15553. setMatrixAt( instanceId, matrix ) {
  15554. this.validateInstanceId( instanceId );
  15555. const matricesTexture = this._matricesTexture;
  15556. const matricesArray = this._matricesTexture.image.data;
  15557. matrix.toArray( matricesArray, instanceId * 16 );
  15558. matricesTexture.needsUpdate = true;
  15559. return this;
  15560. }
  15561. getMatrixAt( instanceId, matrix ) {
  15562. this.validateInstanceId( instanceId );
  15563. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  15564. }
  15565. setColorAt( instanceId, color ) {
  15566. this.validateInstanceId( instanceId );
  15567. if ( this._colorsTexture === null ) {
  15568. this._initColorsTexture();
  15569. }
  15570. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  15571. this._colorsTexture.needsUpdate = true;
  15572. return this;
  15573. }
  15574. getColorAt( instanceId, color ) {
  15575. this.validateInstanceId( instanceId );
  15576. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  15577. }
  15578. setVisibleAt( instanceId, value ) {
  15579. this.validateInstanceId( instanceId );
  15580. if ( this._instanceInfo[ instanceId ].visible === value ) {
  15581. return this;
  15582. }
  15583. this._instanceInfo[ instanceId ].visible = value;
  15584. this._visibilityChanged = true;
  15585. return this;
  15586. }
  15587. getVisibleAt( instanceId ) {
  15588. this.validateInstanceId( instanceId );
  15589. return this._instanceInfo[ instanceId ].visible;
  15590. }
  15591. setGeometryIdAt( instanceId, geometryId ) {
  15592. this.validateInstanceId( instanceId );
  15593. this.validateGeometryId( geometryId );
  15594. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  15595. return this;
  15596. }
  15597. getGeometryIdAt( instanceId ) {
  15598. this.validateInstanceId( instanceId );
  15599. return this._instanceInfo[ instanceId ].geometryIndex;
  15600. }
  15601. getGeometryRangeAt( geometryId, target = {} ) {
  15602. this.validateGeometryId( geometryId );
  15603. const geometryInfo = this._geometryInfo[ geometryId ];
  15604. target.vertexStart = geometryInfo.vertexStart;
  15605. target.vertexCount = geometryInfo.vertexCount;
  15606. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  15607. target.indexStart = geometryInfo.indexStart;
  15608. target.indexCount = geometryInfo.indexCount;
  15609. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  15610. target.start = geometryInfo.start;
  15611. target.count = geometryInfo.count;
  15612. return target;
  15613. }
  15614. setInstanceCount( maxInstanceCount ) {
  15615. // shrink the available instances as much as possible
  15616. const availableInstanceIds = this._availableInstanceIds;
  15617. const instanceInfo = this._instanceInfo;
  15618. availableInstanceIds.sort( ascIdSort );
  15619. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  15620. instanceInfo.pop();
  15621. availableInstanceIds.pop();
  15622. }
  15623. // throw an error if it can't be shrunk to the desired size
  15624. if ( maxInstanceCount < instanceInfo.length ) {
  15625. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  15626. }
  15627. // copy the multi draw counts
  15628. const multiDrawCounts = new Int32Array( maxInstanceCount );
  15629. const multiDrawStarts = new Int32Array( maxInstanceCount );
  15630. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  15631. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  15632. this._multiDrawCounts = multiDrawCounts;
  15633. this._multiDrawStarts = multiDrawStarts;
  15634. this._maxInstanceCount = maxInstanceCount;
  15635. // update texture data for instance sampling
  15636. const indirectTexture = this._indirectTexture;
  15637. const matricesTexture = this._matricesTexture;
  15638. const colorsTexture = this._colorsTexture;
  15639. indirectTexture.dispose();
  15640. this._initIndirectTexture();
  15641. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  15642. matricesTexture.dispose();
  15643. this._initMatricesTexture();
  15644. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  15645. if ( colorsTexture ) {
  15646. colorsTexture.dispose();
  15647. this._initColorsTexture();
  15648. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  15649. }
  15650. }
  15651. setGeometrySize( maxVertexCount, maxIndexCount ) {
  15652. // Check if we can shrink to the requested vertex attribute size
  15653. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  15654. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  15655. if ( requiredVertexLength > maxVertexCount ) {
  15656. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  15657. }
  15658. // Check if we can shrink to the requested index attribute size
  15659. if ( this.geometry.index ) {
  15660. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  15661. if ( requiredIndexLength > maxIndexCount ) {
  15662. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  15663. }
  15664. }
  15665. //
  15666. // dispose of the previous geometry
  15667. const oldGeometry = this.geometry;
  15668. oldGeometry.dispose();
  15669. // recreate the geometry needed based on the previous variant
  15670. this._maxVertexCount = maxVertexCount;
  15671. this._maxIndexCount = maxIndexCount;
  15672. if ( this._geometryInitialized ) {
  15673. this._geometryInitialized = false;
  15674. this.geometry = new BufferGeometry();
  15675. this._initializeGeometry( oldGeometry );
  15676. }
  15677. // copy data from the previous geometry
  15678. const geometry = this.geometry;
  15679. if ( oldGeometry.index ) {
  15680. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  15681. }
  15682. for ( const key in oldGeometry.attributes ) {
  15683. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  15684. }
  15685. }
  15686. raycast( raycaster, intersects ) {
  15687. const instanceInfo = this._instanceInfo;
  15688. const geometryInfoList = this._geometryInfo;
  15689. const matrixWorld = this.matrixWorld;
  15690. const batchGeometry = this.geometry;
  15691. // iterate over each geometry
  15692. _mesh.material = this.material;
  15693. _mesh.geometry.index = batchGeometry.index;
  15694. _mesh.geometry.attributes = batchGeometry.attributes;
  15695. if ( _mesh.geometry.boundingBox === null ) {
  15696. _mesh.geometry.boundingBox = new Box3();
  15697. }
  15698. if ( _mesh.geometry.boundingSphere === null ) {
  15699. _mesh.geometry.boundingSphere = new Sphere();
  15700. }
  15701. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15702. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  15703. continue;
  15704. }
  15705. const geometryId = instanceInfo[ i ].geometryIndex;
  15706. const geometryInfo = geometryInfoList[ geometryId ];
  15707. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  15708. // get the intersects
  15709. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  15710. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  15711. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  15712. _mesh.raycast( raycaster, _batchIntersects );
  15713. // add batch id to the intersects
  15714. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  15715. const intersect = _batchIntersects[ j ];
  15716. intersect.object = this;
  15717. intersect.batchId = i;
  15718. intersects.push( intersect );
  15719. }
  15720. _batchIntersects.length = 0;
  15721. }
  15722. _mesh.material = null;
  15723. _mesh.geometry.index = null;
  15724. _mesh.geometry.attributes = {};
  15725. _mesh.geometry.setDrawRange( 0, Infinity );
  15726. }
  15727. copy( source ) {
  15728. super.copy( source );
  15729. this.geometry = source.geometry.clone();
  15730. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  15731. this.sortObjects = source.sortObjects;
  15732. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  15733. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  15734. this._geometryInfo = source._geometryInfo.map( info => ( {
  15735. ...info,
  15736. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  15737. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  15738. } ) );
  15739. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  15740. this._maxInstanceCount = source._maxInstanceCount;
  15741. this._maxVertexCount = source._maxVertexCount;
  15742. this._maxIndexCount = source._maxIndexCount;
  15743. this._geometryInitialized = source._geometryInitialized;
  15744. this._geometryCount = source._geometryCount;
  15745. this._multiDrawCounts = source._multiDrawCounts.slice();
  15746. this._multiDrawStarts = source._multiDrawStarts.slice();
  15747. this._matricesTexture = source._matricesTexture.clone();
  15748. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  15749. if ( this._colorsTexture !== null ) {
  15750. this._colorsTexture = source._colorsTexture.clone();
  15751. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  15752. }
  15753. return this;
  15754. }
  15755. dispose() {
  15756. // Assuming the geometry is not shared with other meshes
  15757. this.geometry.dispose();
  15758. this._matricesTexture.dispose();
  15759. this._matricesTexture = null;
  15760. this._indirectTexture.dispose();
  15761. this._indirectTexture = null;
  15762. if ( this._colorsTexture !== null ) {
  15763. this._colorsTexture.dispose();
  15764. this._colorsTexture = null;
  15765. }
  15766. return this;
  15767. }
  15768. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  15769. // if visibility has not changed and frustum culling and object sorting is not required
  15770. // then skip iterating over all items
  15771. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  15772. return;
  15773. }
  15774. // the indexed version of the multi draw function requires specifying the start
  15775. // offset in bytes.
  15776. const index = geometry.getIndex();
  15777. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  15778. const instanceInfo = this._instanceInfo;
  15779. const multiDrawStarts = this._multiDrawStarts;
  15780. const multiDrawCounts = this._multiDrawCounts;
  15781. const geometryInfoList = this._geometryInfo;
  15782. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  15783. const indirectTexture = this._indirectTexture;
  15784. const indirectArray = indirectTexture.image.data;
  15785. // prepare the frustum in the local frame
  15786. if ( perObjectFrustumCulled ) {
  15787. _matrix$1
  15788. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  15789. .multiply( this.matrixWorld );
  15790. _frustum.setFromProjectionMatrix(
  15791. _matrix$1,
  15792. renderer.coordinateSystem
  15793. );
  15794. }
  15795. let multiDrawCount = 0;
  15796. if ( this.sortObjects ) {
  15797. // get the camera position in the local frame
  15798. _matrix$1.copy( this.matrixWorld ).invert();
  15799. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  15800. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  15801. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15802. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  15803. const geometryId = instanceInfo[ i ].geometryIndex;
  15804. // get the bounds in world space
  15805. this.getMatrixAt( i, _matrix$1 );
  15806. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  15807. // determine whether the batched geometry is within the frustum
  15808. let culled = false;
  15809. if ( perObjectFrustumCulled ) {
  15810. culled = ! _frustum.intersectsSphere( _sphere$2 );
  15811. }
  15812. if ( ! culled ) {
  15813. // get the distance from camera used for sorting
  15814. const geometryInfo = geometryInfoList[ geometryId ];
  15815. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  15816. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  15817. }
  15818. }
  15819. }
  15820. // Sort the draw ranges and prep for rendering
  15821. const list = _renderList.list;
  15822. const customSort = this.customSort;
  15823. if ( customSort === null ) {
  15824. list.sort( material.transparent ? sortTransparent : sortOpaque );
  15825. } else {
  15826. customSort.call( this, list, camera );
  15827. }
  15828. for ( let i = 0, l = list.length; i < l; i ++ ) {
  15829. const item = list[ i ];
  15830. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  15831. multiDrawCounts[ multiDrawCount ] = item.count;
  15832. indirectArray[ multiDrawCount ] = item.index;
  15833. multiDrawCount ++;
  15834. }
  15835. _renderList.reset();
  15836. } else {
  15837. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15838. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  15839. const geometryId = instanceInfo[ i ].geometryIndex;
  15840. // determine whether the batched geometry is within the frustum
  15841. let culled = false;
  15842. if ( perObjectFrustumCulled ) {
  15843. // get the bounds in world space
  15844. this.getMatrixAt( i, _matrix$1 );
  15845. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  15846. culled = ! _frustum.intersectsSphere( _sphere$2 );
  15847. }
  15848. if ( ! culled ) {
  15849. const geometryInfo = geometryInfoList[ geometryId ];
  15850. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  15851. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  15852. indirectArray[ multiDrawCount ] = i;
  15853. multiDrawCount ++;
  15854. }
  15855. }
  15856. }
  15857. }
  15858. indirectTexture.needsUpdate = true;
  15859. this._multiDrawCount = multiDrawCount;
  15860. this._visibilityChanged = false;
  15861. }
  15862. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  15863. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  15864. }
  15865. }
  15866. class LineBasicMaterial extends Material {
  15867. constructor( parameters ) {
  15868. super();
  15869. this.isLineBasicMaterial = true;
  15870. this.type = 'LineBasicMaterial';
  15871. this.color = new Color( 0xffffff );
  15872. this.map = null;
  15873. this.linewidth = 1;
  15874. this.linecap = 'round';
  15875. this.linejoin = 'round';
  15876. this.fog = true;
  15877. this.setValues( parameters );
  15878. }
  15879. copy( source ) {
  15880. super.copy( source );
  15881. this.color.copy( source.color );
  15882. this.map = source.map;
  15883. this.linewidth = source.linewidth;
  15884. this.linecap = source.linecap;
  15885. this.linejoin = source.linejoin;
  15886. this.fog = source.fog;
  15887. return this;
  15888. }
  15889. }
  15890. const _vStart = /*@__PURE__*/ new Vector3();
  15891. const _vEnd = /*@__PURE__*/ new Vector3();
  15892. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  15893. const _ray$1 = /*@__PURE__*/ new Ray();
  15894. const _sphere$1 = /*@__PURE__*/ new Sphere();
  15895. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  15896. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  15897. class Line extends Object3D {
  15898. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  15899. super();
  15900. this.isLine = true;
  15901. this.type = 'Line';
  15902. this.geometry = geometry;
  15903. this.material = material;
  15904. this.updateMorphTargets();
  15905. }
  15906. copy( source, recursive ) {
  15907. super.copy( source, recursive );
  15908. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15909. this.geometry = source.geometry;
  15910. return this;
  15911. }
  15912. computeLineDistances() {
  15913. const geometry = this.geometry;
  15914. // we assume non-indexed geometry
  15915. if ( geometry.index === null ) {
  15916. const positionAttribute = geometry.attributes.position;
  15917. const lineDistances = [ 0 ];
  15918. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  15919. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  15920. _vEnd.fromBufferAttribute( positionAttribute, i );
  15921. lineDistances[ i ] = lineDistances[ i - 1 ];
  15922. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  15923. }
  15924. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15925. } else {
  15926. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15927. }
  15928. return this;
  15929. }
  15930. raycast( raycaster, intersects ) {
  15931. const geometry = this.geometry;
  15932. const matrixWorld = this.matrixWorld;
  15933. const threshold = raycaster.params.Line.threshold;
  15934. const drawRange = geometry.drawRange;
  15935. // Checking boundingSphere distance to ray
  15936. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15937. _sphere$1.copy( geometry.boundingSphere );
  15938. _sphere$1.applyMatrix4( matrixWorld );
  15939. _sphere$1.radius += threshold;
  15940. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  15941. //
  15942. _inverseMatrix$1.copy( matrixWorld ).invert();
  15943. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  15944. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  15945. const localThresholdSq = localThreshold * localThreshold;
  15946. const step = this.isLineSegments ? 2 : 1;
  15947. const index = geometry.index;
  15948. const attributes = geometry.attributes;
  15949. const positionAttribute = attributes.position;
  15950. if ( index !== null ) {
  15951. const start = Math.max( 0, drawRange.start );
  15952. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15953. for ( let i = start, l = end - 1; i < l; i += step ) {
  15954. const a = index.getX( i );
  15955. const b = index.getX( i + 1 );
  15956. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  15957. if ( intersect ) {
  15958. intersects.push( intersect );
  15959. }
  15960. }
  15961. if ( this.isLineLoop ) {
  15962. const a = index.getX( end - 1 );
  15963. const b = index.getX( start );
  15964. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  15965. if ( intersect ) {
  15966. intersects.push( intersect );
  15967. }
  15968. }
  15969. } else {
  15970. const start = Math.max( 0, drawRange.start );
  15971. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  15972. for ( let i = start, l = end - 1; i < l; i += step ) {
  15973. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  15974. if ( intersect ) {
  15975. intersects.push( intersect );
  15976. }
  15977. }
  15978. if ( this.isLineLoop ) {
  15979. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  15980. if ( intersect ) {
  15981. intersects.push( intersect );
  15982. }
  15983. }
  15984. }
  15985. }
  15986. updateMorphTargets() {
  15987. const geometry = this.geometry;
  15988. const morphAttributes = geometry.morphAttributes;
  15989. const keys = Object.keys( morphAttributes );
  15990. if ( keys.length > 0 ) {
  15991. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15992. if ( morphAttribute !== undefined ) {
  15993. this.morphTargetInfluences = [];
  15994. this.morphTargetDictionary = {};
  15995. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15996. const name = morphAttribute[ m ].name || String( m );
  15997. this.morphTargetInfluences.push( 0 );
  15998. this.morphTargetDictionary[ name ] = m;
  15999. }
  16000. }
  16001. }
  16002. }
  16003. }
  16004. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  16005. const positionAttribute = object.geometry.attributes.position;
  16006. _vStart.fromBufferAttribute( positionAttribute, a );
  16007. _vEnd.fromBufferAttribute( positionAttribute, b );
  16008. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  16009. if ( distSq > thresholdSq ) return;
  16010. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  16011. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  16012. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16013. return {
  16014. distance: distance,
  16015. // What do we want? intersection point on the ray or on the segment??
  16016. // point: raycaster.ray.at( distance ),
  16017. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  16018. index: i,
  16019. face: null,
  16020. faceIndex: null,
  16021. barycoord: null,
  16022. object: object
  16023. };
  16024. }
  16025. const _start = /*@__PURE__*/ new Vector3();
  16026. const _end = /*@__PURE__*/ new Vector3();
  16027. class LineSegments extends Line {
  16028. constructor( geometry, material ) {
  16029. super( geometry, material );
  16030. this.isLineSegments = true;
  16031. this.type = 'LineSegments';
  16032. }
  16033. computeLineDistances() {
  16034. const geometry = this.geometry;
  16035. // we assume non-indexed geometry
  16036. if ( geometry.index === null ) {
  16037. const positionAttribute = geometry.attributes.position;
  16038. const lineDistances = [];
  16039. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16040. _start.fromBufferAttribute( positionAttribute, i );
  16041. _end.fromBufferAttribute( positionAttribute, i + 1 );
  16042. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16043. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  16044. }
  16045. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16046. } else {
  16047. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16048. }
  16049. return this;
  16050. }
  16051. }
  16052. class LineLoop extends Line {
  16053. constructor( geometry, material ) {
  16054. super( geometry, material );
  16055. this.isLineLoop = true;
  16056. this.type = 'LineLoop';
  16057. }
  16058. }
  16059. class PointsMaterial extends Material {
  16060. constructor( parameters ) {
  16061. super();
  16062. this.isPointsMaterial = true;
  16063. this.type = 'PointsMaterial';
  16064. this.color = new Color( 0xffffff );
  16065. this.map = null;
  16066. this.alphaMap = null;
  16067. this.size = 1;
  16068. this.sizeAttenuation = true;
  16069. this.fog = true;
  16070. this.setValues( parameters );
  16071. }
  16072. copy( source ) {
  16073. super.copy( source );
  16074. this.color.copy( source.color );
  16075. this.map = source.map;
  16076. this.alphaMap = source.alphaMap;
  16077. this.size = source.size;
  16078. this.sizeAttenuation = source.sizeAttenuation;
  16079. this.fog = source.fog;
  16080. return this;
  16081. }
  16082. }
  16083. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  16084. const _ray = /*@__PURE__*/ new Ray();
  16085. const _sphere = /*@__PURE__*/ new Sphere();
  16086. const _position$2 = /*@__PURE__*/ new Vector3();
  16087. class Points extends Object3D {
  16088. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16089. super();
  16090. this.isPoints = true;
  16091. this.type = 'Points';
  16092. this.geometry = geometry;
  16093. this.material = material;
  16094. this.updateMorphTargets();
  16095. }
  16096. copy( source, recursive ) {
  16097. super.copy( source, recursive );
  16098. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  16099. this.geometry = source.geometry;
  16100. return this;
  16101. }
  16102. raycast( raycaster, intersects ) {
  16103. const geometry = this.geometry;
  16104. const matrixWorld = this.matrixWorld;
  16105. const threshold = raycaster.params.Points.threshold;
  16106. const drawRange = geometry.drawRange;
  16107. // Checking boundingSphere distance to ray
  16108. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16109. _sphere.copy( geometry.boundingSphere );
  16110. _sphere.applyMatrix4( matrixWorld );
  16111. _sphere.radius += threshold;
  16112. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  16113. //
  16114. _inverseMatrix.copy( matrixWorld ).invert();
  16115. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  16116. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16117. const localThresholdSq = localThreshold * localThreshold;
  16118. const index = geometry.index;
  16119. const attributes = geometry.attributes;
  16120. const positionAttribute = attributes.position;
  16121. if ( index !== null ) {
  16122. const start = Math.max( 0, drawRange.start );
  16123. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  16124. for ( let i = start, il = end; i < il; i ++ ) {
  16125. const a = index.getX( i );
  16126. _position$2.fromBufferAttribute( positionAttribute, a );
  16127. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16128. }
  16129. } else {
  16130. const start = Math.max( 0, drawRange.start );
  16131. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16132. for ( let i = start, l = end; i < l; i ++ ) {
  16133. _position$2.fromBufferAttribute( positionAttribute, i );
  16134. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16135. }
  16136. }
  16137. }
  16138. updateMorphTargets() {
  16139. const geometry = this.geometry;
  16140. const morphAttributes = geometry.morphAttributes;
  16141. const keys = Object.keys( morphAttributes );
  16142. if ( keys.length > 0 ) {
  16143. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16144. if ( morphAttribute !== undefined ) {
  16145. this.morphTargetInfluences = [];
  16146. this.morphTargetDictionary = {};
  16147. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16148. const name = morphAttribute[ m ].name || String( m );
  16149. this.morphTargetInfluences.push( 0 );
  16150. this.morphTargetDictionary[ name ] = m;
  16151. }
  16152. }
  16153. }
  16154. }
  16155. }
  16156. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16157. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  16158. if ( rayPointDistanceSq < localThresholdSq ) {
  16159. const intersectPoint = new Vector3();
  16160. _ray.closestPointToPoint( point, intersectPoint );
  16161. intersectPoint.applyMatrix4( matrixWorld );
  16162. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16163. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16164. intersects.push( {
  16165. distance: distance,
  16166. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16167. point: intersectPoint,
  16168. index: index,
  16169. face: null,
  16170. faceIndex: null,
  16171. barycoord: null,
  16172. object: object
  16173. } );
  16174. }
  16175. }
  16176. class VideoTexture extends Texture {
  16177. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16178. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16179. this.isVideoTexture = true;
  16180. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16181. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16182. this.generateMipmaps = false;
  16183. const scope = this;
  16184. function updateVideo() {
  16185. scope.needsUpdate = true;
  16186. video.requestVideoFrameCallback( updateVideo );
  16187. }
  16188. if ( 'requestVideoFrameCallback' in video ) {
  16189. video.requestVideoFrameCallback( updateVideo );
  16190. }
  16191. }
  16192. clone() {
  16193. return new this.constructor( this.image ).copy( this );
  16194. }
  16195. update() {
  16196. const video = this.image;
  16197. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16198. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16199. this.needsUpdate = true;
  16200. }
  16201. }
  16202. }
  16203. class VideoFrameTexture extends VideoTexture {
  16204. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16205. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16206. this.isVideoFrameTexture = true;
  16207. }
  16208. update() {
  16209. // overwrites `VideoTexture.update()` with an empty method since
  16210. // this type of texture is updated via `setFrame()`.
  16211. }
  16212. clone() {
  16213. return new this.constructor().copy( this ); // restoring Texture.clone()
  16214. }
  16215. setFrame( frame ) {
  16216. this.image = frame;
  16217. this.needsUpdate = true;
  16218. }
  16219. }
  16220. class FramebufferTexture extends Texture {
  16221. constructor( width, height ) {
  16222. super( { width, height } );
  16223. this.isFramebufferTexture = true;
  16224. this.magFilter = NearestFilter;
  16225. this.minFilter = NearestFilter;
  16226. this.generateMipmaps = false;
  16227. this.needsUpdate = true;
  16228. }
  16229. }
  16230. class CompressedTexture extends Texture {
  16231. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  16232. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16233. this.isCompressedTexture = true;
  16234. this.image = { width: width, height: height };
  16235. this.mipmaps = mipmaps;
  16236. // no flipping for cube textures
  16237. // (also flipping doesn't work for compressed textures )
  16238. this.flipY = false;
  16239. // can't generate mipmaps for compressed textures
  16240. // mips must be embedded in DDS files
  16241. this.generateMipmaps = false;
  16242. }
  16243. }
  16244. class CompressedArrayTexture extends CompressedTexture {
  16245. constructor( mipmaps, width, height, depth, format, type ) {
  16246. super( mipmaps, width, height, format, type );
  16247. this.isCompressedArrayTexture = true;
  16248. this.image.depth = depth;
  16249. this.wrapR = ClampToEdgeWrapping;
  16250. this.layerUpdates = new Set();
  16251. }
  16252. addLayerUpdate( layerIndex ) {
  16253. this.layerUpdates.add( layerIndex );
  16254. }
  16255. clearLayerUpdates() {
  16256. this.layerUpdates.clear();
  16257. }
  16258. }
  16259. class CompressedCubeTexture extends CompressedTexture {
  16260. constructor( images, format, type ) {
  16261. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  16262. this.isCompressedCubeTexture = true;
  16263. this.isCubeTexture = true;
  16264. this.image = images;
  16265. }
  16266. }
  16267. class CanvasTexture extends Texture {
  16268. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16269. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16270. this.isCanvasTexture = true;
  16271. this.needsUpdate = true;
  16272. }
  16273. }
  16274. class DepthTexture extends Texture {
  16275. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  16276. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16277. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16278. }
  16279. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  16280. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  16281. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16282. this.isDepthTexture = true;
  16283. this.image = { width: width, height: height };
  16284. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16285. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16286. this.flipY = false;
  16287. this.generateMipmaps = false;
  16288. this.compareFunction = null;
  16289. }
  16290. copy( source ) {
  16291. super.copy( source );
  16292. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  16293. this.compareFunction = source.compareFunction;
  16294. return this;
  16295. }
  16296. toJSON( meta ) {
  16297. const data = super.toJSON( meta );
  16298. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  16299. return data;
  16300. }
  16301. }
  16302. /**
  16303. * An abstract base class for creating an analytic curve object that contains methods
  16304. * for interpolation.
  16305. *
  16306. * @abstract
  16307. */
  16308. class Curve {
  16309. /**
  16310. * Constructs a new curve.
  16311. */
  16312. constructor() {
  16313. /**
  16314. * The type property is used for detecting the object type
  16315. * in context of serialization/deserialization.
  16316. *
  16317. * @type {string}
  16318. * @readonly
  16319. */
  16320. this.type = 'Curve';
  16321. /**
  16322. * This value determines the amount of divisions when calculating the
  16323. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  16324. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  16325. * recommended to increase the value of this property if the curve is very large.
  16326. *
  16327. * @type {number}
  16328. * @default 200
  16329. */
  16330. this.arcLengthDivisions = 200;
  16331. /**
  16332. * Must be set to `true` if the curve parameters have changed.
  16333. *
  16334. * @type {boolean}
  16335. * @default false
  16336. */
  16337. this.needsUpdate = false;
  16338. /**
  16339. * An internal cache that holds precomputed curve length values.
  16340. *
  16341. * @private
  16342. * @type {?Array<number>}
  16343. * @default null
  16344. */
  16345. this.cacheArcLengths = null;
  16346. }
  16347. /**
  16348. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  16349. * for the given interpolation factor.
  16350. *
  16351. * @abstract
  16352. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16353. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16354. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  16355. */
  16356. getPoint( /* t, optionalTarget */ ) {
  16357. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  16358. }
  16359. /**
  16360. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  16361. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  16362. * of the curve which equidistant samples.
  16363. *
  16364. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16365. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16366. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  16367. */
  16368. getPointAt( u, optionalTarget ) {
  16369. const t = this.getUtoTmapping( u );
  16370. return this.getPoint( t, optionalTarget );
  16371. }
  16372. /**
  16373. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  16374. * the curve shape.
  16375. *
  16376. * @param {number} [divisions=5] - The number of divisions.
  16377. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  16378. */
  16379. getPoints( divisions = 5 ) {
  16380. const points = [];
  16381. for ( let d = 0; d <= divisions; d ++ ) {
  16382. points.push( this.getPoint( d / divisions ) );
  16383. }
  16384. return points;
  16385. }
  16386. // Get sequence of points using getPointAt( u )
  16387. /**
  16388. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  16389. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  16390. * curve.
  16391. *
  16392. * @param {number} [divisions=5] - The number of divisions.
  16393. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  16394. */
  16395. getSpacedPoints( divisions = 5 ) {
  16396. const points = [];
  16397. for ( let d = 0; d <= divisions; d ++ ) {
  16398. points.push( this.getPointAt( d / divisions ) );
  16399. }
  16400. return points;
  16401. }
  16402. /**
  16403. * Returns the total arc length of the curve.
  16404. *
  16405. * @return {number} The length of the curve.
  16406. */
  16407. getLength() {
  16408. const lengths = this.getLengths();
  16409. return lengths[ lengths.length - 1 ];
  16410. }
  16411. /**
  16412. * Returns an array of cumulative segment lengths of the curve.
  16413. *
  16414. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  16415. * @return {Array<number>} An array holding the cumulative segment lengths.
  16416. */
  16417. getLengths( divisions = this.arcLengthDivisions ) {
  16418. if ( this.cacheArcLengths &&
  16419. ( this.cacheArcLengths.length === divisions + 1 ) &&
  16420. ! this.needsUpdate ) {
  16421. return this.cacheArcLengths;
  16422. }
  16423. this.needsUpdate = false;
  16424. const cache = [];
  16425. let current, last = this.getPoint( 0 );
  16426. let sum = 0;
  16427. cache.push( 0 );
  16428. for ( let p = 1; p <= divisions; p ++ ) {
  16429. current = this.getPoint( p / divisions );
  16430. sum += current.distanceTo( last );
  16431. cache.push( sum );
  16432. last = current;
  16433. }
  16434. this.cacheArcLengths = cache;
  16435. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  16436. }
  16437. /**
  16438. * Update the cumulative segment distance cache. The method must be called
  16439. * every time curve parameters are changed. If an updated curve is part of a
  16440. * composed curve like {@link CurvePath}, this method must be called on the
  16441. * composed curve, too.
  16442. */
  16443. updateArcLengths() {
  16444. this.needsUpdate = true;
  16445. this.getLengths();
  16446. }
  16447. /**
  16448. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  16449. * interpolation factor in the same range that can be ued to sample equidistant points
  16450. * from a curve.
  16451. *
  16452. * @param {number} u - The interpolation factor.
  16453. * @param {?number} distance - An optional distance on the curve.
  16454. * @return {number} The updated interpolation factor.
  16455. */
  16456. getUtoTmapping( u, distance = null ) {
  16457. const arcLengths = this.getLengths();
  16458. let i = 0;
  16459. const il = arcLengths.length;
  16460. let targetArcLength; // The targeted u distance value to get
  16461. if ( distance ) {
  16462. targetArcLength = distance;
  16463. } else {
  16464. targetArcLength = u * arcLengths[ il - 1 ];
  16465. }
  16466. // binary search for the index with largest value smaller than target u distance
  16467. let low = 0, high = il - 1, comparison;
  16468. while ( low <= high ) {
  16469. 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
  16470. comparison = arcLengths[ i ] - targetArcLength;
  16471. if ( comparison < 0 ) {
  16472. low = i + 1;
  16473. } else if ( comparison > 0 ) {
  16474. high = i - 1;
  16475. } else {
  16476. high = i;
  16477. break;
  16478. // DONE
  16479. }
  16480. }
  16481. i = high;
  16482. if ( arcLengths[ i ] === targetArcLength ) {
  16483. return i / ( il - 1 );
  16484. }
  16485. // we could get finer grain at lengths, or use simple interpolation between two points
  16486. const lengthBefore = arcLengths[ i ];
  16487. const lengthAfter = arcLengths[ i + 1 ];
  16488. const segmentLength = lengthAfter - lengthBefore;
  16489. // determine where we are between the 'before' and 'after' points
  16490. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16491. // add that fractional amount to t
  16492. const t = ( i + segmentFraction ) / ( il - 1 );
  16493. return t;
  16494. }
  16495. /**
  16496. * Returns a unit vector tangent for the given interpolation factor.
  16497. * If the derived curve does not implement its tangent derivation,
  16498. * two points a small delta apart will be used to find its gradient
  16499. * which seems to give a reasonable approximation.
  16500. *
  16501. * @param {number} t - The interpolation factor.
  16502. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16503. * @return {(Vector2|Vector3)} The tagent vector.
  16504. */
  16505. getTangent( t, optionalTarget ) {
  16506. const delta = 0.0001;
  16507. let t1 = t - delta;
  16508. let t2 = t + delta;
  16509. // Capping in case of danger
  16510. if ( t1 < 0 ) t1 = 0;
  16511. if ( t2 > 1 ) t2 = 1;
  16512. const pt1 = this.getPoint( t1 );
  16513. const pt2 = this.getPoint( t2 );
  16514. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  16515. tangent.copy( pt2 ).sub( pt1 ).normalize();
  16516. return tangent;
  16517. }
  16518. /**
  16519. * Same as {@link Curve#getTangent} but with equidistant samples.
  16520. *
  16521. * @param {number} u - The interpolation factor.
  16522. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16523. * @return {(Vector2|Vector3)} The tagent vector.
  16524. * @see {@link Curve#getPointAt}
  16525. */
  16526. getTangentAt( u, optionalTarget ) {
  16527. const t = this.getUtoTmapping( u );
  16528. return this.getTangent( t, optionalTarget );
  16529. }
  16530. /**
  16531. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  16532. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  16533. *
  16534. * @param {number} segments - The number of segments.
  16535. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  16536. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  16537. */
  16538. computeFrenetFrames( segments, closed = false ) {
  16539. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  16540. const normal = new Vector3();
  16541. const tangents = [];
  16542. const normals = [];
  16543. const binormals = [];
  16544. const vec = new Vector3();
  16545. const mat = new Matrix4();
  16546. // compute the tangent vectors for each segment on the curve
  16547. for ( let i = 0; i <= segments; i ++ ) {
  16548. const u = i / segments;
  16549. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  16550. }
  16551. // select an initial normal vector perpendicular to the first tangent vector,
  16552. // and in the direction of the minimum tangent xyz component
  16553. normals[ 0 ] = new Vector3();
  16554. binormals[ 0 ] = new Vector3();
  16555. let min = Number.MAX_VALUE;
  16556. const tx = Math.abs( tangents[ 0 ].x );
  16557. const ty = Math.abs( tangents[ 0 ].y );
  16558. const tz = Math.abs( tangents[ 0 ].z );
  16559. if ( tx <= min ) {
  16560. min = tx;
  16561. normal.set( 1, 0, 0 );
  16562. }
  16563. if ( ty <= min ) {
  16564. min = ty;
  16565. normal.set( 0, 1, 0 );
  16566. }
  16567. if ( tz <= min ) {
  16568. normal.set( 0, 0, 1 );
  16569. }
  16570. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  16571. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  16572. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  16573. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  16574. for ( let i = 1; i <= segments; i ++ ) {
  16575. normals[ i ] = normals[ i - 1 ].clone();
  16576. binormals[ i ] = binormals[ i - 1 ].clone();
  16577. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  16578. if ( vec.length() > Number.EPSILON ) {
  16579. vec.normalize();
  16580. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  16581. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  16582. }
  16583. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  16584. }
  16585. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  16586. if ( closed === true ) {
  16587. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  16588. theta /= segments;
  16589. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  16590. theta = - theta;
  16591. }
  16592. for ( let i = 1; i <= segments; i ++ ) {
  16593. // twist a little...
  16594. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  16595. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  16596. }
  16597. }
  16598. return {
  16599. tangents: tangents,
  16600. normals: normals,
  16601. binormals: binormals
  16602. };
  16603. }
  16604. /**
  16605. * Returns a new curve with copied values from this instance.
  16606. *
  16607. * @return {Curve} A clone of this instance.
  16608. */
  16609. clone() {
  16610. return new this.constructor().copy( this );
  16611. }
  16612. /**
  16613. * Copies the values of the given curve to this instance.
  16614. *
  16615. * @param {Curve} source - The curve to copy.
  16616. * @return {Curve} A reference to this curve.
  16617. */
  16618. copy( source ) {
  16619. this.arcLengthDivisions = source.arcLengthDivisions;
  16620. return this;
  16621. }
  16622. /**
  16623. * Serializes the curve into JSON.
  16624. *
  16625. * @return {Object} A JSON object representing the serialized curve.
  16626. * @see {@link ObjectLoader#parse}
  16627. */
  16628. toJSON() {
  16629. const data = {
  16630. metadata: {
  16631. version: 4.6,
  16632. type: 'Curve',
  16633. generator: 'Curve.toJSON'
  16634. }
  16635. };
  16636. data.arcLengthDivisions = this.arcLengthDivisions;
  16637. data.type = this.type;
  16638. return data;
  16639. }
  16640. /**
  16641. * Deserializes the curve from the given JSON.
  16642. *
  16643. * @param {Object} json - The JSON holding the serialized curve.
  16644. * @return {Curve} A reference to this curve.
  16645. */
  16646. fromJSON( json ) {
  16647. this.arcLengthDivisions = json.arcLengthDivisions;
  16648. return this;
  16649. }
  16650. }
  16651. /**
  16652. * A curve representing an ellipse.
  16653. *
  16654. * ```js
  16655. * const curve = new THREE.EllipseCurve(
  16656. * 0, 0,
  16657. * 10, 10,
  16658. * 0, 2 * Math.PI,
  16659. * false,
  16660. * 0
  16661. * );
  16662. *
  16663. * const points = curve.getPoints( 50 );
  16664. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  16665. *
  16666. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  16667. *
  16668. * // Create the final object to add to the scene
  16669. * const ellipse = new THREE.Line( geometry, material );
  16670. * ```
  16671. *
  16672. * @augments Curve
  16673. */
  16674. class EllipseCurve extends Curve {
  16675. /**
  16676. * Constructs a new ellipse curve.
  16677. *
  16678. * @param {number} [aX=0] - The X center of the ellipse.
  16679. * @param {number} [aY=0] - The Y center of the ellipse.
  16680. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  16681. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  16682. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  16683. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  16684. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  16685. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  16686. */
  16687. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  16688. super();
  16689. /**
  16690. * This flag can be used for type testing.
  16691. *
  16692. * @type {boolean}
  16693. * @readonly
  16694. * @default true
  16695. */
  16696. this.isEllipseCurve = true;
  16697. this.type = 'EllipseCurve';
  16698. /**
  16699. * The X center of the ellipse.
  16700. *
  16701. * @type {number}
  16702. * @default 0
  16703. */
  16704. this.aX = aX;
  16705. /**
  16706. * The Y center of the ellipse.
  16707. *
  16708. * @type {number}
  16709. * @default 0
  16710. */
  16711. this.aY = aY;
  16712. /**
  16713. * The radius of the ellipse in the x direction.
  16714. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  16715. *
  16716. * @type {number}
  16717. * @default 1
  16718. */
  16719. this.xRadius = xRadius;
  16720. /**
  16721. * The radius of the ellipse in the y direction.
  16722. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  16723. *
  16724. * @type {number}
  16725. * @default 1
  16726. */
  16727. this.yRadius = yRadius;
  16728. /**
  16729. * The start angle of the curve in radians starting from the positive X axis.
  16730. *
  16731. * @type {number}
  16732. * @default 0
  16733. */
  16734. this.aStartAngle = aStartAngle;
  16735. /**
  16736. * The end angle of the curve in radians starting from the positive X axis.
  16737. *
  16738. * @type {number}
  16739. * @default Math.PI*2
  16740. */
  16741. this.aEndAngle = aEndAngle;
  16742. /**
  16743. * Whether the ellipse is drawn clockwise or not.
  16744. *
  16745. * @type {boolean}
  16746. * @default false
  16747. */
  16748. this.aClockwise = aClockwise;
  16749. /**
  16750. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  16751. *
  16752. * @type {number}
  16753. * @default 0
  16754. */
  16755. this.aRotation = aRotation;
  16756. }
  16757. /**
  16758. * Returns a point on the curve.
  16759. *
  16760. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16761. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  16762. * @return {Vector2} The position on the curve.
  16763. */
  16764. getPoint( t, optionalTarget = new Vector2() ) {
  16765. const point = optionalTarget;
  16766. const twoPi = Math.PI * 2;
  16767. let deltaAngle = this.aEndAngle - this.aStartAngle;
  16768. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  16769. // ensures that deltaAngle is 0 .. 2 PI
  16770. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  16771. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  16772. if ( deltaAngle < Number.EPSILON ) {
  16773. if ( samePoints ) {
  16774. deltaAngle = 0;
  16775. } else {
  16776. deltaAngle = twoPi;
  16777. }
  16778. }
  16779. if ( this.aClockwise === true && ! samePoints ) {
  16780. if ( deltaAngle === twoPi ) {
  16781. deltaAngle = - twoPi;
  16782. } else {
  16783. deltaAngle = deltaAngle - twoPi;
  16784. }
  16785. }
  16786. const angle = this.aStartAngle + t * deltaAngle;
  16787. let x = this.aX + this.xRadius * Math.cos( angle );
  16788. let y = this.aY + this.yRadius * Math.sin( angle );
  16789. if ( this.aRotation !== 0 ) {
  16790. const cos = Math.cos( this.aRotation );
  16791. const sin = Math.sin( this.aRotation );
  16792. const tx = x - this.aX;
  16793. const ty = y - this.aY;
  16794. // Rotate the point about the center of the ellipse.
  16795. x = tx * cos - ty * sin + this.aX;
  16796. y = tx * sin + ty * cos + this.aY;
  16797. }
  16798. return point.set( x, y );
  16799. }
  16800. copy( source ) {
  16801. super.copy( source );
  16802. this.aX = source.aX;
  16803. this.aY = source.aY;
  16804. this.xRadius = source.xRadius;
  16805. this.yRadius = source.yRadius;
  16806. this.aStartAngle = source.aStartAngle;
  16807. this.aEndAngle = source.aEndAngle;
  16808. this.aClockwise = source.aClockwise;
  16809. this.aRotation = source.aRotation;
  16810. return this;
  16811. }
  16812. toJSON() {
  16813. const data = super.toJSON();
  16814. data.aX = this.aX;
  16815. data.aY = this.aY;
  16816. data.xRadius = this.xRadius;
  16817. data.yRadius = this.yRadius;
  16818. data.aStartAngle = this.aStartAngle;
  16819. data.aEndAngle = this.aEndAngle;
  16820. data.aClockwise = this.aClockwise;
  16821. data.aRotation = this.aRotation;
  16822. return data;
  16823. }
  16824. fromJSON( json ) {
  16825. super.fromJSON( json );
  16826. this.aX = json.aX;
  16827. this.aY = json.aY;
  16828. this.xRadius = json.xRadius;
  16829. this.yRadius = json.yRadius;
  16830. this.aStartAngle = json.aStartAngle;
  16831. this.aEndAngle = json.aEndAngle;
  16832. this.aClockwise = json.aClockwise;
  16833. this.aRotation = json.aRotation;
  16834. return this;
  16835. }
  16836. }
  16837. /**
  16838. * A curve representing an arc.
  16839. *
  16840. * @augments EllipseCurve
  16841. */
  16842. class ArcCurve extends EllipseCurve {
  16843. /**
  16844. * Constructs a new arc curve.
  16845. *
  16846. * @param {number} [aX=0] - The X center of the ellipse.
  16847. * @param {number} [aY=0] - The Y center of the ellipse.
  16848. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  16849. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  16850. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  16851. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  16852. */
  16853. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16854. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16855. /**
  16856. * This flag can be used for type testing.
  16857. *
  16858. * @type {boolean}
  16859. * @readonly
  16860. * @default true
  16861. */
  16862. this.isArcCurve = true;
  16863. this.type = 'ArcCurve';
  16864. }
  16865. }
  16866. function CubicPoly() {
  16867. /**
  16868. * Centripetal CatmullRom Curve - which is useful for avoiding
  16869. * cusps and self-intersections in non-uniform catmull rom curves.
  16870. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  16871. *
  16872. * curve.type accepts centripetal(default), chordal and catmullrom
  16873. * curve.tension is used for catmullrom which defaults to 0.5
  16874. */
  16875. /*
  16876. Based on an optimized c++ solution in
  16877. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  16878. - http://ideone.com/NoEbVM
  16879. This CubicPoly class could be used for reusing some variables and calculations,
  16880. but for three.js curve use, it could be possible inlined and flatten into a single function call
  16881. which can be placed in CurveUtils.
  16882. */
  16883. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  16884. /*
  16885. * Compute coefficients for a cubic polynomial
  16886. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  16887. * such that
  16888. * p(0) = x0, p(1) = x1
  16889. * and
  16890. * p'(0) = t0, p'(1) = t1.
  16891. */
  16892. function init( x0, x1, t0, t1 ) {
  16893. c0 = x0;
  16894. c1 = t0;
  16895. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  16896. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  16897. }
  16898. return {
  16899. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  16900. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  16901. },
  16902. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  16903. // compute tangents when parameterized in [t1,t2]
  16904. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  16905. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  16906. // rescale tangents for parametrization in [0,1]
  16907. t1 *= dt1;
  16908. t2 *= dt1;
  16909. init( x1, x2, t1, t2 );
  16910. },
  16911. calc: function ( t ) {
  16912. const t2 = t * t;
  16913. const t3 = t2 * t;
  16914. return c0 + c1 * t + c2 * t2 + c3 * t3;
  16915. }
  16916. };
  16917. }
  16918. //
  16919. const tmp = /*@__PURE__*/ new Vector3();
  16920. const px = /*@__PURE__*/ new CubicPoly();
  16921. const py = /*@__PURE__*/ new CubicPoly();
  16922. const pz = /*@__PURE__*/ new CubicPoly();
  16923. /**
  16924. * A curve representing a Catmull-Rom spline.
  16925. *
  16926. * ```js
  16927. * //Create a closed wavey loop
  16928. * const curve = new THREE.CatmullRomCurve3( [
  16929. * new THREE.Vector3( -10, 0, 10 ),
  16930. * new THREE.Vector3( -5, 5, 5 ),
  16931. * new THREE.Vector3( 0, 0, 0 ),
  16932. * new THREE.Vector3( 5, -5, 5 ),
  16933. * new THREE.Vector3( 10, 0, 10 )
  16934. * ] );
  16935. *
  16936. * const points = curve.getPoints( 50 );
  16937. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  16938. *
  16939. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  16940. *
  16941. * // Create the final object to add to the scene
  16942. * const curveObject = new THREE.Line( geometry, material );
  16943. * ```
  16944. *
  16945. * @augments Curve
  16946. */
  16947. class CatmullRomCurve3 extends Curve {
  16948. /**
  16949. * Constructs a new Catmull-Rom curve.
  16950. *
  16951. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  16952. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  16953. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  16954. * @param {number} [tension=0.5] - Tension of the curve.
  16955. */
  16956. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  16957. super();
  16958. /**
  16959. * This flag can be used for type testing.
  16960. *
  16961. * @type {boolean}
  16962. * @readonly
  16963. * @default true
  16964. */
  16965. this.isCatmullRomCurve3 = true;
  16966. this.type = 'CatmullRomCurve3';
  16967. /**
  16968. * An array of 3D points defining the curve.
  16969. *
  16970. * @type {Array<Vector3>}
  16971. */
  16972. this.points = points;
  16973. /**
  16974. * Whether the curve is closed or not.
  16975. *
  16976. * @type {boolean}
  16977. * @default false
  16978. */
  16979. this.closed = closed;
  16980. /**
  16981. * The curve type.
  16982. *
  16983. * @type {('centripetal'|'chordal'|'catmullrom')}
  16984. * @default 'centripetal'
  16985. */
  16986. this.curveType = curveType;
  16987. /**
  16988. * Tension of the curve.
  16989. *
  16990. * @type {number}
  16991. * @default 0.5
  16992. */
  16993. this.tension = tension;
  16994. }
  16995. /**
  16996. * Returns a point on the curve.
  16997. *
  16998. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16999. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17000. * @return {Vector3} The position on the curve.
  17001. */
  17002. getPoint( t, optionalTarget = new Vector3() ) {
  17003. const point = optionalTarget;
  17004. const points = this.points;
  17005. const l = points.length;
  17006. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  17007. let intPoint = Math.floor( p );
  17008. let weight = p - intPoint;
  17009. if ( this.closed ) {
  17010. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  17011. } else if ( weight === 0 && intPoint === l - 1 ) {
  17012. intPoint = l - 2;
  17013. weight = 1;
  17014. }
  17015. let p0, p3; // 4 points (p1 & p2 defined below)
  17016. if ( this.closed || intPoint > 0 ) {
  17017. p0 = points[ ( intPoint - 1 ) % l ];
  17018. } else {
  17019. // extrapolate first point
  17020. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  17021. p0 = tmp;
  17022. }
  17023. const p1 = points[ intPoint % l ];
  17024. const p2 = points[ ( intPoint + 1 ) % l ];
  17025. if ( this.closed || intPoint + 2 < l ) {
  17026. p3 = points[ ( intPoint + 2 ) % l ];
  17027. } else {
  17028. // extrapolate last point
  17029. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  17030. p3 = tmp;
  17031. }
  17032. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  17033. // init Centripetal / Chordal Catmull-Rom
  17034. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  17035. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  17036. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  17037. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  17038. // safety check for repeated points
  17039. if ( dt1 < 1e-4 ) dt1 = 1.0;
  17040. if ( dt0 < 1e-4 ) dt0 = dt1;
  17041. if ( dt2 < 1e-4 ) dt2 = dt1;
  17042. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  17043. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  17044. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  17045. } else if ( this.curveType === 'catmullrom' ) {
  17046. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  17047. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  17048. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  17049. }
  17050. point.set(
  17051. px.calc( weight ),
  17052. py.calc( weight ),
  17053. pz.calc( weight )
  17054. );
  17055. return point;
  17056. }
  17057. copy( source ) {
  17058. super.copy( source );
  17059. this.points = [];
  17060. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  17061. const point = source.points[ i ];
  17062. this.points.push( point.clone() );
  17063. }
  17064. this.closed = source.closed;
  17065. this.curveType = source.curveType;
  17066. this.tension = source.tension;
  17067. return this;
  17068. }
  17069. toJSON() {
  17070. const data = super.toJSON();
  17071. data.points = [];
  17072. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  17073. const point = this.points[ i ];
  17074. data.points.push( point.toArray() );
  17075. }
  17076. data.closed = this.closed;
  17077. data.curveType = this.curveType;
  17078. data.tension = this.tension;
  17079. return data;
  17080. }
  17081. fromJSON( json ) {
  17082. super.fromJSON( json );
  17083. this.points = [];
  17084. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  17085. const point = json.points[ i ];
  17086. this.points.push( new Vector3().fromArray( point ) );
  17087. }
  17088. this.closed = json.closed;
  17089. this.curveType = json.curveType;
  17090. this.tension = json.tension;
  17091. return this;
  17092. }
  17093. }
  17094. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17095. /**
  17096. * Computes a point on a Camtull-Rom spline.
  17097. *
  17098. * @param {number} t - The interpolation factor.
  17099. * @param {number} p0 - The first control point.
  17100. * @param {number} p1 - The second control point.
  17101. * @param {number} p2 - The third control point.
  17102. * @param {number} p3 - The fourth control point.
  17103. * @return {number} The calculated point on a Camtull-Rom spline.
  17104. */
  17105. function CatmullRom( t, p0, p1, p2, p3 ) {
  17106. const v0 = ( p2 - p0 ) * 0.5;
  17107. const v1 = ( p3 - p1 ) * 0.5;
  17108. const t2 = t * t;
  17109. const t3 = t * t2;
  17110. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17111. }
  17112. //
  17113. function QuadraticBezierP0( t, p ) {
  17114. const k = 1 - t;
  17115. return k * k * p;
  17116. }
  17117. function QuadraticBezierP1( t, p ) {
  17118. return 2 * ( 1 - t ) * t * p;
  17119. }
  17120. function QuadraticBezierP2( t, p ) {
  17121. return t * t * p;
  17122. }
  17123. /**
  17124. * Computes a point on a Quadratic Bezier curve.
  17125. *
  17126. * @param {number} t - The interpolation factor.
  17127. * @param {number} p0 - The first control point.
  17128. * @param {number} p1 - The second control point.
  17129. * @param {number} p2 - The third control point.
  17130. * @return {number} The calculated point on a Quadratic Bezier curve.
  17131. */
  17132. function QuadraticBezier( t, p0, p1, p2 ) {
  17133. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  17134. QuadraticBezierP2( t, p2 );
  17135. }
  17136. //
  17137. function CubicBezierP0( t, p ) {
  17138. const k = 1 - t;
  17139. return k * k * k * p;
  17140. }
  17141. function CubicBezierP1( t, p ) {
  17142. const k = 1 - t;
  17143. return 3 * k * k * t * p;
  17144. }
  17145. function CubicBezierP2( t, p ) {
  17146. return 3 * ( 1 - t ) * t * t * p;
  17147. }
  17148. function CubicBezierP3( t, p ) {
  17149. return t * t * t * p;
  17150. }
  17151. /**
  17152. * Computes a point on a Cubic Bezier curve.
  17153. *
  17154. * @param {number} t - The interpolation factor.
  17155. * @param {number} p0 - The first control point.
  17156. * @param {number} p1 - The second control point.
  17157. * @param {number} p2 - The third control point.
  17158. * @param {number} p3 - The fourth control point.
  17159. * @return {number} The calculated point on a Cubic Bezier curve.
  17160. */
  17161. function CubicBezier( t, p0, p1, p2, p3 ) {
  17162. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  17163. CubicBezierP3( t, p3 );
  17164. }
  17165. /**
  17166. * A curve representing a 2D Cubic Bezier curve.
  17167. *
  17168. * ```js
  17169. * const curve = new THREE.CubicBezierCurve(
  17170. * new THREE.Vector2( - 0, 0 ),
  17171. * new THREE.Vector2( - 5, 15 ),
  17172. * new THREE.Vector2( 20, 15 ),
  17173. * new THREE.Vector2( 10, 0 )
  17174. * );
  17175. *
  17176. * const points = curve.getPoints( 50 );
  17177. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17178. *
  17179. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17180. *
  17181. * // Create the final object to add to the scene
  17182. * const curveObject = new THREE.Line( geometry, material );
  17183. * ```
  17184. *
  17185. * @augments Curve
  17186. */
  17187. class CubicBezierCurve extends Curve {
  17188. /**
  17189. * Constructs a new Cubic Bezier curve.
  17190. *
  17191. * @param {Vector2} [v0] - The start point.
  17192. * @param {Vector2} [v1] - The first control point.
  17193. * @param {Vector2} [v2] - The second control point.
  17194. * @param {Vector2} [v3] - The end point.
  17195. */
  17196. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  17197. super();
  17198. /**
  17199. * This flag can be used for type testing.
  17200. *
  17201. * @type {boolean}
  17202. * @readonly
  17203. * @default true
  17204. */
  17205. this.isCubicBezierCurve = true;
  17206. this.type = 'CubicBezierCurve';
  17207. /**
  17208. * The start point.
  17209. *
  17210. * @type {Vector2}
  17211. */
  17212. this.v0 = v0;
  17213. /**
  17214. * The first control point.
  17215. *
  17216. * @type {Vector2}
  17217. */
  17218. this.v1 = v1;
  17219. /**
  17220. * The second control point.
  17221. *
  17222. * @type {Vector2}
  17223. */
  17224. this.v2 = v2;
  17225. /**
  17226. * The end point.
  17227. *
  17228. * @type {Vector2}
  17229. */
  17230. this.v3 = v3;
  17231. }
  17232. /**
  17233. * Returns a point on the curve.
  17234. *
  17235. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17236. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17237. * @return {Vector2} The position on the curve.
  17238. */
  17239. getPoint( t, optionalTarget = new Vector2() ) {
  17240. const point = optionalTarget;
  17241. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  17242. point.set(
  17243. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  17244. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  17245. );
  17246. return point;
  17247. }
  17248. copy( source ) {
  17249. super.copy( source );
  17250. this.v0.copy( source.v0 );
  17251. this.v1.copy( source.v1 );
  17252. this.v2.copy( source.v2 );
  17253. this.v3.copy( source.v3 );
  17254. return this;
  17255. }
  17256. toJSON() {
  17257. const data = super.toJSON();
  17258. data.v0 = this.v0.toArray();
  17259. data.v1 = this.v1.toArray();
  17260. data.v2 = this.v2.toArray();
  17261. data.v3 = this.v3.toArray();
  17262. return data;
  17263. }
  17264. fromJSON( json ) {
  17265. super.fromJSON( json );
  17266. this.v0.fromArray( json.v0 );
  17267. this.v1.fromArray( json.v1 );
  17268. this.v2.fromArray( json.v2 );
  17269. this.v3.fromArray( json.v3 );
  17270. return this;
  17271. }
  17272. }
  17273. /**
  17274. * A curve representing a 3D Cubic Bezier curve.
  17275. *
  17276. * @augments Curve
  17277. */
  17278. class CubicBezierCurve3 extends Curve {
  17279. /**
  17280. * Constructs a new Cubic Bezier curve.
  17281. *
  17282. * @param {Vector3} [v0] - The start point.
  17283. * @param {Vector3} [v1] - The first control point.
  17284. * @param {Vector3} [v2] - The second control point.
  17285. * @param {Vector3} [v3] - The end point.
  17286. */
  17287. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  17288. super();
  17289. /**
  17290. * This flag can be used for type testing.
  17291. *
  17292. * @type {boolean}
  17293. * @readonly
  17294. * @default true
  17295. */
  17296. this.isCubicBezierCurve3 = true;
  17297. this.type = 'CubicBezierCurve3';
  17298. /**
  17299. * The start point.
  17300. *
  17301. * @type {Vector3}
  17302. */
  17303. this.v0 = v0;
  17304. /**
  17305. * The first control point.
  17306. *
  17307. * @type {Vector3}
  17308. */
  17309. this.v1 = v1;
  17310. /**
  17311. * The second control point.
  17312. *
  17313. * @type {Vector3}
  17314. */
  17315. this.v2 = v2;
  17316. /**
  17317. * The end point.
  17318. *
  17319. * @type {Vector3}
  17320. */
  17321. this.v3 = v3;
  17322. }
  17323. /**
  17324. * Returns a point on the curve.
  17325. *
  17326. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17327. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17328. * @return {Vector3} The position on the curve.
  17329. */
  17330. getPoint( t, optionalTarget = new Vector3() ) {
  17331. const point = optionalTarget;
  17332. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  17333. point.set(
  17334. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  17335. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  17336. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  17337. );
  17338. return point;
  17339. }
  17340. copy( source ) {
  17341. super.copy( source );
  17342. this.v0.copy( source.v0 );
  17343. this.v1.copy( source.v1 );
  17344. this.v2.copy( source.v2 );
  17345. this.v3.copy( source.v3 );
  17346. return this;
  17347. }
  17348. toJSON() {
  17349. const data = super.toJSON();
  17350. data.v0 = this.v0.toArray();
  17351. data.v1 = this.v1.toArray();
  17352. data.v2 = this.v2.toArray();
  17353. data.v3 = this.v3.toArray();
  17354. return data;
  17355. }
  17356. fromJSON( json ) {
  17357. super.fromJSON( json );
  17358. this.v0.fromArray( json.v0 );
  17359. this.v1.fromArray( json.v1 );
  17360. this.v2.fromArray( json.v2 );
  17361. this.v3.fromArray( json.v3 );
  17362. return this;
  17363. }
  17364. }
  17365. /**
  17366. * A curve representing a 2D line segment.
  17367. *
  17368. * @augments Curve
  17369. */
  17370. class LineCurve extends Curve {
  17371. /**
  17372. * Constructs a new line curve.
  17373. *
  17374. * @param {Vector2} [v1] - The start point.
  17375. * @param {Vector2} [v2] - The end point.
  17376. */
  17377. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  17378. super();
  17379. /**
  17380. * This flag can be used for type testing.
  17381. *
  17382. * @type {boolean}
  17383. * @readonly
  17384. * @default true
  17385. */
  17386. this.isLineCurve = true;
  17387. this.type = 'LineCurve';
  17388. /**
  17389. * The start point.
  17390. *
  17391. * @type {Vector2}
  17392. */
  17393. this.v1 = v1;
  17394. /**
  17395. * The end point.
  17396. *
  17397. * @type {Vector2}
  17398. */
  17399. this.v2 = v2;
  17400. }
  17401. /**
  17402. * Returns a point on the line.
  17403. *
  17404. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  17405. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17406. * @return {Vector2} The position on the line.
  17407. */
  17408. getPoint( t, optionalTarget = new Vector2() ) {
  17409. const point = optionalTarget;
  17410. if ( t === 1 ) {
  17411. point.copy( this.v2 );
  17412. } else {
  17413. point.copy( this.v2 ).sub( this.v1 );
  17414. point.multiplyScalar( t ).add( this.v1 );
  17415. }
  17416. return point;
  17417. }
  17418. // Line curve is linear, so we can overwrite default getPointAt
  17419. getPointAt( u, optionalTarget ) {
  17420. return this.getPoint( u, optionalTarget );
  17421. }
  17422. getTangent( t, optionalTarget = new Vector2() ) {
  17423. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  17424. }
  17425. getTangentAt( u, optionalTarget ) {
  17426. return this.getTangent( u, optionalTarget );
  17427. }
  17428. copy( source ) {
  17429. super.copy( source );
  17430. this.v1.copy( source.v1 );
  17431. this.v2.copy( source.v2 );
  17432. return this;
  17433. }
  17434. toJSON() {
  17435. const data = super.toJSON();
  17436. data.v1 = this.v1.toArray();
  17437. data.v2 = this.v2.toArray();
  17438. return data;
  17439. }
  17440. fromJSON( json ) {
  17441. super.fromJSON( json );
  17442. this.v1.fromArray( json.v1 );
  17443. this.v2.fromArray( json.v2 );
  17444. return this;
  17445. }
  17446. }
  17447. /**
  17448. * A curve representing a 3D line segment.
  17449. *
  17450. * @augments Curve
  17451. */
  17452. class LineCurve3 extends Curve {
  17453. /**
  17454. * Constructs a new line curve.
  17455. *
  17456. * @param {Vector3} [v1] - The start point.
  17457. * @param {Vector3} [v2] - The end point.
  17458. */
  17459. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  17460. super();
  17461. /**
  17462. * This flag can be used for type testing.
  17463. *
  17464. * @type {boolean}
  17465. * @readonly
  17466. * @default true
  17467. */
  17468. this.isLineCurve3 = true;
  17469. this.type = 'LineCurve3';
  17470. /**
  17471. * The start point.
  17472. *
  17473. * @type {Vector3}
  17474. */
  17475. this.v1 = v1;
  17476. /**
  17477. * The end point.
  17478. *
  17479. * @type {Vector2}
  17480. */
  17481. this.v2 = v2;
  17482. }
  17483. /**
  17484. * Returns a point on the line.
  17485. *
  17486. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  17487. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17488. * @return {Vector3} The position on the line.
  17489. */
  17490. getPoint( t, optionalTarget = new Vector3() ) {
  17491. const point = optionalTarget;
  17492. if ( t === 1 ) {
  17493. point.copy( this.v2 );
  17494. } else {
  17495. point.copy( this.v2 ).sub( this.v1 );
  17496. point.multiplyScalar( t ).add( this.v1 );
  17497. }
  17498. return point;
  17499. }
  17500. // Line curve is linear, so we can overwrite default getPointAt
  17501. getPointAt( u, optionalTarget ) {
  17502. return this.getPoint( u, optionalTarget );
  17503. }
  17504. getTangent( t, optionalTarget = new Vector3() ) {
  17505. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  17506. }
  17507. getTangentAt( u, optionalTarget ) {
  17508. return this.getTangent( u, optionalTarget );
  17509. }
  17510. copy( source ) {
  17511. super.copy( source );
  17512. this.v1.copy( source.v1 );
  17513. this.v2.copy( source.v2 );
  17514. return this;
  17515. }
  17516. toJSON() {
  17517. const data = super.toJSON();
  17518. data.v1 = this.v1.toArray();
  17519. data.v2 = this.v2.toArray();
  17520. return data;
  17521. }
  17522. fromJSON( json ) {
  17523. super.fromJSON( json );
  17524. this.v1.fromArray( json.v1 );
  17525. this.v2.fromArray( json.v2 );
  17526. return this;
  17527. }
  17528. }
  17529. /**
  17530. * A curve representing a 2D Quadratic Bezier curve.
  17531. *
  17532. * ```js
  17533. * const curve = new THREE.QuadraticBezierCurve(
  17534. * new THREE.Vector2( - 10, 0 ),
  17535. * new THREE.Vector2( 20, 15 ),
  17536. * new THREE.Vector2( 10, 0 )
  17537. * )
  17538. *
  17539. * const points = curve.getPoints( 50 );
  17540. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17541. *
  17542. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17543. *
  17544. * // Create the final object to add to the scene
  17545. * const curveObject = new THREE.Line( geometry, material );
  17546. * ```
  17547. *
  17548. * @augments Curve
  17549. */
  17550. class QuadraticBezierCurve extends Curve {
  17551. /**
  17552. * Constructs a new Quadratic Bezier curve.
  17553. *
  17554. * @param {Vector2} [v0] - The start point.
  17555. * @param {Vector2} [v1] - The control point.
  17556. * @param {Vector2} [v2] - The end point.
  17557. */
  17558. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  17559. super();
  17560. /**
  17561. * This flag can be used for type testing.
  17562. *
  17563. * @type {boolean}
  17564. * @readonly
  17565. * @default true
  17566. */
  17567. this.isQuadraticBezierCurve = true;
  17568. this.type = 'QuadraticBezierCurve';
  17569. /**
  17570. * The start point.
  17571. *
  17572. * @type {Vector2}
  17573. */
  17574. this.v0 = v0;
  17575. /**
  17576. * The control point.
  17577. *
  17578. * @type {Vector2}
  17579. */
  17580. this.v1 = v1;
  17581. /**
  17582. * The end point.
  17583. *
  17584. * @type {Vector2}
  17585. */
  17586. this.v2 = v2;
  17587. }
  17588. /**
  17589. * Returns a point on the curve.
  17590. *
  17591. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17592. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17593. * @return {Vector2} The position on the curve.
  17594. */
  17595. getPoint( t, optionalTarget = new Vector2() ) {
  17596. const point = optionalTarget;
  17597. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  17598. point.set(
  17599. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  17600. QuadraticBezier( t, v0.y, v1.y, v2.y )
  17601. );
  17602. return point;
  17603. }
  17604. copy( source ) {
  17605. super.copy( source );
  17606. this.v0.copy( source.v0 );
  17607. this.v1.copy( source.v1 );
  17608. this.v2.copy( source.v2 );
  17609. return this;
  17610. }
  17611. toJSON() {
  17612. const data = super.toJSON();
  17613. data.v0 = this.v0.toArray();
  17614. data.v1 = this.v1.toArray();
  17615. data.v2 = this.v2.toArray();
  17616. return data;
  17617. }
  17618. fromJSON( json ) {
  17619. super.fromJSON( json );
  17620. this.v0.fromArray( json.v0 );
  17621. this.v1.fromArray( json.v1 );
  17622. this.v2.fromArray( json.v2 );
  17623. return this;
  17624. }
  17625. }
  17626. /**
  17627. * A curve representing a 3D Quadratic Bezier curve.
  17628. *
  17629. * @augments Curve
  17630. */
  17631. class QuadraticBezierCurve3 extends Curve {
  17632. /**
  17633. * Constructs a new Quadratic Bezier curve.
  17634. *
  17635. * @param {Vector3} [v0] - The start point.
  17636. * @param {Vector3} [v1] - The control point.
  17637. * @param {Vector3} [v2] - The end point.
  17638. */
  17639. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  17640. super();
  17641. /**
  17642. * This flag can be used for type testing.
  17643. *
  17644. * @type {boolean}
  17645. * @readonly
  17646. * @default true
  17647. */
  17648. this.isQuadraticBezierCurve3 = true;
  17649. this.type = 'QuadraticBezierCurve3';
  17650. /**
  17651. * The start point.
  17652. *
  17653. * @type {Vector3}
  17654. */
  17655. this.v0 = v0;
  17656. /**
  17657. * The control point.
  17658. *
  17659. * @type {Vector3}
  17660. */
  17661. this.v1 = v1;
  17662. /**
  17663. * The end point.
  17664. *
  17665. * @type {Vector3}
  17666. */
  17667. this.v2 = v2;
  17668. }
  17669. /**
  17670. * Returns a point on the curve.
  17671. *
  17672. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17673. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17674. * @return {Vector3} The position on the curve.
  17675. */
  17676. getPoint( t, optionalTarget = new Vector3() ) {
  17677. const point = optionalTarget;
  17678. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  17679. point.set(
  17680. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  17681. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  17682. QuadraticBezier( t, v0.z, v1.z, v2.z )
  17683. );
  17684. return point;
  17685. }
  17686. copy( source ) {
  17687. super.copy( source );
  17688. this.v0.copy( source.v0 );
  17689. this.v1.copy( source.v1 );
  17690. this.v2.copy( source.v2 );
  17691. return this;
  17692. }
  17693. toJSON() {
  17694. const data = super.toJSON();
  17695. data.v0 = this.v0.toArray();
  17696. data.v1 = this.v1.toArray();
  17697. data.v2 = this.v2.toArray();
  17698. return data;
  17699. }
  17700. fromJSON( json ) {
  17701. super.fromJSON( json );
  17702. this.v0.fromArray( json.v0 );
  17703. this.v1.fromArray( json.v1 );
  17704. this.v2.fromArray( json.v2 );
  17705. return this;
  17706. }
  17707. }
  17708. /**
  17709. * A curve representing a 2D spline curve.
  17710. *
  17711. * ```js
  17712. * // Create a sine-like wave
  17713. * const curve = new THREE.SplineCurve( [
  17714. * new THREE.Vector2( -10, 0 ),
  17715. * new THREE.Vector2( -5, 5 ),
  17716. * new THREE.Vector2( 0, 0 ),
  17717. * new THREE.Vector2( 5, -5 ),
  17718. * new THREE.Vector2( 10, 0 )
  17719. * ] );
  17720. *
  17721. * const points = curve.getPoints( 50 );
  17722. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17723. *
  17724. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17725. *
  17726. * // Create the final object to add to the scene
  17727. * const splineObject = new THREE.Line( geometry, material );
  17728. * ```
  17729. *
  17730. * @augments Curve
  17731. */
  17732. class SplineCurve extends Curve {
  17733. /**
  17734. * Constructs a new 2D spline curve.
  17735. *
  17736. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  17737. */
  17738. constructor( points = [] ) {
  17739. super();
  17740. /**
  17741. * This flag can be used for type testing.
  17742. *
  17743. * @type {boolean}
  17744. * @readonly
  17745. * @default true
  17746. */
  17747. this.isSplineCurve = true;
  17748. this.type = 'SplineCurve';
  17749. /**
  17750. * An array of 2D points defining the curve.
  17751. *
  17752. * @type {Array<Vector2>}
  17753. */
  17754. this.points = points;
  17755. }
  17756. /**
  17757. * Returns a point on the curve.
  17758. *
  17759. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17760. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17761. * @return {Vector2} The position on the curve.
  17762. */
  17763. getPoint( t, optionalTarget = new Vector2() ) {
  17764. const point = optionalTarget;
  17765. const points = this.points;
  17766. const p = ( points.length - 1 ) * t;
  17767. const intPoint = Math.floor( p );
  17768. const weight = p - intPoint;
  17769. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  17770. const p1 = points[ intPoint ];
  17771. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17772. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17773. point.set(
  17774. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  17775. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  17776. );
  17777. return point;
  17778. }
  17779. copy( source ) {
  17780. super.copy( source );
  17781. this.points = [];
  17782. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  17783. const point = source.points[ i ];
  17784. this.points.push( point.clone() );
  17785. }
  17786. return this;
  17787. }
  17788. toJSON() {
  17789. const data = super.toJSON();
  17790. data.points = [];
  17791. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  17792. const point = this.points[ i ];
  17793. data.points.push( point.toArray() );
  17794. }
  17795. return data;
  17796. }
  17797. fromJSON( json ) {
  17798. super.fromJSON( json );
  17799. this.points = [];
  17800. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  17801. const point = json.points[ i ];
  17802. this.points.push( new Vector2().fromArray( point ) );
  17803. }
  17804. return this;
  17805. }
  17806. }
  17807. var Curves = /*#__PURE__*/Object.freeze({
  17808. __proto__: null,
  17809. ArcCurve: ArcCurve,
  17810. CatmullRomCurve3: CatmullRomCurve3,
  17811. CubicBezierCurve: CubicBezierCurve,
  17812. CubicBezierCurve3: CubicBezierCurve3,
  17813. EllipseCurve: EllipseCurve,
  17814. LineCurve: LineCurve,
  17815. LineCurve3: LineCurve3,
  17816. QuadraticBezierCurve: QuadraticBezierCurve,
  17817. QuadraticBezierCurve3: QuadraticBezierCurve3,
  17818. SplineCurve: SplineCurve
  17819. });
  17820. /**
  17821. * A base class extending {@link Curve}. `CurvePath` is simply an
  17822. * array of connected curves, but retains the API of a curve.
  17823. *
  17824. * @augments Curve
  17825. */
  17826. class CurvePath extends Curve {
  17827. /**
  17828. * Constructs a new curve path.
  17829. */
  17830. constructor() {
  17831. super();
  17832. this.type = 'CurvePath';
  17833. /**
  17834. * An array of curves defining the
  17835. * path.
  17836. *
  17837. * @type {Array<Curve>}
  17838. */
  17839. this.curves = [];
  17840. /**
  17841. * Whether the path should automatically be closed
  17842. * by a line curve.
  17843. *
  17844. * @type {boolean}
  17845. * @default false
  17846. */
  17847. this.autoClose = false;
  17848. }
  17849. /**
  17850. * Adds a curve to this curve path.
  17851. *
  17852. * @param {Curve} curve - The curve to add.
  17853. */
  17854. add( curve ) {
  17855. this.curves.push( curve );
  17856. }
  17857. /**
  17858. * Adds a line curve to close the path.
  17859. *
  17860. * @return {CurvePath} A reference to this curve path.
  17861. */
  17862. closePath() {
  17863. // Add a line curve if start and end of lines are not connected
  17864. const startPoint = this.curves[ 0 ].getPoint( 0 );
  17865. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  17866. if ( ! startPoint.equals( endPoint ) ) {
  17867. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  17868. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  17869. }
  17870. return this;
  17871. }
  17872. /**
  17873. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  17874. * for the given interpolation factor.
  17875. *
  17876. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17877. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17878. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  17879. */
  17880. getPoint( t, optionalTarget ) {
  17881. // To get accurate point with reference to
  17882. // entire path distance at time t,
  17883. // following has to be done:
  17884. // 1. Length of each sub path have to be known
  17885. // 2. Locate and identify type of curve
  17886. // 3. Get t for the curve
  17887. // 4. Return curve.getPointAt(t')
  17888. const d = t * this.getLength();
  17889. const curveLengths = this.getCurveLengths();
  17890. let i = 0;
  17891. // To think about boundaries points.
  17892. while ( i < curveLengths.length ) {
  17893. if ( curveLengths[ i ] >= d ) {
  17894. const diff = curveLengths[ i ] - d;
  17895. const curve = this.curves[ i ];
  17896. const segmentLength = curve.getLength();
  17897. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  17898. return curve.getPointAt( u, optionalTarget );
  17899. }
  17900. i ++;
  17901. }
  17902. return null;
  17903. // loop where sum != 0, sum > d , sum+1 <d
  17904. }
  17905. getLength() {
  17906. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17907. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17908. // getPoint() depends on getLength
  17909. const lens = this.getCurveLengths();
  17910. return lens[ lens.length - 1 ];
  17911. }
  17912. updateArcLengths() {
  17913. // cacheLengths must be recalculated.
  17914. this.needsUpdate = true;
  17915. this.cacheLengths = null;
  17916. this.getCurveLengths();
  17917. }
  17918. /**
  17919. * Returns list of cumulative curve lengths of the defined curves.
  17920. *
  17921. * @return {Array<number>} The curve lengths.
  17922. */
  17923. getCurveLengths() {
  17924. // Compute lengths and cache them
  17925. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17926. // We use cache values if curves and cache array are same length
  17927. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  17928. return this.cacheLengths;
  17929. }
  17930. // Get length of sub-curve
  17931. // Push sums into cached array
  17932. const lengths = [];
  17933. let sums = 0;
  17934. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  17935. sums += this.curves[ i ].getLength();
  17936. lengths.push( sums );
  17937. }
  17938. this.cacheLengths = lengths;
  17939. return lengths;
  17940. }
  17941. getSpacedPoints( divisions = 40 ) {
  17942. const points = [];
  17943. for ( let i = 0; i <= divisions; i ++ ) {
  17944. points.push( this.getPoint( i / divisions ) );
  17945. }
  17946. if ( this.autoClose ) {
  17947. points.push( points[ 0 ] );
  17948. }
  17949. return points;
  17950. }
  17951. getPoints( divisions = 12 ) {
  17952. const points = [];
  17953. let last;
  17954. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  17955. const curve = curves[ i ];
  17956. const resolution = curve.isEllipseCurve ? divisions * 2
  17957. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  17958. : curve.isSplineCurve ? divisions * curve.points.length
  17959. : divisions;
  17960. const pts = curve.getPoints( resolution );
  17961. for ( let j = 0; j < pts.length; j ++ ) {
  17962. const point = pts[ j ];
  17963. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  17964. points.push( point );
  17965. last = point;
  17966. }
  17967. }
  17968. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  17969. points.push( points[ 0 ] );
  17970. }
  17971. return points;
  17972. }
  17973. copy( source ) {
  17974. super.copy( source );
  17975. this.curves = [];
  17976. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  17977. const curve = source.curves[ i ];
  17978. this.curves.push( curve.clone() );
  17979. }
  17980. this.autoClose = source.autoClose;
  17981. return this;
  17982. }
  17983. toJSON() {
  17984. const data = super.toJSON();
  17985. data.autoClose = this.autoClose;
  17986. data.curves = [];
  17987. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  17988. const curve = this.curves[ i ];
  17989. data.curves.push( curve.toJSON() );
  17990. }
  17991. return data;
  17992. }
  17993. fromJSON( json ) {
  17994. super.fromJSON( json );
  17995. this.autoClose = json.autoClose;
  17996. this.curves = [];
  17997. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  17998. const curve = json.curves[ i ];
  17999. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  18000. }
  18001. return this;
  18002. }
  18003. }
  18004. /**
  18005. * A 2D path representation. The class provides methods for creating paths
  18006. * and contours of 2D shapes similar to the 2D Canvas API.
  18007. *
  18008. * ```js
  18009. * const path = new THREE.Path();
  18010. *
  18011. * path.lineTo( 0, 0.8 );
  18012. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  18013. * path.lineTo( 1, 1 );
  18014. *
  18015. * const points = path.getPoints();
  18016. *
  18017. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18018. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  18019. *
  18020. * const line = new THREE.Line( geometry, material );
  18021. * scene.add( line );
  18022. * ```
  18023. *
  18024. * @augments CurvePath
  18025. */
  18026. class Path extends CurvePath {
  18027. /**
  18028. * Constructs a new path.
  18029. *
  18030. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  18031. */
  18032. constructor( points ) {
  18033. super();
  18034. this.type = 'Path';
  18035. /**
  18036. * The current offset of the path. Any new curve added will start here.
  18037. *
  18038. * @type {Vector2}
  18039. */
  18040. this.currentPoint = new Vector2();
  18041. if ( points ) {
  18042. this.setFromPoints( points );
  18043. }
  18044. }
  18045. /**
  18046. * Creates a path from the given list of points. The points are added
  18047. * to the path as instances of {@link LineCurve}.
  18048. *
  18049. * @param {Array<Vector2>} points - An array of 2D points.
  18050. * @return {Path} A reference to this path.
  18051. */
  18052. setFromPoints( points ) {
  18053. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  18054. for ( let i = 1, l = points.length; i < l; i ++ ) {
  18055. this.lineTo( points[ i ].x, points[ i ].y );
  18056. }
  18057. return this;
  18058. }
  18059. /**
  18060. * Moves {@link Path#currentPoint} to the given point.
  18061. *
  18062. * @param {number} x - The x coordinate.
  18063. * @param {number} y - The y coordinate.
  18064. * @return {Path} A reference to this path.
  18065. */
  18066. moveTo( x, y ) {
  18067. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  18068. return this;
  18069. }
  18070. /**
  18071. * Adds an instance of {@link LineCurve} to the path by connecting
  18072. * the current point with the given one.
  18073. *
  18074. * @param {number} x - The x coordinate of the end point.
  18075. * @param {number} y - The y coordinate of the end point.
  18076. * @return {Path} A reference to this path.
  18077. */
  18078. lineTo( x, y ) {
  18079. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  18080. this.curves.push( curve );
  18081. this.currentPoint.set( x, y );
  18082. return this;
  18083. }
  18084. /**
  18085. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  18086. * the current point with the given one.
  18087. *
  18088. * @param {number} aCPx - The x coordinate of the control point.
  18089. * @param {number} aCPy - The y coordinate of the control point.
  18090. * @param {number} aX - The x coordinate of the end point.
  18091. * @param {number} aY - The y coordinate of the end point.
  18092. * @return {Path} A reference to this path.
  18093. */
  18094. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  18095. const curve = new QuadraticBezierCurve(
  18096. this.currentPoint.clone(),
  18097. new Vector2( aCPx, aCPy ),
  18098. new Vector2( aX, aY )
  18099. );
  18100. this.curves.push( curve );
  18101. this.currentPoint.set( aX, aY );
  18102. return this;
  18103. }
  18104. /**
  18105. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  18106. * the current point with the given one.
  18107. *
  18108. * @param {number} aCP1x - The x coordinate of the first control point.
  18109. * @param {number} aCP1y - The y coordinate of the first control point.
  18110. * @param {number} aCP2x - The x coordinate of the second control point.
  18111. * @param {number} aCP2y - The y coordinate of the second control point.
  18112. * @param {number} aX - The x coordinate of the end point.
  18113. * @param {number} aY - The y coordinate of the end point.
  18114. * @return {Path} A reference to this path.
  18115. */
  18116. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18117. const curve = new CubicBezierCurve(
  18118. this.currentPoint.clone(),
  18119. new Vector2( aCP1x, aCP1y ),
  18120. new Vector2( aCP2x, aCP2y ),
  18121. new Vector2( aX, aY )
  18122. );
  18123. this.curves.push( curve );
  18124. this.currentPoint.set( aX, aY );
  18125. return this;
  18126. }
  18127. /**
  18128. * Adds an instance of {@link SplineCurve} to the path by connecting
  18129. * the current point with the given list of points.
  18130. *
  18131. * @param {Array<Vector2>} pts - An array of points in 2D space.
  18132. * @return {Path} A reference to this path.
  18133. */
  18134. splineThru( pts ) {
  18135. const npts = [ this.currentPoint.clone() ].concat( pts );
  18136. const curve = new SplineCurve( npts );
  18137. this.curves.push( curve );
  18138. this.currentPoint.copy( pts[ pts.length - 1 ] );
  18139. return this;
  18140. }
  18141. /**
  18142. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  18143. * to the current point.
  18144. *
  18145. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  18146. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  18147. * @param {number} aRadius - The radius of the arc.
  18148. * @param {number} aStartAngle - The start angle in radians.
  18149. * @param {number} aEndAngle - The end angle in radians.
  18150. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  18151. * @return {Path} A reference to this path.
  18152. */
  18153. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18154. const x0 = this.currentPoint.x;
  18155. const y0 = this.currentPoint.y;
  18156. this.absarc( aX + x0, aY + y0, aRadius,
  18157. aStartAngle, aEndAngle, aClockwise );
  18158. return this;
  18159. }
  18160. /**
  18161. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  18162. *
  18163. * @param {number} aX - The x coordinate of the center of the arc.
  18164. * @param {number} aY - The y coordinate of the center of the arc.
  18165. * @param {number} aRadius - The radius of the arc.
  18166. * @param {number} aStartAngle - The start angle in radians.
  18167. * @param {number} aEndAngle - The end angle in radians.
  18168. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  18169. * @return {Path} A reference to this path.
  18170. */
  18171. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18172. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18173. return this;
  18174. }
  18175. /**
  18176. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  18177. * to the current point
  18178. *
  18179. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  18180. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  18181. * @param {number} xRadius - The radius of the ellipse in the x axis.
  18182. * @param {number} yRadius - The radius of the ellipse in the y axis.
  18183. * @param {number} aStartAngle - The start angle in radians.
  18184. * @param {number} aEndAngle - The end angle in radians.
  18185. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  18186. * @param {boolean} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  18187. * @return {Path} A reference to this path.
  18188. */
  18189. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18190. const x0 = this.currentPoint.x;
  18191. const y0 = this.currentPoint.y;
  18192. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18193. return this;
  18194. }
  18195. /**
  18196. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  18197. *
  18198. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  18199. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  18200. * @param {number} xRadius - The radius of the ellipse in the x axis.
  18201. * @param {number} yRadius - The radius of the ellipse in the y axis.
  18202. * @param {number} aStartAngle - The start angle in radians.
  18203. * @param {number} aEndAngle - The end angle in radians.
  18204. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  18205. * @param {boolean} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  18206. * @return {Path} A reference to this path.
  18207. */
  18208. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18209. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18210. if ( this.curves.length > 0 ) {
  18211. // if a previous curve is present, attempt to join
  18212. const firstPoint = curve.getPoint( 0 );
  18213. if ( ! firstPoint.equals( this.currentPoint ) ) {
  18214. this.lineTo( firstPoint.x, firstPoint.y );
  18215. }
  18216. }
  18217. this.curves.push( curve );
  18218. const lastPoint = curve.getPoint( 1 );
  18219. this.currentPoint.copy( lastPoint );
  18220. return this;
  18221. }
  18222. copy( source ) {
  18223. super.copy( source );
  18224. this.currentPoint.copy( source.currentPoint );
  18225. return this;
  18226. }
  18227. toJSON() {
  18228. const data = super.toJSON();
  18229. data.currentPoint = this.currentPoint.toArray();
  18230. return data;
  18231. }
  18232. fromJSON( json ) {
  18233. super.fromJSON( json );
  18234. this.currentPoint.fromArray( json.currentPoint );
  18235. return this;
  18236. }
  18237. }
  18238. class LatheGeometry extends BufferGeometry {
  18239. 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 ) {
  18240. super();
  18241. this.type = 'LatheGeometry';
  18242. this.parameters = {
  18243. points: points,
  18244. segments: segments,
  18245. phiStart: phiStart,
  18246. phiLength: phiLength
  18247. };
  18248. segments = Math.floor( segments );
  18249. // clamp phiLength so it's in range of [ 0, 2PI ]
  18250. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  18251. // buffers
  18252. const indices = [];
  18253. const vertices = [];
  18254. const uvs = [];
  18255. const initNormals = [];
  18256. const normals = [];
  18257. // helper variables
  18258. const inverseSegments = 1.0 / segments;
  18259. const vertex = new Vector3();
  18260. const uv = new Vector2();
  18261. const normal = new Vector3();
  18262. const curNormal = new Vector3();
  18263. const prevNormal = new Vector3();
  18264. let dx = 0;
  18265. let dy = 0;
  18266. // pre-compute normals for initial "meridian"
  18267. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  18268. switch ( j ) {
  18269. case 0: // special handling for 1st vertex on path
  18270. dx = points[ j + 1 ].x - points[ j ].x;
  18271. dy = points[ j + 1 ].y - points[ j ].y;
  18272. normal.x = dy * 1.0;
  18273. normal.y = - dx;
  18274. normal.z = dy * 0.0;
  18275. prevNormal.copy( normal );
  18276. normal.normalize();
  18277. initNormals.push( normal.x, normal.y, normal.z );
  18278. break;
  18279. case ( points.length - 1 ): // special handling for last Vertex on path
  18280. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  18281. break;
  18282. default: // default handling for all vertices in between
  18283. dx = points[ j + 1 ].x - points[ j ].x;
  18284. dy = points[ j + 1 ].y - points[ j ].y;
  18285. normal.x = dy * 1.0;
  18286. normal.y = - dx;
  18287. normal.z = dy * 0.0;
  18288. curNormal.copy( normal );
  18289. normal.x += prevNormal.x;
  18290. normal.y += prevNormal.y;
  18291. normal.z += prevNormal.z;
  18292. normal.normalize();
  18293. initNormals.push( normal.x, normal.y, normal.z );
  18294. prevNormal.copy( curNormal );
  18295. }
  18296. }
  18297. // generate vertices, uvs and normals
  18298. for ( let i = 0; i <= segments; i ++ ) {
  18299. const phi = phiStart + i * inverseSegments * phiLength;
  18300. const sin = Math.sin( phi );
  18301. const cos = Math.cos( phi );
  18302. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  18303. // vertex
  18304. vertex.x = points[ j ].x * sin;
  18305. vertex.y = points[ j ].y;
  18306. vertex.z = points[ j ].x * cos;
  18307. vertices.push( vertex.x, vertex.y, vertex.z );
  18308. // uv
  18309. uv.x = i / segments;
  18310. uv.y = j / ( points.length - 1 );
  18311. uvs.push( uv.x, uv.y );
  18312. // normal
  18313. const x = initNormals[ 3 * j + 0 ] * sin;
  18314. const y = initNormals[ 3 * j + 1 ];
  18315. const z = initNormals[ 3 * j + 0 ] * cos;
  18316. normals.push( x, y, z );
  18317. }
  18318. }
  18319. // indices
  18320. for ( let i = 0; i < segments; i ++ ) {
  18321. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  18322. const base = j + i * points.length;
  18323. const a = base;
  18324. const b = base + points.length;
  18325. const c = base + points.length + 1;
  18326. const d = base + 1;
  18327. // faces
  18328. indices.push( a, b, d );
  18329. indices.push( c, d, b );
  18330. }
  18331. }
  18332. // build geometry
  18333. this.setIndex( indices );
  18334. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18335. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18336. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18337. }
  18338. copy( source ) {
  18339. super.copy( source );
  18340. this.parameters = Object.assign( {}, source.parameters );
  18341. return this;
  18342. }
  18343. static fromJSON( data ) {
  18344. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  18345. }
  18346. }
  18347. class CapsuleGeometry extends LatheGeometry {
  18348. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  18349. const path = new Path();
  18350. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  18351. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  18352. super( path.getPoints( capSegments ), radialSegments );
  18353. this.type = 'CapsuleGeometry';
  18354. this.parameters = {
  18355. radius: radius,
  18356. length: length,
  18357. capSegments: capSegments,
  18358. radialSegments: radialSegments,
  18359. };
  18360. }
  18361. static fromJSON( data ) {
  18362. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  18363. }
  18364. }
  18365. class CircleGeometry extends BufferGeometry {
  18366. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18367. super();
  18368. this.type = 'CircleGeometry';
  18369. this.parameters = {
  18370. radius: radius,
  18371. segments: segments,
  18372. thetaStart: thetaStart,
  18373. thetaLength: thetaLength
  18374. };
  18375. segments = Math.max( 3, segments );
  18376. // buffers
  18377. const indices = [];
  18378. const vertices = [];
  18379. const normals = [];
  18380. const uvs = [];
  18381. // helper variables
  18382. const vertex = new Vector3();
  18383. const uv = new Vector2();
  18384. // center point
  18385. vertices.push( 0, 0, 0 );
  18386. normals.push( 0, 0, 1 );
  18387. uvs.push( 0.5, 0.5 );
  18388. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  18389. const segment = thetaStart + s / segments * thetaLength;
  18390. // vertex
  18391. vertex.x = radius * Math.cos( segment );
  18392. vertex.y = radius * Math.sin( segment );
  18393. vertices.push( vertex.x, vertex.y, vertex.z );
  18394. // normal
  18395. normals.push( 0, 0, 1 );
  18396. // uvs
  18397. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  18398. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  18399. uvs.push( uv.x, uv.y );
  18400. }
  18401. // indices
  18402. for ( let i = 1; i <= segments; i ++ ) {
  18403. indices.push( i, i + 1, 0 );
  18404. }
  18405. // build geometry
  18406. this.setIndex( indices );
  18407. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18408. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18409. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18410. }
  18411. copy( source ) {
  18412. super.copy( source );
  18413. this.parameters = Object.assign( {}, source.parameters );
  18414. return this;
  18415. }
  18416. static fromJSON( data ) {
  18417. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  18418. }
  18419. }
  18420. class CylinderGeometry extends BufferGeometry {
  18421. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18422. super();
  18423. this.type = 'CylinderGeometry';
  18424. this.parameters = {
  18425. radiusTop: radiusTop,
  18426. radiusBottom: radiusBottom,
  18427. height: height,
  18428. radialSegments: radialSegments,
  18429. heightSegments: heightSegments,
  18430. openEnded: openEnded,
  18431. thetaStart: thetaStart,
  18432. thetaLength: thetaLength
  18433. };
  18434. const scope = this;
  18435. radialSegments = Math.floor( radialSegments );
  18436. heightSegments = Math.floor( heightSegments );
  18437. // buffers
  18438. const indices = [];
  18439. const vertices = [];
  18440. const normals = [];
  18441. const uvs = [];
  18442. // helper variables
  18443. let index = 0;
  18444. const indexArray = [];
  18445. const halfHeight = height / 2;
  18446. let groupStart = 0;
  18447. // generate geometry
  18448. generateTorso();
  18449. if ( openEnded === false ) {
  18450. if ( radiusTop > 0 ) generateCap( true );
  18451. if ( radiusBottom > 0 ) generateCap( false );
  18452. }
  18453. // build geometry
  18454. this.setIndex( indices );
  18455. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18456. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18457. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18458. function generateTorso() {
  18459. const normal = new Vector3();
  18460. const vertex = new Vector3();
  18461. let groupCount = 0;
  18462. // this will be used to calculate the normal
  18463. const slope = ( radiusBottom - radiusTop ) / height;
  18464. // generate vertices, normals and uvs
  18465. for ( let y = 0; y <= heightSegments; y ++ ) {
  18466. const indexRow = [];
  18467. const v = y / heightSegments;
  18468. // calculate the radius of the current row
  18469. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18470. for ( let x = 0; x <= radialSegments; x ++ ) {
  18471. const u = x / radialSegments;
  18472. const theta = u * thetaLength + thetaStart;
  18473. const sinTheta = Math.sin( theta );
  18474. const cosTheta = Math.cos( theta );
  18475. // vertex
  18476. vertex.x = radius * sinTheta;
  18477. vertex.y = - v * height + halfHeight;
  18478. vertex.z = radius * cosTheta;
  18479. vertices.push( vertex.x, vertex.y, vertex.z );
  18480. // normal
  18481. normal.set( sinTheta, slope, cosTheta ).normalize();
  18482. normals.push( normal.x, normal.y, normal.z );
  18483. // uv
  18484. uvs.push( u, 1 - v );
  18485. // save index of vertex in respective row
  18486. indexRow.push( index ++ );
  18487. }
  18488. // now save vertices of the row in our index array
  18489. indexArray.push( indexRow );
  18490. }
  18491. // generate indices
  18492. for ( let x = 0; x < radialSegments; x ++ ) {
  18493. for ( let y = 0; y < heightSegments; y ++ ) {
  18494. // we use the index array to access the correct indices
  18495. const a = indexArray[ y ][ x ];
  18496. const b = indexArray[ y + 1 ][ x ];
  18497. const c = indexArray[ y + 1 ][ x + 1 ];
  18498. const d = indexArray[ y ][ x + 1 ];
  18499. // faces
  18500. if ( radiusTop > 0 || y !== 0 ) {
  18501. indices.push( a, b, d );
  18502. groupCount += 3;
  18503. }
  18504. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  18505. indices.push( b, c, d );
  18506. groupCount += 3;
  18507. }
  18508. }
  18509. }
  18510. // add a group to the geometry. this will ensure multi material support
  18511. scope.addGroup( groupStart, groupCount, 0 );
  18512. // calculate new start value for groups
  18513. groupStart += groupCount;
  18514. }
  18515. function generateCap( top ) {
  18516. // save the index of the first center vertex
  18517. const centerIndexStart = index;
  18518. const uv = new Vector2();
  18519. const vertex = new Vector3();
  18520. let groupCount = 0;
  18521. const radius = ( top === true ) ? radiusTop : radiusBottom;
  18522. const sign = ( top === true ) ? 1 : -1;
  18523. // first we generate the center vertex data of the cap.
  18524. // because the geometry needs one set of uvs per face,
  18525. // we must generate a center vertex per face/segment
  18526. for ( let x = 1; x <= radialSegments; x ++ ) {
  18527. // vertex
  18528. vertices.push( 0, halfHeight * sign, 0 );
  18529. // normal
  18530. normals.push( 0, sign, 0 );
  18531. // uv
  18532. uvs.push( 0.5, 0.5 );
  18533. // increase index
  18534. index ++;
  18535. }
  18536. // save the index of the last center vertex
  18537. const centerIndexEnd = index;
  18538. // now we generate the surrounding vertices, normals and uvs
  18539. for ( let x = 0; x <= radialSegments; x ++ ) {
  18540. const u = x / radialSegments;
  18541. const theta = u * thetaLength + thetaStart;
  18542. const cosTheta = Math.cos( theta );
  18543. const sinTheta = Math.sin( theta );
  18544. // vertex
  18545. vertex.x = radius * sinTheta;
  18546. vertex.y = halfHeight * sign;
  18547. vertex.z = radius * cosTheta;
  18548. vertices.push( vertex.x, vertex.y, vertex.z );
  18549. // normal
  18550. normals.push( 0, sign, 0 );
  18551. // uv
  18552. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18553. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18554. uvs.push( uv.x, uv.y );
  18555. // increase index
  18556. index ++;
  18557. }
  18558. // generate indices
  18559. for ( let x = 0; x < radialSegments; x ++ ) {
  18560. const c = centerIndexStart + x;
  18561. const i = centerIndexEnd + x;
  18562. if ( top === true ) {
  18563. // face top
  18564. indices.push( i, i + 1, c );
  18565. } else {
  18566. // face bottom
  18567. indices.push( i + 1, i, c );
  18568. }
  18569. groupCount += 3;
  18570. }
  18571. // add a group to the geometry. this will ensure multi material support
  18572. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18573. // calculate new start value for groups
  18574. groupStart += groupCount;
  18575. }
  18576. }
  18577. copy( source ) {
  18578. super.copy( source );
  18579. this.parameters = Object.assign( {}, source.parameters );
  18580. return this;
  18581. }
  18582. static fromJSON( data ) {
  18583. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18584. }
  18585. }
  18586. class ConeGeometry extends CylinderGeometry {
  18587. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18588. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18589. this.type = 'ConeGeometry';
  18590. this.parameters = {
  18591. radius: radius,
  18592. height: height,
  18593. radialSegments: radialSegments,
  18594. heightSegments: heightSegments,
  18595. openEnded: openEnded,
  18596. thetaStart: thetaStart,
  18597. thetaLength: thetaLength
  18598. };
  18599. }
  18600. static fromJSON( data ) {
  18601. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18602. }
  18603. }
  18604. class PolyhedronGeometry extends BufferGeometry {
  18605. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  18606. super();
  18607. this.type = 'PolyhedronGeometry';
  18608. this.parameters = {
  18609. vertices: vertices,
  18610. indices: indices,
  18611. radius: radius,
  18612. detail: detail
  18613. };
  18614. // default buffer data
  18615. const vertexBuffer = [];
  18616. const uvBuffer = [];
  18617. // the subdivision creates the vertex buffer data
  18618. subdivide( detail );
  18619. // all vertices should lie on a conceptual sphere with a given radius
  18620. applyRadius( radius );
  18621. // finally, create the uv data
  18622. generateUVs();
  18623. // build non-indexed geometry
  18624. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18625. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18626. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18627. if ( detail === 0 ) {
  18628. this.computeVertexNormals(); // flat normals
  18629. } else {
  18630. this.normalizeNormals(); // smooth normals
  18631. }
  18632. // helper functions
  18633. function subdivide( detail ) {
  18634. const a = new Vector3();
  18635. const b = new Vector3();
  18636. const c = new Vector3();
  18637. // iterate over all faces and apply a subdivision with the given detail value
  18638. for ( let i = 0; i < indices.length; i += 3 ) {
  18639. // get the vertices of the face
  18640. getVertexByIndex( indices[ i + 0 ], a );
  18641. getVertexByIndex( indices[ i + 1 ], b );
  18642. getVertexByIndex( indices[ i + 2 ], c );
  18643. // perform subdivision
  18644. subdivideFace( a, b, c, detail );
  18645. }
  18646. }
  18647. function subdivideFace( a, b, c, detail ) {
  18648. const cols = detail + 1;
  18649. // we use this multidimensional array as a data structure for creating the subdivision
  18650. const v = [];
  18651. // construct all of the vertices for this subdivision
  18652. for ( let i = 0; i <= cols; i ++ ) {
  18653. v[ i ] = [];
  18654. const aj = a.clone().lerp( c, i / cols );
  18655. const bj = b.clone().lerp( c, i / cols );
  18656. const rows = cols - i;
  18657. for ( let j = 0; j <= rows; j ++ ) {
  18658. if ( j === 0 && i === cols ) {
  18659. v[ i ][ j ] = aj;
  18660. } else {
  18661. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18662. }
  18663. }
  18664. }
  18665. // construct all of the faces
  18666. for ( let i = 0; i < cols; i ++ ) {
  18667. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18668. const k = Math.floor( j / 2 );
  18669. if ( j % 2 === 0 ) {
  18670. pushVertex( v[ i ][ k + 1 ] );
  18671. pushVertex( v[ i + 1 ][ k ] );
  18672. pushVertex( v[ i ][ k ] );
  18673. } else {
  18674. pushVertex( v[ i ][ k + 1 ] );
  18675. pushVertex( v[ i + 1 ][ k + 1 ] );
  18676. pushVertex( v[ i + 1 ][ k ] );
  18677. }
  18678. }
  18679. }
  18680. }
  18681. function applyRadius( radius ) {
  18682. const vertex = new Vector3();
  18683. // iterate over the entire buffer and apply the radius to each vertex
  18684. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18685. vertex.x = vertexBuffer[ i + 0 ];
  18686. vertex.y = vertexBuffer[ i + 1 ];
  18687. vertex.z = vertexBuffer[ i + 2 ];
  18688. vertex.normalize().multiplyScalar( radius );
  18689. vertexBuffer[ i + 0 ] = vertex.x;
  18690. vertexBuffer[ i + 1 ] = vertex.y;
  18691. vertexBuffer[ i + 2 ] = vertex.z;
  18692. }
  18693. }
  18694. function generateUVs() {
  18695. const vertex = new Vector3();
  18696. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18697. vertex.x = vertexBuffer[ i + 0 ];
  18698. vertex.y = vertexBuffer[ i + 1 ];
  18699. vertex.z = vertexBuffer[ i + 2 ];
  18700. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18701. const v = inclination( vertex ) / Math.PI + 0.5;
  18702. uvBuffer.push( u, 1 - v );
  18703. }
  18704. correctUVs();
  18705. correctSeam();
  18706. }
  18707. function correctSeam() {
  18708. // handle case when face straddles the seam, see #3269
  18709. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18710. // uv data of a single face
  18711. const x0 = uvBuffer[ i + 0 ];
  18712. const x1 = uvBuffer[ i + 2 ];
  18713. const x2 = uvBuffer[ i + 4 ];
  18714. const max = Math.max( x0, x1, x2 );
  18715. const min = Math.min( x0, x1, x2 );
  18716. // 0.9 is somewhat arbitrary
  18717. if ( max > 0.9 && min < 0.1 ) {
  18718. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18719. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18720. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18721. }
  18722. }
  18723. }
  18724. function pushVertex( vertex ) {
  18725. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18726. }
  18727. function getVertexByIndex( index, vertex ) {
  18728. const stride = index * 3;
  18729. vertex.x = vertices[ stride + 0 ];
  18730. vertex.y = vertices[ stride + 1 ];
  18731. vertex.z = vertices[ stride + 2 ];
  18732. }
  18733. function correctUVs() {
  18734. const a = new Vector3();
  18735. const b = new Vector3();
  18736. const c = new Vector3();
  18737. const centroid = new Vector3();
  18738. const uvA = new Vector2();
  18739. const uvB = new Vector2();
  18740. const uvC = new Vector2();
  18741. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18742. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18743. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18744. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18745. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18746. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18747. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18748. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18749. const azi = azimuth( centroid );
  18750. correctUV( uvA, j + 0, a, azi );
  18751. correctUV( uvB, j + 2, b, azi );
  18752. correctUV( uvC, j + 4, c, azi );
  18753. }
  18754. }
  18755. function correctUV( uv, stride, vector, azimuth ) {
  18756. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18757. uvBuffer[ stride ] = uv.x - 1;
  18758. }
  18759. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18760. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18761. }
  18762. }
  18763. // Angle around the Y axis, counter-clockwise when looking from above.
  18764. function azimuth( vector ) {
  18765. return Math.atan2( vector.z, - vector.x );
  18766. }
  18767. // Angle above the XZ plane.
  18768. function inclination( vector ) {
  18769. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18770. }
  18771. }
  18772. copy( source ) {
  18773. super.copy( source );
  18774. this.parameters = Object.assign( {}, source.parameters );
  18775. return this;
  18776. }
  18777. static fromJSON( data ) {
  18778. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  18779. }
  18780. }
  18781. class DodecahedronGeometry extends PolyhedronGeometry {
  18782. constructor( radius = 1, detail = 0 ) {
  18783. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18784. const r = 1 / t;
  18785. const vertices = [
  18786. // (±1, ±1, ±1)
  18787. -1, -1, -1, -1, -1, 1,
  18788. -1, 1, -1, -1, 1, 1,
  18789. 1, -1, -1, 1, -1, 1,
  18790. 1, 1, -1, 1, 1, 1,
  18791. // (0, ±1/φ, ±φ)
  18792. 0, - r, - t, 0, - r, t,
  18793. 0, r, - t, 0, r, t,
  18794. // (±1/φ, ±φ, 0)
  18795. - r, - t, 0, - r, t, 0,
  18796. r, - t, 0, r, t, 0,
  18797. // (±φ, 0, ±1/φ)
  18798. - t, 0, - r, t, 0, - r,
  18799. - t, 0, r, t, 0, r
  18800. ];
  18801. const indices = [
  18802. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18803. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18804. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18805. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18806. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18807. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18808. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18809. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18810. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18811. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18812. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18813. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18814. ];
  18815. super( vertices, indices, radius, detail );
  18816. this.type = 'DodecahedronGeometry';
  18817. this.parameters = {
  18818. radius: radius,
  18819. detail: detail
  18820. };
  18821. }
  18822. static fromJSON( data ) {
  18823. return new DodecahedronGeometry( data.radius, data.detail );
  18824. }
  18825. }
  18826. const _v0$1 = /*@__PURE__*/ new Vector3();
  18827. const _v1$1 = /*@__PURE__*/ new Vector3();
  18828. const _normal = /*@__PURE__*/ new Vector3();
  18829. const _triangle = /*@__PURE__*/ new Triangle();
  18830. class EdgesGeometry extends BufferGeometry {
  18831. constructor( geometry = null, thresholdAngle = 1 ) {
  18832. super();
  18833. this.type = 'EdgesGeometry';
  18834. this.parameters = {
  18835. geometry: geometry,
  18836. thresholdAngle: thresholdAngle
  18837. };
  18838. if ( geometry !== null ) {
  18839. const precisionPoints = 4;
  18840. const precision = Math.pow( 10, precisionPoints );
  18841. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  18842. const indexAttr = geometry.getIndex();
  18843. const positionAttr = geometry.getAttribute( 'position' );
  18844. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18845. const indexArr = [ 0, 0, 0 ];
  18846. const vertKeys = [ 'a', 'b', 'c' ];
  18847. const hashes = new Array( 3 );
  18848. const edgeData = {};
  18849. const vertices = [];
  18850. for ( let i = 0; i < indexCount; i += 3 ) {
  18851. if ( indexAttr ) {
  18852. indexArr[ 0 ] = indexAttr.getX( i );
  18853. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18854. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18855. } else {
  18856. indexArr[ 0 ] = i;
  18857. indexArr[ 1 ] = i + 1;
  18858. indexArr[ 2 ] = i + 2;
  18859. }
  18860. const { a, b, c } = _triangle;
  18861. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18862. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18863. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18864. _triangle.getNormal( _normal );
  18865. // create hashes for the edge from the vertices
  18866. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18867. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18868. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18869. // skip degenerate triangles
  18870. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18871. continue;
  18872. }
  18873. // iterate over every edge
  18874. for ( let j = 0; j < 3; j ++ ) {
  18875. // get the first and next vertex making up the edge
  18876. const jNext = ( j + 1 ) % 3;
  18877. const vecHash0 = hashes[ j ];
  18878. const vecHash1 = hashes[ jNext ];
  18879. const v0 = _triangle[ vertKeys[ j ] ];
  18880. const v1 = _triangle[ vertKeys[ jNext ] ];
  18881. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18882. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18883. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18884. // if we found a sibling edge add it into the vertex array if
  18885. // it meets the angle threshold and delete the edge from the map.
  18886. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18887. vertices.push( v0.x, v0.y, v0.z );
  18888. vertices.push( v1.x, v1.y, v1.z );
  18889. }
  18890. edgeData[ reverseHash ] = null;
  18891. } else if ( ! ( hash in edgeData ) ) {
  18892. // if we've already got an edge here then skip adding a new one
  18893. edgeData[ hash ] = {
  18894. index0: indexArr[ j ],
  18895. index1: indexArr[ jNext ],
  18896. normal: _normal.clone(),
  18897. };
  18898. }
  18899. }
  18900. }
  18901. // iterate over all remaining, unmatched edges and add them to the vertex array
  18902. for ( const key in edgeData ) {
  18903. if ( edgeData[ key ] ) {
  18904. const { index0, index1 } = edgeData[ key ];
  18905. _v0$1.fromBufferAttribute( positionAttr, index0 );
  18906. _v1$1.fromBufferAttribute( positionAttr, index1 );
  18907. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  18908. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  18909. }
  18910. }
  18911. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18912. }
  18913. }
  18914. copy( source ) {
  18915. super.copy( source );
  18916. this.parameters = Object.assign( {}, source.parameters );
  18917. return this;
  18918. }
  18919. }
  18920. /**
  18921. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  18922. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  18923. * points, or to get triangulated faces.
  18924. *
  18925. * ```js
  18926. * const heartShape = new THREE.Shape();
  18927. *
  18928. * heartShape.moveTo( 25, 25 );
  18929. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  18930. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  18931. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  18932. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  18933. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  18934. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  18935. *
  18936. * const extrudeSettings = {
  18937. * depth: 8,
  18938. * bevelEnabled: true,
  18939. * bevelSegments: 2,
  18940. * steps: 2,
  18941. * bevelSize: 1,
  18942. * bevelThickness: 1
  18943. * };
  18944. *
  18945. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  18946. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  18947. * ```
  18948. *
  18949. * @augments Path
  18950. */
  18951. class Shape extends Path {
  18952. /**
  18953. * Constructs a new shape.
  18954. *
  18955. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  18956. */
  18957. constructor( points ) {
  18958. super( points );
  18959. /**
  18960. * The UUID of the shape.
  18961. *
  18962. * @type {string}
  18963. * @readonly
  18964. */
  18965. this.uuid = generateUUID();
  18966. this.type = 'Shape';
  18967. /**
  18968. * Defines the holes in the shape. Hole defnitions must use the
  18969. * opposite winding order (CW/CCW) than the outer shape.
  18970. *
  18971. * @type {Array<Path>}
  18972. * @readonly
  18973. */
  18974. this.holes = [];
  18975. }
  18976. /**
  18977. * Returns an array representing each contour of the holes
  18978. * as a list of 2D points.
  18979. *
  18980. * @param {number} divisions - The fineness of the result.
  18981. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  18982. */
  18983. getPointsHoles( divisions ) {
  18984. const holesPts = [];
  18985. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  18986. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  18987. }
  18988. return holesPts;
  18989. }
  18990. // get points of shape and holes (keypoints based on segments parameter)
  18991. /**
  18992. * Returns an object that holds contour data for the shape and its holes as
  18993. * arrays of 2D points.
  18994. *
  18995. * @param {number} divisions - The fineness of the result.
  18996. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  18997. */
  18998. extractPoints( divisions ) {
  18999. return {
  19000. shape: this.getPoints( divisions ),
  19001. holes: this.getPointsHoles( divisions )
  19002. };
  19003. }
  19004. copy( source ) {
  19005. super.copy( source );
  19006. this.holes = [];
  19007. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  19008. const hole = source.holes[ i ];
  19009. this.holes.push( hole.clone() );
  19010. }
  19011. return this;
  19012. }
  19013. toJSON() {
  19014. const data = super.toJSON();
  19015. data.uuid = this.uuid;
  19016. data.holes = [];
  19017. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19018. const hole = this.holes[ i ];
  19019. data.holes.push( hole.toJSON() );
  19020. }
  19021. return data;
  19022. }
  19023. fromJSON( json ) {
  19024. super.fromJSON( json );
  19025. this.uuid = json.uuid;
  19026. this.holes = [];
  19027. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  19028. const hole = json.holes[ i ];
  19029. this.holes.push( new Path().fromJSON( hole ) );
  19030. }
  19031. return this;
  19032. }
  19033. }
  19034. /**
  19035. * An implementation of the earcut polygon triangulation algorithm. The code
  19036. * is a port of [mapbox/earcut]{@link https://github.com/mapbox/earcut mapbox/earcut} (v2.2.4).
  19037. *
  19038. * @hideconstructor
  19039. */
  19040. class Earcut {
  19041. /**
  19042. * Triangulates the given shape definition by returning an array of triangles.
  19043. *
  19044. * @param {Array<number>} data - An array with 2D points.
  19045. * @param {Array<number>} holeIndices - An array with indices defining holes.
  19046. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  19047. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  19048. * representing vertex indices.
  19049. */
  19050. static triangulate( data, holeIndices, dim = 2 ) {
  19051. const hasHoles = holeIndices && holeIndices.length;
  19052. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  19053. let outerNode = linkedList( data, 0, outerLen, dim, true );
  19054. const triangles = [];
  19055. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  19056. let minX, minY, maxX, maxY, x, y, invSize;
  19057. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  19058. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19059. if ( data.length > 80 * dim ) {
  19060. minX = maxX = data[ 0 ];
  19061. minY = maxY = data[ 1 ];
  19062. for ( let i = dim; i < outerLen; i += dim ) {
  19063. x = data[ i ];
  19064. y = data[ i + 1 ];
  19065. if ( x < minX ) minX = x;
  19066. if ( y < minY ) minY = y;
  19067. if ( x > maxX ) maxX = x;
  19068. if ( y > maxY ) maxY = y;
  19069. }
  19070. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19071. invSize = Math.max( maxX - minX, maxY - minY );
  19072. invSize = invSize !== 0 ? 32767 / invSize : 0;
  19073. }
  19074. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  19075. return triangles;
  19076. }
  19077. }
  19078. // create a circular doubly linked list from polygon points in the specified winding order
  19079. function linkedList( data, start, end, dim, clockwise ) {
  19080. let i, last;
  19081. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  19082. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19083. } else {
  19084. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19085. }
  19086. if ( last && equals( last, last.next ) ) {
  19087. removeNode( last );
  19088. last = last.next;
  19089. }
  19090. return last;
  19091. }
  19092. // eliminate colinear or duplicate points
  19093. function filterPoints( start, end ) {
  19094. if ( ! start ) return start;
  19095. if ( ! end ) end = start;
  19096. let p = start,
  19097. again;
  19098. do {
  19099. again = false;
  19100. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  19101. removeNode( p );
  19102. p = end = p.prev;
  19103. if ( p === p.next ) break;
  19104. again = true;
  19105. } else {
  19106. p = p.next;
  19107. }
  19108. } while ( again || p !== end );
  19109. return end;
  19110. }
  19111. // main ear slicing loop which triangulates a polygon (given as a linked list)
  19112. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  19113. if ( ! ear ) return;
  19114. // interlink polygon nodes in z-order
  19115. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  19116. let stop = ear,
  19117. prev, next;
  19118. // iterate through ears, slicing them one by one
  19119. while ( ear.prev !== ear.next ) {
  19120. prev = ear.prev;
  19121. next = ear.next;
  19122. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  19123. // cut off the triangle
  19124. triangles.push( prev.i / dim | 0 );
  19125. triangles.push( ear.i / dim | 0 );
  19126. triangles.push( next.i / dim | 0 );
  19127. removeNode( ear );
  19128. // skipping the next vertex leads to less sliver triangles
  19129. ear = next.next;
  19130. stop = next.next;
  19131. continue;
  19132. }
  19133. ear = next;
  19134. // if we looped through the whole remaining polygon and can't find any more ears
  19135. if ( ear === stop ) {
  19136. // try filtering points and slicing again
  19137. if ( ! pass ) {
  19138. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  19139. // if this didn't work, try curing all small self-intersections locally
  19140. } else if ( pass === 1 ) {
  19141. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  19142. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  19143. // as a last resort, try splitting the remaining polygon into two
  19144. } else if ( pass === 2 ) {
  19145. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  19146. }
  19147. break;
  19148. }
  19149. }
  19150. }
  19151. // check whether a polygon node forms a valid ear with adjacent nodes
  19152. function isEar( ear ) {
  19153. const a = ear.prev,
  19154. b = ear,
  19155. c = ear.next;
  19156. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19157. // now make sure we don't have other points inside the potential ear
  19158. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  19159. // triangle bbox; min & max are calculated like this for speed
  19160. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  19161. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  19162. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  19163. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  19164. let p = c.next;
  19165. while ( p !== a ) {
  19166. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  19167. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  19168. area( p.prev, p, p.next ) >= 0 ) return false;
  19169. p = p.next;
  19170. }
  19171. return true;
  19172. }
  19173. function isEarHashed( ear, minX, minY, invSize ) {
  19174. const a = ear.prev,
  19175. b = ear,
  19176. c = ear.next;
  19177. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19178. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  19179. // triangle bbox; min & max are calculated like this for speed
  19180. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  19181. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  19182. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  19183. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  19184. // z-order range for the current triangle bbox;
  19185. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  19186. maxZ = zOrder( x1, y1, minX, minY, invSize );
  19187. let p = ear.prevZ,
  19188. n = ear.nextZ;
  19189. // look for points inside the triangle in both directions
  19190. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19191. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  19192. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  19193. p = p.prevZ;
  19194. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  19195. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  19196. n = n.nextZ;
  19197. }
  19198. // look for remaining points in decreasing z-order
  19199. while ( p && p.z >= minZ ) {
  19200. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  19201. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  19202. p = p.prevZ;
  19203. }
  19204. // look for remaining points in increasing z-order
  19205. while ( n && n.z <= maxZ ) {
  19206. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  19207. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  19208. n = n.nextZ;
  19209. }
  19210. return true;
  19211. }
  19212. // go through all polygon nodes and cure small local self-intersections
  19213. function cureLocalIntersections( start, triangles, dim ) {
  19214. let p = start;
  19215. do {
  19216. const a = p.prev,
  19217. b = p.next.next;
  19218. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  19219. triangles.push( a.i / dim | 0 );
  19220. triangles.push( p.i / dim | 0 );
  19221. triangles.push( b.i / dim | 0 );
  19222. // remove two nodes involved
  19223. removeNode( p );
  19224. removeNode( p.next );
  19225. p = start = b;
  19226. }
  19227. p = p.next;
  19228. } while ( p !== start );
  19229. return filterPoints( p );
  19230. }
  19231. // try splitting polygon into two and triangulate them independently
  19232. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  19233. // look for a valid diagonal that divides the polygon into two
  19234. let a = start;
  19235. do {
  19236. let b = a.next.next;
  19237. while ( b !== a.prev ) {
  19238. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  19239. // split the polygon in two by the diagonal
  19240. let c = splitPolygon( a, b );
  19241. // filter colinear points around the cuts
  19242. a = filterPoints( a, a.next );
  19243. c = filterPoints( c, c.next );
  19244. // run earcut on each half
  19245. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  19246. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  19247. return;
  19248. }
  19249. b = b.next;
  19250. }
  19251. a = a.next;
  19252. } while ( a !== start );
  19253. }
  19254. // link every hole into the outer loop, producing a single-ring polygon without holes
  19255. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  19256. const queue = [];
  19257. let i, len, start, end, list;
  19258. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  19259. start = holeIndices[ i ] * dim;
  19260. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  19261. list = linkedList( data, start, end, dim, false );
  19262. if ( list === list.next ) list.steiner = true;
  19263. queue.push( getLeftmost( list ) );
  19264. }
  19265. queue.sort( compareX );
  19266. // process holes from left to right
  19267. for ( i = 0; i < queue.length; i ++ ) {
  19268. outerNode = eliminateHole( queue[ i ], outerNode );
  19269. }
  19270. return outerNode;
  19271. }
  19272. function compareX( a, b ) {
  19273. return a.x - b.x;
  19274. }
  19275. // find a bridge between vertices that connects hole with an outer ring and link it
  19276. function eliminateHole( hole, outerNode ) {
  19277. const bridge = findHoleBridge( hole, outerNode );
  19278. if ( ! bridge ) {
  19279. return outerNode;
  19280. }
  19281. const bridgeReverse = splitPolygon( bridge, hole );
  19282. // filter collinear points around the cuts
  19283. filterPoints( bridgeReverse, bridgeReverse.next );
  19284. return filterPoints( bridge, bridge.next );
  19285. }
  19286. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19287. function findHoleBridge( hole, outerNode ) {
  19288. let p = outerNode,
  19289. qx = - Infinity,
  19290. m;
  19291. const hx = hole.x, hy = hole.y;
  19292. // find a segment intersected by a ray from the hole's leftmost point to the left;
  19293. // segment's endpoint with lesser x will be potential connection point
  19294. do {
  19295. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  19296. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  19297. if ( x <= hx && x > qx ) {
  19298. qx = x;
  19299. m = p.x < p.next.x ? p : p.next;
  19300. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  19301. }
  19302. }
  19303. p = p.next;
  19304. } while ( p !== outerNode );
  19305. if ( ! m ) return null;
  19306. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19307. // if there are no points found, we have a valid connection;
  19308. // otherwise choose the point of the minimum angle with the ray as connection point
  19309. const stop = m,
  19310. mx = m.x,
  19311. my = m.y;
  19312. let tanMin = Infinity, tan;
  19313. p = m;
  19314. do {
  19315. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  19316. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  19317. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  19318. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  19319. m = p;
  19320. tanMin = tan;
  19321. }
  19322. }
  19323. p = p.next;
  19324. } while ( p !== stop );
  19325. return m;
  19326. }
  19327. // whether sector in vertex m contains sector in vertex p in the same coordinates
  19328. function sectorContainsSector( m, p ) {
  19329. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  19330. }
  19331. // interlink polygon nodes in z-order
  19332. function indexCurve( start, minX, minY, invSize ) {
  19333. let p = start;
  19334. do {
  19335. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  19336. p.prevZ = p.prev;
  19337. p.nextZ = p.next;
  19338. p = p.next;
  19339. } while ( p !== start );
  19340. p.prevZ.nextZ = null;
  19341. p.prevZ = null;
  19342. sortLinked( p );
  19343. }
  19344. // Simon Tatham's linked list merge sort algorithm
  19345. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19346. function sortLinked( list ) {
  19347. let i, p, q, e, tail, numMerges, pSize, qSize,
  19348. inSize = 1;
  19349. do {
  19350. p = list;
  19351. list = null;
  19352. tail = null;
  19353. numMerges = 0;
  19354. while ( p ) {
  19355. numMerges ++;
  19356. q = p;
  19357. pSize = 0;
  19358. for ( i = 0; i < inSize; i ++ ) {
  19359. pSize ++;
  19360. q = q.nextZ;
  19361. if ( ! q ) break;
  19362. }
  19363. qSize = inSize;
  19364. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  19365. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  19366. e = p;
  19367. p = p.nextZ;
  19368. pSize --;
  19369. } else {
  19370. e = q;
  19371. q = q.nextZ;
  19372. qSize --;
  19373. }
  19374. if ( tail ) tail.nextZ = e;
  19375. else list = e;
  19376. e.prevZ = tail;
  19377. tail = e;
  19378. }
  19379. p = q;
  19380. }
  19381. tail.nextZ = null;
  19382. inSize *= 2;
  19383. } while ( numMerges > 1 );
  19384. return list;
  19385. }
  19386. // z-order of a point given coords and inverse of the longer side of data bbox
  19387. function zOrder( x, y, minX, minY, invSize ) {
  19388. // coords are transformed into non-negative 15-bit integer range
  19389. x = ( x - minX ) * invSize | 0;
  19390. y = ( y - minY ) * invSize | 0;
  19391. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  19392. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  19393. x = ( x | ( x << 2 ) ) & 0x33333333;
  19394. x = ( x | ( x << 1 ) ) & 0x55555555;
  19395. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  19396. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  19397. y = ( y | ( y << 2 ) ) & 0x33333333;
  19398. y = ( y | ( y << 1 ) ) & 0x55555555;
  19399. return x | ( y << 1 );
  19400. }
  19401. // find the leftmost node of a polygon ring
  19402. function getLeftmost( start ) {
  19403. let p = start,
  19404. leftmost = start;
  19405. do {
  19406. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  19407. p = p.next;
  19408. } while ( p !== start );
  19409. return leftmost;
  19410. }
  19411. // check if a point lies within a convex triangle
  19412. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  19413. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  19414. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  19415. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  19416. }
  19417. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19418. function isValidDiagonal( a, b ) {
  19419. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  19420. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  19421. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  19422. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  19423. }
  19424. // signed area of a triangle
  19425. function area( p, q, r ) {
  19426. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  19427. }
  19428. // check if two points are equal
  19429. function equals( p1, p2 ) {
  19430. return p1.x === p2.x && p1.y === p2.y;
  19431. }
  19432. // check if two segments intersect
  19433. function intersects( p1, q1, p2, q2 ) {
  19434. const o1 = sign( area( p1, q1, p2 ) );
  19435. const o2 = sign( area( p1, q1, q2 ) );
  19436. const o3 = sign( area( p2, q2, p1 ) );
  19437. const o4 = sign( area( p2, q2, q1 ) );
  19438. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  19439. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19440. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19441. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19442. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19443. return false;
  19444. }
  19445. // for collinear points p, q, r, check if point q lies on segment pr
  19446. function onSegment( p, q, r ) {
  19447. 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 );
  19448. }
  19449. function sign( num ) {
  19450. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19451. }
  19452. // check if a polygon diagonal intersects any polygon segments
  19453. function intersectsPolygon( a, b ) {
  19454. let p = a;
  19455. do {
  19456. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  19457. intersects( p, p.next, a, b ) ) return true;
  19458. p = p.next;
  19459. } while ( p !== a );
  19460. return false;
  19461. }
  19462. // check if a polygon diagonal is locally inside the polygon
  19463. function locallyInside( a, b ) {
  19464. return area( a.prev, a, a.next ) < 0 ?
  19465. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  19466. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  19467. }
  19468. // check if the middle point of a polygon diagonal is inside the polygon
  19469. function middleInside( a, b ) {
  19470. let p = a,
  19471. inside = false;
  19472. const px = ( a.x + b.x ) / 2,
  19473. py = ( a.y + b.y ) / 2;
  19474. do {
  19475. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  19476. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  19477. inside = ! inside;
  19478. p = p.next;
  19479. } while ( p !== a );
  19480. return inside;
  19481. }
  19482. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19483. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19484. function splitPolygon( a, b ) {
  19485. const a2 = new Node( a.i, a.x, a.y ),
  19486. b2 = new Node( b.i, b.x, b.y ),
  19487. an = a.next,
  19488. bp = b.prev;
  19489. a.next = b;
  19490. b.prev = a;
  19491. a2.next = an;
  19492. an.prev = a2;
  19493. b2.next = a2;
  19494. a2.prev = b2;
  19495. bp.next = b2;
  19496. b2.prev = bp;
  19497. return b2;
  19498. }
  19499. // create a node and optionally link it with previous one (in a circular doubly linked list)
  19500. function insertNode( i, x, y, last ) {
  19501. const p = new Node( i, x, y );
  19502. if ( ! last ) {
  19503. p.prev = p;
  19504. p.next = p;
  19505. } else {
  19506. p.next = last.next;
  19507. p.prev = last;
  19508. last.next.prev = p;
  19509. last.next = p;
  19510. }
  19511. return p;
  19512. }
  19513. function removeNode( p ) {
  19514. p.next.prev = p.prev;
  19515. p.prev.next = p.next;
  19516. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  19517. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  19518. }
  19519. function Node( i, x, y ) {
  19520. // vertex index in coordinates array
  19521. this.i = i;
  19522. // vertex coordinates
  19523. this.x = x;
  19524. this.y = y;
  19525. // previous and next vertex nodes in a polygon ring
  19526. this.prev = null;
  19527. this.next = null;
  19528. // z-order curve value
  19529. this.z = 0;
  19530. // previous and next nodes in z-order
  19531. this.prevZ = null;
  19532. this.nextZ = null;
  19533. // indicates whether this is a steiner point
  19534. this.steiner = false;
  19535. }
  19536. function signedArea( data, start, end, dim ) {
  19537. let sum = 0;
  19538. for ( let i = start, j = end - dim; i < end; i += dim ) {
  19539. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  19540. j = i;
  19541. }
  19542. return sum;
  19543. }
  19544. /**
  19545. * A class containing utility functions for shapes.
  19546. *
  19547. * @hideconstructor
  19548. */
  19549. class ShapeUtils {
  19550. /**
  19551. * Calculate area of a ( 2D ) contour polygon.
  19552. *
  19553. * @param {Array<Vector2>} contour - An array of 2D points.
  19554. * @return {number} The area.
  19555. */
  19556. static area( contour ) {
  19557. const n = contour.length;
  19558. let a = 0.0;
  19559. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  19560. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19561. }
  19562. return a * 0.5;
  19563. }
  19564. /**
  19565. * Returns `true` if the given contour uses a clockwise winding order.
  19566. *
  19567. * @param {Array<Vector2>} pts - An array of 2D points defining a polyong.
  19568. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  19569. */
  19570. static isClockWise( pts ) {
  19571. return ShapeUtils.area( pts ) < 0;
  19572. }
  19573. /**
  19574. * Triangluates the given shape definition.
  19575. *
  19576. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  19577. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  19578. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  19579. */
  19580. static triangulateShape( contour, holes ) {
  19581. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19582. const holeIndices = []; // array of hole indices
  19583. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19584. removeDupEndPts( contour );
  19585. addContour( vertices, contour );
  19586. //
  19587. let holeIndex = contour.length;
  19588. holes.forEach( removeDupEndPts );
  19589. for ( let i = 0; i < holes.length; i ++ ) {
  19590. holeIndices.push( holeIndex );
  19591. holeIndex += holes[ i ].length;
  19592. addContour( vertices, holes[ i ] );
  19593. }
  19594. //
  19595. const triangles = Earcut.triangulate( vertices, holeIndices );
  19596. //
  19597. for ( let i = 0; i < triangles.length; i += 3 ) {
  19598. faces.push( triangles.slice( i, i + 3 ) );
  19599. }
  19600. return faces;
  19601. }
  19602. }
  19603. function removeDupEndPts( points ) {
  19604. const l = points.length;
  19605. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19606. points.pop();
  19607. }
  19608. }
  19609. function addContour( vertices, contour ) {
  19610. for ( let i = 0; i < contour.length; i ++ ) {
  19611. vertices.push( contour[ i ].x );
  19612. vertices.push( contour[ i ].y );
  19613. }
  19614. }
  19615. /**
  19616. * Creates extruded geometry from a path shape.
  19617. *
  19618. * parameters = {
  19619. *
  19620. * curveSegments: <int>, // number of points on the curves
  19621. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19622. * depth: <float>, // Depth to extrude the shape
  19623. *
  19624. * bevelEnabled: <bool>, // turn on bevel
  19625. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19626. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19627. * bevelOffset: <float>, // how far from shape outline does bevel start
  19628. * bevelSegments: <int>, // number of bevel layers
  19629. *
  19630. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19631. *
  19632. * UVGenerator: <Object> // object that provides UV generator functions
  19633. *
  19634. * }
  19635. */
  19636. class ExtrudeGeometry extends BufferGeometry {
  19637. 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 = {} ) {
  19638. super();
  19639. this.type = 'ExtrudeGeometry';
  19640. this.parameters = {
  19641. shapes: shapes,
  19642. options: options
  19643. };
  19644. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19645. const scope = this;
  19646. const verticesArray = [];
  19647. const uvArray = [];
  19648. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19649. const shape = shapes[ i ];
  19650. addShape( shape );
  19651. }
  19652. // build geometry
  19653. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  19654. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  19655. this.computeVertexNormals();
  19656. // functions
  19657. function addShape( shape ) {
  19658. const placeholder = [];
  19659. // options
  19660. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19661. const steps = options.steps !== undefined ? options.steps : 1;
  19662. const depth = options.depth !== undefined ? options.depth : 1;
  19663. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19664. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  19665. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  19666. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19667. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19668. const extrudePath = options.extrudePath;
  19669. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19670. //
  19671. let extrudePts, extrudeByPath = false;
  19672. let splineTube, binormal, normal, position2;
  19673. if ( extrudePath ) {
  19674. extrudePts = extrudePath.getSpacedPoints( steps );
  19675. extrudeByPath = true;
  19676. bevelEnabled = false; // bevels not supported for path extrusion
  19677. // SETUP TNB variables
  19678. // TODO1 - have a .isClosed in spline?
  19679. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19680. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19681. binormal = new Vector3();
  19682. normal = new Vector3();
  19683. position2 = new Vector3();
  19684. }
  19685. // Safeguards if bevels are not enabled
  19686. if ( ! bevelEnabled ) {
  19687. bevelSegments = 0;
  19688. bevelThickness = 0;
  19689. bevelSize = 0;
  19690. bevelOffset = 0;
  19691. }
  19692. // Variables initialization
  19693. const shapePoints = shape.extractPoints( curveSegments );
  19694. let vertices = shapePoints.shape;
  19695. const holes = shapePoints.holes;
  19696. const reverse = ! ShapeUtils.isClockWise( vertices );
  19697. if ( reverse ) {
  19698. vertices = vertices.reverse();
  19699. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19700. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19701. const ahole = holes[ h ];
  19702. if ( ShapeUtils.isClockWise( ahole ) ) {
  19703. holes[ h ] = ahole.reverse();
  19704. }
  19705. }
  19706. }
  19707. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19708. /* Vertices */
  19709. const contour = vertices; // vertices has all points but contour has only points of circumference
  19710. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19711. const ahole = holes[ h ];
  19712. vertices = vertices.concat( ahole );
  19713. }
  19714. function scalePt2( pt, vec, size ) {
  19715. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19716. return pt.clone().addScaledVector( vec, size );
  19717. }
  19718. const vlen = vertices.length, flen = faces.length;
  19719. // Find directions for point movement
  19720. function getBevelVec( inPt, inPrev, inNext ) {
  19721. // computes for inPt the corresponding point inPt' on a new contour
  19722. // shifted by 1 unit (length of normalized vector) to the left
  19723. // if we walk along contour clockwise, this new contour is outside the old one
  19724. //
  19725. // inPt' is the intersection of the two lines parallel to the two
  19726. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19727. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19728. // good reading for geometry algorithms (here: line-line intersection)
  19729. // http://geomalgorithms.com/a05-_intersect-1.html
  19730. const v_prev_x = inPt.x - inPrev.x,
  19731. v_prev_y = inPt.y - inPrev.y;
  19732. const v_next_x = inNext.x - inPt.x,
  19733. v_next_y = inNext.y - inPt.y;
  19734. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19735. // check for collinear edges
  19736. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19737. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19738. // not collinear
  19739. // length of vectors for normalizing
  19740. const v_prev_len = Math.sqrt( v_prev_lensq );
  19741. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19742. // shift adjacent points by unit vectors to the left
  19743. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19744. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19745. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19746. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19747. // scaling factor for v_prev to intersection point
  19748. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19749. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19750. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19751. // vector from inPt to intersection point
  19752. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19753. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19754. // Don't normalize!, otherwise sharp corners become ugly
  19755. // but prevent crazy spikes
  19756. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19757. if ( v_trans_lensq <= 2 ) {
  19758. return new Vector2( v_trans_x, v_trans_y );
  19759. } else {
  19760. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19761. }
  19762. } else {
  19763. // handle special case of collinear edges
  19764. let direction_eq = false; // assumes: opposite
  19765. if ( v_prev_x > Number.EPSILON ) {
  19766. if ( v_next_x > Number.EPSILON ) {
  19767. direction_eq = true;
  19768. }
  19769. } else {
  19770. if ( v_prev_x < - Number.EPSILON ) {
  19771. if ( v_next_x < - Number.EPSILON ) {
  19772. direction_eq = true;
  19773. }
  19774. } else {
  19775. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19776. direction_eq = true;
  19777. }
  19778. }
  19779. }
  19780. if ( direction_eq ) {
  19781. // console.log("Warning: lines are a straight sequence");
  19782. v_trans_x = - v_prev_y;
  19783. v_trans_y = v_prev_x;
  19784. shrink_by = Math.sqrt( v_prev_lensq );
  19785. } else {
  19786. // console.log("Warning: lines are a straight spike");
  19787. v_trans_x = v_prev_x;
  19788. v_trans_y = v_prev_y;
  19789. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19790. }
  19791. }
  19792. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19793. }
  19794. const contourMovements = [];
  19795. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19796. if ( j === il ) j = 0;
  19797. if ( k === il ) k = 0;
  19798. // (j)---(i)---(k)
  19799. // console.log('i,j,k', i, j , k)
  19800. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19801. }
  19802. const holesMovements = [];
  19803. let oneHoleMovements, verticesMovements = contourMovements.concat();
  19804. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19805. const ahole = holes[ h ];
  19806. oneHoleMovements = [];
  19807. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19808. if ( j === il ) j = 0;
  19809. if ( k === il ) k = 0;
  19810. // (j)---(i)---(k)
  19811. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19812. }
  19813. holesMovements.push( oneHoleMovements );
  19814. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19815. }
  19816. // Loop bevelSegments, 1 for the front, 1 for the back
  19817. for ( let b = 0; b < bevelSegments; b ++ ) {
  19818. //for ( b = bevelSegments; b > 0; b -- ) {
  19819. const t = b / bevelSegments;
  19820. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19821. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19822. // contract shape
  19823. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19824. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19825. v( vert.x, vert.y, - z );
  19826. }
  19827. // expand holes
  19828. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19829. const ahole = holes[ h ];
  19830. oneHoleMovements = holesMovements[ h ];
  19831. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19832. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19833. v( vert.x, vert.y, - z );
  19834. }
  19835. }
  19836. }
  19837. const bs = bevelSize + bevelOffset;
  19838. // Back facing vertices
  19839. for ( let i = 0; i < vlen; i ++ ) {
  19840. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19841. if ( ! extrudeByPath ) {
  19842. v( vert.x, vert.y, 0 );
  19843. } else {
  19844. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19845. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19846. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19847. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19848. v( position2.x, position2.y, position2.z );
  19849. }
  19850. }
  19851. // Add stepped vertices...
  19852. // Including front facing vertices
  19853. for ( let s = 1; s <= steps; s ++ ) {
  19854. for ( let i = 0; i < vlen; i ++ ) {
  19855. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19856. if ( ! extrudeByPath ) {
  19857. v( vert.x, vert.y, depth / steps * s );
  19858. } else {
  19859. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19860. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19861. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19862. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19863. v( position2.x, position2.y, position2.z );
  19864. }
  19865. }
  19866. }
  19867. // Add bevel segments planes
  19868. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19869. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  19870. const t = b / bevelSegments;
  19871. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19872. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19873. // contract shape
  19874. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19875. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19876. v( vert.x, vert.y, depth + z );
  19877. }
  19878. // expand holes
  19879. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19880. const ahole = holes[ h ];
  19881. oneHoleMovements = holesMovements[ h ];
  19882. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19883. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19884. if ( ! extrudeByPath ) {
  19885. v( vert.x, vert.y, depth + z );
  19886. } else {
  19887. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19888. }
  19889. }
  19890. }
  19891. }
  19892. /* Faces */
  19893. // Top and bottom faces
  19894. buildLidFaces();
  19895. // Sides faces
  19896. buildSideFaces();
  19897. ///// Internal functions
  19898. function buildLidFaces() {
  19899. const start = verticesArray.length / 3;
  19900. if ( bevelEnabled ) {
  19901. let layer = 0; // steps + 1
  19902. let offset = vlen * layer;
  19903. // Bottom faces
  19904. for ( let i = 0; i < flen; i ++ ) {
  19905. const face = faces[ i ];
  19906. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19907. }
  19908. layer = steps + bevelSegments * 2;
  19909. offset = vlen * layer;
  19910. // Top faces
  19911. for ( let i = 0; i < flen; i ++ ) {
  19912. const face = faces[ i ];
  19913. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19914. }
  19915. } else {
  19916. // Bottom faces
  19917. for ( let i = 0; i < flen; i ++ ) {
  19918. const face = faces[ i ];
  19919. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19920. }
  19921. // Top faces
  19922. for ( let i = 0; i < flen; i ++ ) {
  19923. const face = faces[ i ];
  19924. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19925. }
  19926. }
  19927. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  19928. }
  19929. // Create faces for the z-sides of the shape
  19930. function buildSideFaces() {
  19931. const start = verticesArray.length / 3;
  19932. let layeroffset = 0;
  19933. sidewalls( contour, layeroffset );
  19934. layeroffset += contour.length;
  19935. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19936. const ahole = holes[ h ];
  19937. sidewalls( ahole, layeroffset );
  19938. //, true
  19939. layeroffset += ahole.length;
  19940. }
  19941. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  19942. }
  19943. function sidewalls( contour, layeroffset ) {
  19944. let i = contour.length;
  19945. while ( -- i >= 0 ) {
  19946. const j = i;
  19947. let k = i - 1;
  19948. if ( k < 0 ) k = contour.length - 1;
  19949. //console.log('b', i,j, i-1, k,vertices.length);
  19950. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  19951. const slen1 = vlen * s;
  19952. const slen2 = vlen * ( s + 1 );
  19953. const a = layeroffset + j + slen1,
  19954. b = layeroffset + k + slen1,
  19955. c = layeroffset + k + slen2,
  19956. d = layeroffset + j + slen2;
  19957. f4( a, b, c, d );
  19958. }
  19959. }
  19960. }
  19961. function v( x, y, z ) {
  19962. placeholder.push( x );
  19963. placeholder.push( y );
  19964. placeholder.push( z );
  19965. }
  19966. function f3( a, b, c ) {
  19967. addVertex( a );
  19968. addVertex( b );
  19969. addVertex( c );
  19970. const nextIndex = verticesArray.length / 3;
  19971. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19972. addUV( uvs[ 0 ] );
  19973. addUV( uvs[ 1 ] );
  19974. addUV( uvs[ 2 ] );
  19975. }
  19976. function f4( a, b, c, d ) {
  19977. addVertex( a );
  19978. addVertex( b );
  19979. addVertex( d );
  19980. addVertex( b );
  19981. addVertex( c );
  19982. addVertex( d );
  19983. const nextIndex = verticesArray.length / 3;
  19984. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19985. addUV( uvs[ 0 ] );
  19986. addUV( uvs[ 1 ] );
  19987. addUV( uvs[ 3 ] );
  19988. addUV( uvs[ 1 ] );
  19989. addUV( uvs[ 2 ] );
  19990. addUV( uvs[ 3 ] );
  19991. }
  19992. function addVertex( index ) {
  19993. verticesArray.push( placeholder[ index * 3 + 0 ] );
  19994. verticesArray.push( placeholder[ index * 3 + 1 ] );
  19995. verticesArray.push( placeholder[ index * 3 + 2 ] );
  19996. }
  19997. function addUV( vector2 ) {
  19998. uvArray.push( vector2.x );
  19999. uvArray.push( vector2.y );
  20000. }
  20001. }
  20002. }
  20003. copy( source ) {
  20004. super.copy( source );
  20005. this.parameters = Object.assign( {}, source.parameters );
  20006. return this;
  20007. }
  20008. toJSON() {
  20009. const data = super.toJSON();
  20010. const shapes = this.parameters.shapes;
  20011. const options = this.parameters.options;
  20012. return toJSON$1( shapes, options, data );
  20013. }
  20014. static fromJSON( data, shapes ) {
  20015. const geometryShapes = [];
  20016. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20017. const shape = shapes[ data.shapes[ j ] ];
  20018. geometryShapes.push( shape );
  20019. }
  20020. const extrudePath = data.options.extrudePath;
  20021. if ( extrudePath !== undefined ) {
  20022. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20023. }
  20024. return new ExtrudeGeometry( geometryShapes, data.options );
  20025. }
  20026. }
  20027. const WorldUVGenerator = {
  20028. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20029. const a_x = vertices[ indexA * 3 ];
  20030. const a_y = vertices[ indexA * 3 + 1 ];
  20031. const b_x = vertices[ indexB * 3 ];
  20032. const b_y = vertices[ indexB * 3 + 1 ];
  20033. const c_x = vertices[ indexC * 3 ];
  20034. const c_y = vertices[ indexC * 3 + 1 ];
  20035. return [
  20036. new Vector2( a_x, a_y ),
  20037. new Vector2( b_x, b_y ),
  20038. new Vector2( c_x, c_y )
  20039. ];
  20040. },
  20041. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20042. const a_x = vertices[ indexA * 3 ];
  20043. const a_y = vertices[ indexA * 3 + 1 ];
  20044. const a_z = vertices[ indexA * 3 + 2 ];
  20045. const b_x = vertices[ indexB * 3 ];
  20046. const b_y = vertices[ indexB * 3 + 1 ];
  20047. const b_z = vertices[ indexB * 3 + 2 ];
  20048. const c_x = vertices[ indexC * 3 ];
  20049. const c_y = vertices[ indexC * 3 + 1 ];
  20050. const c_z = vertices[ indexC * 3 + 2 ];
  20051. const d_x = vertices[ indexD * 3 ];
  20052. const d_y = vertices[ indexD * 3 + 1 ];
  20053. const d_z = vertices[ indexD * 3 + 2 ];
  20054. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  20055. return [
  20056. new Vector2( a_x, 1 - a_z ),
  20057. new Vector2( b_x, 1 - b_z ),
  20058. new Vector2( c_x, 1 - c_z ),
  20059. new Vector2( d_x, 1 - d_z )
  20060. ];
  20061. } else {
  20062. return [
  20063. new Vector2( a_y, 1 - a_z ),
  20064. new Vector2( b_y, 1 - b_z ),
  20065. new Vector2( c_y, 1 - c_z ),
  20066. new Vector2( d_y, 1 - d_z )
  20067. ];
  20068. }
  20069. }
  20070. };
  20071. function toJSON$1( shapes, options, data ) {
  20072. data.shapes = [];
  20073. if ( Array.isArray( shapes ) ) {
  20074. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20075. const shape = shapes[ i ];
  20076. data.shapes.push( shape.uuid );
  20077. }
  20078. } else {
  20079. data.shapes.push( shapes.uuid );
  20080. }
  20081. data.options = Object.assign( {}, options );
  20082. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  20083. return data;
  20084. }
  20085. class IcosahedronGeometry extends PolyhedronGeometry {
  20086. constructor( radius = 1, detail = 0 ) {
  20087. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20088. const vertices = [
  20089. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  20090. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  20091. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  20092. ];
  20093. const indices = [
  20094. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20095. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20096. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20097. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20098. ];
  20099. super( vertices, indices, radius, detail );
  20100. this.type = 'IcosahedronGeometry';
  20101. this.parameters = {
  20102. radius: radius,
  20103. detail: detail
  20104. };
  20105. }
  20106. static fromJSON( data ) {
  20107. return new IcosahedronGeometry( data.radius, data.detail );
  20108. }
  20109. }
  20110. class OctahedronGeometry extends PolyhedronGeometry {
  20111. constructor( radius = 1, detail = 0 ) {
  20112. const vertices = [
  20113. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  20114. 0, -1, 0, 0, 0, 1, 0, 0, -1
  20115. ];
  20116. const indices = [
  20117. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20118. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20119. 1, 3, 4, 1, 4, 2
  20120. ];
  20121. super( vertices, indices, radius, detail );
  20122. this.type = 'OctahedronGeometry';
  20123. this.parameters = {
  20124. radius: radius,
  20125. detail: detail
  20126. };
  20127. }
  20128. static fromJSON( data ) {
  20129. return new OctahedronGeometry( data.radius, data.detail );
  20130. }
  20131. }
  20132. class PlaneGeometry extends BufferGeometry {
  20133. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  20134. super();
  20135. this.type = 'PlaneGeometry';
  20136. this.parameters = {
  20137. width: width,
  20138. height: height,
  20139. widthSegments: widthSegments,
  20140. heightSegments: heightSegments
  20141. };
  20142. const width_half = width / 2;
  20143. const height_half = height / 2;
  20144. const gridX = Math.floor( widthSegments );
  20145. const gridY = Math.floor( heightSegments );
  20146. const gridX1 = gridX + 1;
  20147. const gridY1 = gridY + 1;
  20148. const segment_width = width / gridX;
  20149. const segment_height = height / gridY;
  20150. //
  20151. const indices = [];
  20152. const vertices = [];
  20153. const normals = [];
  20154. const uvs = [];
  20155. for ( let iy = 0; iy < gridY1; iy ++ ) {
  20156. const y = iy * segment_height - height_half;
  20157. for ( let ix = 0; ix < gridX1; ix ++ ) {
  20158. const x = ix * segment_width - width_half;
  20159. vertices.push( x, - y, 0 );
  20160. normals.push( 0, 0, 1 );
  20161. uvs.push( ix / gridX );
  20162. uvs.push( 1 - ( iy / gridY ) );
  20163. }
  20164. }
  20165. for ( let iy = 0; iy < gridY; iy ++ ) {
  20166. for ( let ix = 0; ix < gridX; ix ++ ) {
  20167. const a = ix + gridX1 * iy;
  20168. const b = ix + gridX1 * ( iy + 1 );
  20169. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20170. const d = ( ix + 1 ) + gridX1 * iy;
  20171. indices.push( a, b, d );
  20172. indices.push( b, c, d );
  20173. }
  20174. }
  20175. this.setIndex( indices );
  20176. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20177. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20178. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20179. }
  20180. copy( source ) {
  20181. super.copy( source );
  20182. this.parameters = Object.assign( {}, source.parameters );
  20183. return this;
  20184. }
  20185. static fromJSON( data ) {
  20186. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  20187. }
  20188. }
  20189. class RingGeometry extends BufferGeometry {
  20190. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20191. super();
  20192. this.type = 'RingGeometry';
  20193. this.parameters = {
  20194. innerRadius: innerRadius,
  20195. outerRadius: outerRadius,
  20196. thetaSegments: thetaSegments,
  20197. phiSegments: phiSegments,
  20198. thetaStart: thetaStart,
  20199. thetaLength: thetaLength
  20200. };
  20201. thetaSegments = Math.max( 3, thetaSegments );
  20202. phiSegments = Math.max( 1, phiSegments );
  20203. // buffers
  20204. const indices = [];
  20205. const vertices = [];
  20206. const normals = [];
  20207. const uvs = [];
  20208. // some helper variables
  20209. let radius = innerRadius;
  20210. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20211. const vertex = new Vector3();
  20212. const uv = new Vector2();
  20213. // generate vertices, normals and uvs
  20214. for ( let j = 0; j <= phiSegments; j ++ ) {
  20215. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20216. // values are generate from the inside of the ring to the outside
  20217. const segment = thetaStart + i / thetaSegments * thetaLength;
  20218. // vertex
  20219. vertex.x = radius * Math.cos( segment );
  20220. vertex.y = radius * Math.sin( segment );
  20221. vertices.push( vertex.x, vertex.y, vertex.z );
  20222. // normal
  20223. normals.push( 0, 0, 1 );
  20224. // uv
  20225. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20226. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20227. uvs.push( uv.x, uv.y );
  20228. }
  20229. // increase the radius for next row of vertices
  20230. radius += radiusStep;
  20231. }
  20232. // indices
  20233. for ( let j = 0; j < phiSegments; j ++ ) {
  20234. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20235. for ( let i = 0; i < thetaSegments; i ++ ) {
  20236. const segment = i + thetaSegmentLevel;
  20237. const a = segment;
  20238. const b = segment + thetaSegments + 1;
  20239. const c = segment + thetaSegments + 2;
  20240. const d = segment + 1;
  20241. // faces
  20242. indices.push( a, b, d );
  20243. indices.push( b, c, d );
  20244. }
  20245. }
  20246. // build geometry
  20247. this.setIndex( indices );
  20248. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20249. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20250. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20251. }
  20252. copy( source ) {
  20253. super.copy( source );
  20254. this.parameters = Object.assign( {}, source.parameters );
  20255. return this;
  20256. }
  20257. static fromJSON( data ) {
  20258. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20259. }
  20260. }
  20261. class ShapeGeometry extends BufferGeometry {
  20262. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  20263. super();
  20264. this.type = 'ShapeGeometry';
  20265. this.parameters = {
  20266. shapes: shapes,
  20267. curveSegments: curveSegments
  20268. };
  20269. // buffers
  20270. const indices = [];
  20271. const vertices = [];
  20272. const normals = [];
  20273. const uvs = [];
  20274. // helper variables
  20275. let groupStart = 0;
  20276. let groupCount = 0;
  20277. // allow single and array values for "shapes" parameter
  20278. if ( Array.isArray( shapes ) === false ) {
  20279. addShape( shapes );
  20280. } else {
  20281. for ( let i = 0; i < shapes.length; i ++ ) {
  20282. addShape( shapes[ i ] );
  20283. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20284. groupStart += groupCount;
  20285. groupCount = 0;
  20286. }
  20287. }
  20288. // build geometry
  20289. this.setIndex( indices );
  20290. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20291. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20292. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20293. // helper functions
  20294. function addShape( shape ) {
  20295. const indexOffset = vertices.length / 3;
  20296. const points = shape.extractPoints( curveSegments );
  20297. let shapeVertices = points.shape;
  20298. const shapeHoles = points.holes;
  20299. // check direction of vertices
  20300. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20301. shapeVertices = shapeVertices.reverse();
  20302. }
  20303. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20304. const shapeHole = shapeHoles[ i ];
  20305. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20306. shapeHoles[ i ] = shapeHole.reverse();
  20307. }
  20308. }
  20309. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20310. // join vertices of inner and outer paths to a single array
  20311. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20312. const shapeHole = shapeHoles[ i ];
  20313. shapeVertices = shapeVertices.concat( shapeHole );
  20314. }
  20315. // vertices, normals, uvs
  20316. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20317. const vertex = shapeVertices[ i ];
  20318. vertices.push( vertex.x, vertex.y, 0 );
  20319. normals.push( 0, 0, 1 );
  20320. uvs.push( vertex.x, vertex.y ); // world uvs
  20321. }
  20322. // indices
  20323. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20324. const face = faces[ i ];
  20325. const a = face[ 0 ] + indexOffset;
  20326. const b = face[ 1 ] + indexOffset;
  20327. const c = face[ 2 ] + indexOffset;
  20328. indices.push( a, b, c );
  20329. groupCount += 3;
  20330. }
  20331. }
  20332. }
  20333. copy( source ) {
  20334. super.copy( source );
  20335. this.parameters = Object.assign( {}, source.parameters );
  20336. return this;
  20337. }
  20338. toJSON() {
  20339. const data = super.toJSON();
  20340. const shapes = this.parameters.shapes;
  20341. return toJSON( shapes, data );
  20342. }
  20343. static fromJSON( data, shapes ) {
  20344. const geometryShapes = [];
  20345. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20346. const shape = shapes[ data.shapes[ j ] ];
  20347. geometryShapes.push( shape );
  20348. }
  20349. return new ShapeGeometry( geometryShapes, data.curveSegments );
  20350. }
  20351. }
  20352. function toJSON( shapes, data ) {
  20353. data.shapes = [];
  20354. if ( Array.isArray( shapes ) ) {
  20355. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20356. const shape = shapes[ i ];
  20357. data.shapes.push( shape.uuid );
  20358. }
  20359. } else {
  20360. data.shapes.push( shapes.uuid );
  20361. }
  20362. return data;
  20363. }
  20364. class SphereGeometry extends BufferGeometry {
  20365. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  20366. super();
  20367. this.type = 'SphereGeometry';
  20368. this.parameters = {
  20369. radius: radius,
  20370. widthSegments: widthSegments,
  20371. heightSegments: heightSegments,
  20372. phiStart: phiStart,
  20373. phiLength: phiLength,
  20374. thetaStart: thetaStart,
  20375. thetaLength: thetaLength
  20376. };
  20377. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  20378. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  20379. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  20380. let index = 0;
  20381. const grid = [];
  20382. const vertex = new Vector3();
  20383. const normal = new Vector3();
  20384. // buffers
  20385. const indices = [];
  20386. const vertices = [];
  20387. const normals = [];
  20388. const uvs = [];
  20389. // generate vertices, normals and uvs
  20390. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  20391. const verticesRow = [];
  20392. const v = iy / heightSegments;
  20393. // special case for the poles
  20394. let uOffset = 0;
  20395. if ( iy === 0 && thetaStart === 0 ) {
  20396. uOffset = 0.5 / widthSegments;
  20397. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  20398. uOffset = -0.5 / widthSegments;
  20399. }
  20400. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  20401. const u = ix / widthSegments;
  20402. // vertex
  20403. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20404. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20405. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20406. vertices.push( vertex.x, vertex.y, vertex.z );
  20407. // normal
  20408. normal.copy( vertex ).normalize();
  20409. normals.push( normal.x, normal.y, normal.z );
  20410. // uv
  20411. uvs.push( u + uOffset, 1 - v );
  20412. verticesRow.push( index ++ );
  20413. }
  20414. grid.push( verticesRow );
  20415. }
  20416. // indices
  20417. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20418. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20419. const a = grid[ iy ][ ix + 1 ];
  20420. const b = grid[ iy ][ ix ];
  20421. const c = grid[ iy + 1 ][ ix ];
  20422. const d = grid[ iy + 1 ][ ix + 1 ];
  20423. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20424. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20425. }
  20426. }
  20427. // build geometry
  20428. this.setIndex( indices );
  20429. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20430. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20431. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20432. }
  20433. copy( source ) {
  20434. super.copy( source );
  20435. this.parameters = Object.assign( {}, source.parameters );
  20436. return this;
  20437. }
  20438. static fromJSON( data ) {
  20439. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  20440. }
  20441. }
  20442. class TetrahedronGeometry extends PolyhedronGeometry {
  20443. constructor( radius = 1, detail = 0 ) {
  20444. const vertices = [
  20445. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  20446. ];
  20447. const indices = [
  20448. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20449. ];
  20450. super( vertices, indices, radius, detail );
  20451. this.type = 'TetrahedronGeometry';
  20452. this.parameters = {
  20453. radius: radius,
  20454. detail: detail
  20455. };
  20456. }
  20457. static fromJSON( data ) {
  20458. return new TetrahedronGeometry( data.radius, data.detail );
  20459. }
  20460. }
  20461. class TorusGeometry extends BufferGeometry {
  20462. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  20463. super();
  20464. this.type = 'TorusGeometry';
  20465. this.parameters = {
  20466. radius: radius,
  20467. tube: tube,
  20468. radialSegments: radialSegments,
  20469. tubularSegments: tubularSegments,
  20470. arc: arc
  20471. };
  20472. radialSegments = Math.floor( radialSegments );
  20473. tubularSegments = Math.floor( tubularSegments );
  20474. // buffers
  20475. const indices = [];
  20476. const vertices = [];
  20477. const normals = [];
  20478. const uvs = [];
  20479. // helper variables
  20480. const center = new Vector3();
  20481. const vertex = new Vector3();
  20482. const normal = new Vector3();
  20483. // generate vertices, normals and uvs
  20484. for ( let j = 0; j <= radialSegments; j ++ ) {
  20485. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20486. const u = i / tubularSegments * arc;
  20487. const v = j / radialSegments * Math.PI * 2;
  20488. // vertex
  20489. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20490. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20491. vertex.z = tube * Math.sin( v );
  20492. vertices.push( vertex.x, vertex.y, vertex.z );
  20493. // normal
  20494. center.x = radius * Math.cos( u );
  20495. center.y = radius * Math.sin( u );
  20496. normal.subVectors( vertex, center ).normalize();
  20497. normals.push( normal.x, normal.y, normal.z );
  20498. // uv
  20499. uvs.push( i / tubularSegments );
  20500. uvs.push( j / radialSegments );
  20501. }
  20502. }
  20503. // generate indices
  20504. for ( let j = 1; j <= radialSegments; j ++ ) {
  20505. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20506. // indices
  20507. const a = ( tubularSegments + 1 ) * j + i - 1;
  20508. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20509. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20510. const d = ( tubularSegments + 1 ) * j + i;
  20511. // faces
  20512. indices.push( a, b, d );
  20513. indices.push( b, c, d );
  20514. }
  20515. }
  20516. // build geometry
  20517. this.setIndex( indices );
  20518. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20519. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20520. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20521. }
  20522. copy( source ) {
  20523. super.copy( source );
  20524. this.parameters = Object.assign( {}, source.parameters );
  20525. return this;
  20526. }
  20527. static fromJSON( data ) {
  20528. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  20529. }
  20530. }
  20531. class TorusKnotGeometry extends BufferGeometry {
  20532. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20533. super();
  20534. this.type = 'TorusKnotGeometry';
  20535. this.parameters = {
  20536. radius: radius,
  20537. tube: tube,
  20538. tubularSegments: tubularSegments,
  20539. radialSegments: radialSegments,
  20540. p: p,
  20541. q: q
  20542. };
  20543. tubularSegments = Math.floor( tubularSegments );
  20544. radialSegments = Math.floor( radialSegments );
  20545. // buffers
  20546. const indices = [];
  20547. const vertices = [];
  20548. const normals = [];
  20549. const uvs = [];
  20550. // helper variables
  20551. const vertex = new Vector3();
  20552. const normal = new Vector3();
  20553. const P1 = new Vector3();
  20554. const P2 = new Vector3();
  20555. const B = new Vector3();
  20556. const T = new Vector3();
  20557. const N = new Vector3();
  20558. // generate vertices, normals and uvs
  20559. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20560. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  20561. const u = i / tubularSegments * p * Math.PI * 2;
  20562. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20563. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20564. calculatePositionOnCurve( u, p, q, radius, P1 );
  20565. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20566. // calculate orthonormal basis
  20567. T.subVectors( P2, P1 );
  20568. N.addVectors( P2, P1 );
  20569. B.crossVectors( T, N );
  20570. N.crossVectors( B, T );
  20571. // normalize B, N. T can be ignored, we don't use it
  20572. B.normalize();
  20573. N.normalize();
  20574. for ( let j = 0; j <= radialSegments; ++ j ) {
  20575. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20576. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20577. const v = j / radialSegments * Math.PI * 2;
  20578. const cx = - tube * Math.cos( v );
  20579. const cy = tube * Math.sin( v );
  20580. // now calculate the final vertex position.
  20581. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  20582. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20583. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20584. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20585. vertices.push( vertex.x, vertex.y, vertex.z );
  20586. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20587. normal.subVectors( vertex, P1 ).normalize();
  20588. normals.push( normal.x, normal.y, normal.z );
  20589. // uv
  20590. uvs.push( i / tubularSegments );
  20591. uvs.push( j / radialSegments );
  20592. }
  20593. }
  20594. // generate indices
  20595. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20596. for ( let i = 1; i <= radialSegments; i ++ ) {
  20597. // indices
  20598. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20599. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20600. const c = ( radialSegments + 1 ) * j + i;
  20601. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20602. // faces
  20603. indices.push( a, b, d );
  20604. indices.push( b, c, d );
  20605. }
  20606. }
  20607. // build geometry
  20608. this.setIndex( indices );
  20609. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20610. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20611. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20612. // this function calculates the current position on the torus curve
  20613. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20614. const cu = Math.cos( u );
  20615. const su = Math.sin( u );
  20616. const quOverP = q / p * u;
  20617. const cs = Math.cos( quOverP );
  20618. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20619. position.y = radius * ( 2 + cs ) * su * 0.5;
  20620. position.z = radius * Math.sin( quOverP ) * 0.5;
  20621. }
  20622. }
  20623. copy( source ) {
  20624. super.copy( source );
  20625. this.parameters = Object.assign( {}, source.parameters );
  20626. return this;
  20627. }
  20628. static fromJSON( data ) {
  20629. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  20630. }
  20631. }
  20632. class TubeGeometry extends BufferGeometry {
  20633. 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 ) {
  20634. super();
  20635. this.type = 'TubeGeometry';
  20636. this.parameters = {
  20637. path: path,
  20638. tubularSegments: tubularSegments,
  20639. radius: radius,
  20640. radialSegments: radialSegments,
  20641. closed: closed
  20642. };
  20643. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20644. // expose internals
  20645. this.tangents = frames.tangents;
  20646. this.normals = frames.normals;
  20647. this.binormals = frames.binormals;
  20648. // helper variables
  20649. const vertex = new Vector3();
  20650. const normal = new Vector3();
  20651. const uv = new Vector2();
  20652. let P = new Vector3();
  20653. // buffer
  20654. const vertices = [];
  20655. const normals = [];
  20656. const uvs = [];
  20657. const indices = [];
  20658. // create buffer data
  20659. generateBufferData();
  20660. // build geometry
  20661. this.setIndex( indices );
  20662. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20663. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20664. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20665. // functions
  20666. function generateBufferData() {
  20667. for ( let i = 0; i < tubularSegments; i ++ ) {
  20668. generateSegment( i );
  20669. }
  20670. // if the geometry is not closed, generate the last row of vertices and normals
  20671. // at the regular position on the given path
  20672. //
  20673. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20674. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20675. // uvs are generated in a separate function.
  20676. // this makes it easy compute correct values for closed geometries
  20677. generateUVs();
  20678. // finally create faces
  20679. generateIndices();
  20680. }
  20681. function generateSegment( i ) {
  20682. // we use getPointAt to sample evenly distributed points from the given path
  20683. P = path.getPointAt( i / tubularSegments, P );
  20684. // retrieve corresponding normal and binormal
  20685. const N = frames.normals[ i ];
  20686. const B = frames.binormals[ i ];
  20687. // generate normals and vertices for the current segment
  20688. for ( let j = 0; j <= radialSegments; j ++ ) {
  20689. const v = j / radialSegments * Math.PI * 2;
  20690. const sin = Math.sin( v );
  20691. const cos = - Math.cos( v );
  20692. // normal
  20693. normal.x = ( cos * N.x + sin * B.x );
  20694. normal.y = ( cos * N.y + sin * B.y );
  20695. normal.z = ( cos * N.z + sin * B.z );
  20696. normal.normalize();
  20697. normals.push( normal.x, normal.y, normal.z );
  20698. // vertex
  20699. vertex.x = P.x + radius * normal.x;
  20700. vertex.y = P.y + radius * normal.y;
  20701. vertex.z = P.z + radius * normal.z;
  20702. vertices.push( vertex.x, vertex.y, vertex.z );
  20703. }
  20704. }
  20705. function generateIndices() {
  20706. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20707. for ( let i = 1; i <= radialSegments; i ++ ) {
  20708. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20709. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20710. const c = ( radialSegments + 1 ) * j + i;
  20711. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20712. // faces
  20713. indices.push( a, b, d );
  20714. indices.push( b, c, d );
  20715. }
  20716. }
  20717. }
  20718. function generateUVs() {
  20719. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20720. for ( let j = 0; j <= radialSegments; j ++ ) {
  20721. uv.x = i / tubularSegments;
  20722. uv.y = j / radialSegments;
  20723. uvs.push( uv.x, uv.y );
  20724. }
  20725. }
  20726. }
  20727. }
  20728. copy( source ) {
  20729. super.copy( source );
  20730. this.parameters = Object.assign( {}, source.parameters );
  20731. return this;
  20732. }
  20733. toJSON() {
  20734. const data = super.toJSON();
  20735. data.path = this.parameters.path.toJSON();
  20736. return data;
  20737. }
  20738. static fromJSON( data ) {
  20739. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20740. // User defined curves or instances of CurvePath will not be deserialized.
  20741. return new TubeGeometry(
  20742. new Curves[ data.path.type ]().fromJSON( data.path ),
  20743. data.tubularSegments,
  20744. data.radius,
  20745. data.radialSegments,
  20746. data.closed
  20747. );
  20748. }
  20749. }
  20750. class WireframeGeometry extends BufferGeometry {
  20751. constructor( geometry = null ) {
  20752. super();
  20753. this.type = 'WireframeGeometry';
  20754. this.parameters = {
  20755. geometry: geometry
  20756. };
  20757. if ( geometry !== null ) {
  20758. // buffer
  20759. const vertices = [];
  20760. const edges = new Set();
  20761. // helper variables
  20762. const start = new Vector3();
  20763. const end = new Vector3();
  20764. if ( geometry.index !== null ) {
  20765. // indexed BufferGeometry
  20766. const position = geometry.attributes.position;
  20767. const indices = geometry.index;
  20768. let groups = geometry.groups;
  20769. if ( groups.length === 0 ) {
  20770. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20771. }
  20772. // create a data structure that contains all edges without duplicates
  20773. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  20774. const group = groups[ o ];
  20775. const groupStart = group.start;
  20776. const groupCount = group.count;
  20777. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  20778. for ( let j = 0; j < 3; j ++ ) {
  20779. const index1 = indices.getX( i + j );
  20780. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  20781. start.fromBufferAttribute( position, index1 );
  20782. end.fromBufferAttribute( position, index2 );
  20783. if ( isUniqueEdge( start, end, edges ) === true ) {
  20784. vertices.push( start.x, start.y, start.z );
  20785. vertices.push( end.x, end.y, end.z );
  20786. }
  20787. }
  20788. }
  20789. }
  20790. } else {
  20791. // non-indexed BufferGeometry
  20792. const position = geometry.attributes.position;
  20793. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20794. for ( let j = 0; j < 3; j ++ ) {
  20795. // three edges per triangle, an edge is represented as (index1, index2)
  20796. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20797. const index1 = 3 * i + j;
  20798. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  20799. start.fromBufferAttribute( position, index1 );
  20800. end.fromBufferAttribute( position, index2 );
  20801. if ( isUniqueEdge( start, end, edges ) === true ) {
  20802. vertices.push( start.x, start.y, start.z );
  20803. vertices.push( end.x, end.y, end.z );
  20804. }
  20805. }
  20806. }
  20807. }
  20808. // build geometry
  20809. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20810. }
  20811. }
  20812. copy( source ) {
  20813. super.copy( source );
  20814. this.parameters = Object.assign( {}, source.parameters );
  20815. return this;
  20816. }
  20817. }
  20818. function isUniqueEdge( start, end, edges ) {
  20819. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20820. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20821. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  20822. return false;
  20823. } else {
  20824. edges.add( hash1 );
  20825. edges.add( hash2 );
  20826. return true;
  20827. }
  20828. }
  20829. var Geometries = /*#__PURE__*/Object.freeze({
  20830. __proto__: null,
  20831. BoxGeometry: BoxGeometry,
  20832. CapsuleGeometry: CapsuleGeometry,
  20833. CircleGeometry: CircleGeometry,
  20834. ConeGeometry: ConeGeometry,
  20835. CylinderGeometry: CylinderGeometry,
  20836. DodecahedronGeometry: DodecahedronGeometry,
  20837. EdgesGeometry: EdgesGeometry,
  20838. ExtrudeGeometry: ExtrudeGeometry,
  20839. IcosahedronGeometry: IcosahedronGeometry,
  20840. LatheGeometry: LatheGeometry,
  20841. OctahedronGeometry: OctahedronGeometry,
  20842. PlaneGeometry: PlaneGeometry,
  20843. PolyhedronGeometry: PolyhedronGeometry,
  20844. RingGeometry: RingGeometry,
  20845. ShapeGeometry: ShapeGeometry,
  20846. SphereGeometry: SphereGeometry,
  20847. TetrahedronGeometry: TetrahedronGeometry,
  20848. TorusGeometry: TorusGeometry,
  20849. TorusKnotGeometry: TorusKnotGeometry,
  20850. TubeGeometry: TubeGeometry,
  20851. WireframeGeometry: WireframeGeometry
  20852. });
  20853. class ShadowMaterial extends Material {
  20854. constructor( parameters ) {
  20855. super();
  20856. this.isShadowMaterial = true;
  20857. this.type = 'ShadowMaterial';
  20858. this.color = new Color( 0x000000 );
  20859. this.transparent = true;
  20860. this.fog = true;
  20861. this.setValues( parameters );
  20862. }
  20863. copy( source ) {
  20864. super.copy( source );
  20865. this.color.copy( source.color );
  20866. this.fog = source.fog;
  20867. return this;
  20868. }
  20869. }
  20870. class RawShaderMaterial extends ShaderMaterial {
  20871. constructor( parameters ) {
  20872. super( parameters );
  20873. this.isRawShaderMaterial = true;
  20874. this.type = 'RawShaderMaterial';
  20875. }
  20876. }
  20877. class MeshStandardMaterial extends Material {
  20878. constructor( parameters ) {
  20879. super();
  20880. this.isMeshStandardMaterial = true;
  20881. this.type = 'MeshStandardMaterial';
  20882. this.defines = { 'STANDARD': '' };
  20883. this.color = new Color( 0xffffff ); // diffuse
  20884. this.roughness = 1.0;
  20885. this.metalness = 0.0;
  20886. this.map = null;
  20887. this.lightMap = null;
  20888. this.lightMapIntensity = 1.0;
  20889. this.aoMap = null;
  20890. this.aoMapIntensity = 1.0;
  20891. this.emissive = new Color( 0x000000 );
  20892. this.emissiveIntensity = 1.0;
  20893. this.emissiveMap = null;
  20894. this.bumpMap = null;
  20895. this.bumpScale = 1;
  20896. this.normalMap = null;
  20897. this.normalMapType = TangentSpaceNormalMap;
  20898. this.normalScale = new Vector2( 1, 1 );
  20899. this.displacementMap = null;
  20900. this.displacementScale = 1;
  20901. this.displacementBias = 0;
  20902. this.roughnessMap = null;
  20903. this.metalnessMap = null;
  20904. this.alphaMap = null;
  20905. this.envMap = null;
  20906. this.envMapRotation = new Euler();
  20907. this.envMapIntensity = 1.0;
  20908. this.wireframe = false;
  20909. this.wireframeLinewidth = 1;
  20910. this.wireframeLinecap = 'round';
  20911. this.wireframeLinejoin = 'round';
  20912. this.flatShading = false;
  20913. this.fog = true;
  20914. this.setValues( parameters );
  20915. }
  20916. copy( source ) {
  20917. super.copy( source );
  20918. this.defines = { 'STANDARD': '' };
  20919. this.color.copy( source.color );
  20920. this.roughness = source.roughness;
  20921. this.metalness = source.metalness;
  20922. this.map = source.map;
  20923. this.lightMap = source.lightMap;
  20924. this.lightMapIntensity = source.lightMapIntensity;
  20925. this.aoMap = source.aoMap;
  20926. this.aoMapIntensity = source.aoMapIntensity;
  20927. this.emissive.copy( source.emissive );
  20928. this.emissiveMap = source.emissiveMap;
  20929. this.emissiveIntensity = source.emissiveIntensity;
  20930. this.bumpMap = source.bumpMap;
  20931. this.bumpScale = source.bumpScale;
  20932. this.normalMap = source.normalMap;
  20933. this.normalMapType = source.normalMapType;
  20934. this.normalScale.copy( source.normalScale );
  20935. this.displacementMap = source.displacementMap;
  20936. this.displacementScale = source.displacementScale;
  20937. this.displacementBias = source.displacementBias;
  20938. this.roughnessMap = source.roughnessMap;
  20939. this.metalnessMap = source.metalnessMap;
  20940. this.alphaMap = source.alphaMap;
  20941. this.envMap = source.envMap;
  20942. this.envMapRotation.copy( source.envMapRotation );
  20943. this.envMapIntensity = source.envMapIntensity;
  20944. this.wireframe = source.wireframe;
  20945. this.wireframeLinewidth = source.wireframeLinewidth;
  20946. this.wireframeLinecap = source.wireframeLinecap;
  20947. this.wireframeLinejoin = source.wireframeLinejoin;
  20948. this.flatShading = source.flatShading;
  20949. this.fog = source.fog;
  20950. return this;
  20951. }
  20952. }
  20953. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20954. constructor( parameters ) {
  20955. super();
  20956. this.isMeshPhysicalMaterial = true;
  20957. this.defines = {
  20958. 'STANDARD': '',
  20959. 'PHYSICAL': ''
  20960. };
  20961. this.type = 'MeshPhysicalMaterial';
  20962. this.anisotropyRotation = 0;
  20963. this.anisotropyMap = null;
  20964. this.clearcoatMap = null;
  20965. this.clearcoatRoughness = 0.0;
  20966. this.clearcoatRoughnessMap = null;
  20967. this.clearcoatNormalScale = new Vector2( 1, 1 );
  20968. this.clearcoatNormalMap = null;
  20969. this.ior = 1.5;
  20970. Object.defineProperty( this, 'reflectivity', {
  20971. get: function () {
  20972. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  20973. },
  20974. set: function ( reflectivity ) {
  20975. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  20976. }
  20977. } );
  20978. this.iridescenceMap = null;
  20979. this.iridescenceIOR = 1.3;
  20980. this.iridescenceThicknessRange = [ 100, 400 ];
  20981. this.iridescenceThicknessMap = null;
  20982. this.sheenColor = new Color( 0x000000 );
  20983. this.sheenColorMap = null;
  20984. this.sheenRoughness = 1.0;
  20985. this.sheenRoughnessMap = null;
  20986. this.transmissionMap = null;
  20987. this.thickness = 0;
  20988. this.thicknessMap = null;
  20989. this.attenuationDistance = Infinity;
  20990. this.attenuationColor = new Color( 1, 1, 1 );
  20991. this.specularIntensity = 1.0;
  20992. this.specularIntensityMap = null;
  20993. this.specularColor = new Color( 1, 1, 1 );
  20994. this.specularColorMap = null;
  20995. this._anisotropy = 0;
  20996. this._clearcoat = 0;
  20997. this._dispersion = 0;
  20998. this._iridescence = 0;
  20999. this._sheen = 0.0;
  21000. this._transmission = 0;
  21001. this.setValues( parameters );
  21002. }
  21003. get anisotropy() {
  21004. return this._anisotropy;
  21005. }
  21006. set anisotropy( value ) {
  21007. if ( this._anisotropy > 0 !== value > 0 ) {
  21008. this.version ++;
  21009. }
  21010. this._anisotropy = value;
  21011. }
  21012. get clearcoat() {
  21013. return this._clearcoat;
  21014. }
  21015. set clearcoat( value ) {
  21016. if ( this._clearcoat > 0 !== value > 0 ) {
  21017. this.version ++;
  21018. }
  21019. this._clearcoat = value;
  21020. }
  21021. get iridescence() {
  21022. return this._iridescence;
  21023. }
  21024. set iridescence( value ) {
  21025. if ( this._iridescence > 0 !== value > 0 ) {
  21026. this.version ++;
  21027. }
  21028. this._iridescence = value;
  21029. }
  21030. get dispersion() {
  21031. return this._dispersion;
  21032. }
  21033. set dispersion( value ) {
  21034. if ( this._dispersion > 0 !== value > 0 ) {
  21035. this.version ++;
  21036. }
  21037. this._dispersion = value;
  21038. }
  21039. get sheen() {
  21040. return this._sheen;
  21041. }
  21042. set sheen( value ) {
  21043. if ( this._sheen > 0 !== value > 0 ) {
  21044. this.version ++;
  21045. }
  21046. this._sheen = value;
  21047. }
  21048. get transmission() {
  21049. return this._transmission;
  21050. }
  21051. set transmission( value ) {
  21052. if ( this._transmission > 0 !== value > 0 ) {
  21053. this.version ++;
  21054. }
  21055. this._transmission = value;
  21056. }
  21057. copy( source ) {
  21058. super.copy( source );
  21059. this.defines = {
  21060. 'STANDARD': '',
  21061. 'PHYSICAL': ''
  21062. };
  21063. this.anisotropy = source.anisotropy;
  21064. this.anisotropyRotation = source.anisotropyRotation;
  21065. this.anisotropyMap = source.anisotropyMap;
  21066. this.clearcoat = source.clearcoat;
  21067. this.clearcoatMap = source.clearcoatMap;
  21068. this.clearcoatRoughness = source.clearcoatRoughness;
  21069. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21070. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21071. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21072. this.dispersion = source.dispersion;
  21073. this.ior = source.ior;
  21074. this.iridescence = source.iridescence;
  21075. this.iridescenceMap = source.iridescenceMap;
  21076. this.iridescenceIOR = source.iridescenceIOR;
  21077. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  21078. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  21079. this.sheen = source.sheen;
  21080. this.sheenColor.copy( source.sheenColor );
  21081. this.sheenColorMap = source.sheenColorMap;
  21082. this.sheenRoughness = source.sheenRoughness;
  21083. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21084. this.transmission = source.transmission;
  21085. this.transmissionMap = source.transmissionMap;
  21086. this.thickness = source.thickness;
  21087. this.thicknessMap = source.thicknessMap;
  21088. this.attenuationDistance = source.attenuationDistance;
  21089. this.attenuationColor.copy( source.attenuationColor );
  21090. this.specularIntensity = source.specularIntensity;
  21091. this.specularIntensityMap = source.specularIntensityMap;
  21092. this.specularColor.copy( source.specularColor );
  21093. this.specularColorMap = source.specularColorMap;
  21094. return this;
  21095. }
  21096. }
  21097. class MeshPhongMaterial extends Material {
  21098. constructor( parameters ) {
  21099. super();
  21100. this.isMeshPhongMaterial = true;
  21101. this.type = 'MeshPhongMaterial';
  21102. this.color = new Color( 0xffffff ); // diffuse
  21103. this.specular = new Color( 0x111111 );
  21104. this.shininess = 30;
  21105. this.map = null;
  21106. this.lightMap = null;
  21107. this.lightMapIntensity = 1.0;
  21108. this.aoMap = null;
  21109. this.aoMapIntensity = 1.0;
  21110. this.emissive = new Color( 0x000000 );
  21111. this.emissiveIntensity = 1.0;
  21112. this.emissiveMap = null;
  21113. this.bumpMap = null;
  21114. this.bumpScale = 1;
  21115. this.normalMap = null;
  21116. this.normalMapType = TangentSpaceNormalMap;
  21117. this.normalScale = new Vector2( 1, 1 );
  21118. this.displacementMap = null;
  21119. this.displacementScale = 1;
  21120. this.displacementBias = 0;
  21121. this.specularMap = null;
  21122. this.alphaMap = null;
  21123. this.envMap = null;
  21124. this.envMapRotation = new Euler();
  21125. this.combine = MultiplyOperation;
  21126. this.reflectivity = 1;
  21127. this.refractionRatio = 0.98;
  21128. this.wireframe = false;
  21129. this.wireframeLinewidth = 1;
  21130. this.wireframeLinecap = 'round';
  21131. this.wireframeLinejoin = 'round';
  21132. this.flatShading = false;
  21133. this.fog = true;
  21134. this.setValues( parameters );
  21135. }
  21136. copy( source ) {
  21137. super.copy( source );
  21138. this.color.copy( source.color );
  21139. this.specular.copy( source.specular );
  21140. this.shininess = source.shininess;
  21141. this.map = source.map;
  21142. this.lightMap = source.lightMap;
  21143. this.lightMapIntensity = source.lightMapIntensity;
  21144. this.aoMap = source.aoMap;
  21145. this.aoMapIntensity = source.aoMapIntensity;
  21146. this.emissive.copy( source.emissive );
  21147. this.emissiveMap = source.emissiveMap;
  21148. this.emissiveIntensity = source.emissiveIntensity;
  21149. this.bumpMap = source.bumpMap;
  21150. this.bumpScale = source.bumpScale;
  21151. this.normalMap = source.normalMap;
  21152. this.normalMapType = source.normalMapType;
  21153. this.normalScale.copy( source.normalScale );
  21154. this.displacementMap = source.displacementMap;
  21155. this.displacementScale = source.displacementScale;
  21156. this.displacementBias = source.displacementBias;
  21157. this.specularMap = source.specularMap;
  21158. this.alphaMap = source.alphaMap;
  21159. this.envMap = source.envMap;
  21160. this.envMapRotation.copy( source.envMapRotation );
  21161. this.combine = source.combine;
  21162. this.reflectivity = source.reflectivity;
  21163. this.refractionRatio = source.refractionRatio;
  21164. this.wireframe = source.wireframe;
  21165. this.wireframeLinewidth = source.wireframeLinewidth;
  21166. this.wireframeLinecap = source.wireframeLinecap;
  21167. this.wireframeLinejoin = source.wireframeLinejoin;
  21168. this.flatShading = source.flatShading;
  21169. this.fog = source.fog;
  21170. return this;
  21171. }
  21172. }
  21173. class MeshToonMaterial extends Material {
  21174. constructor( parameters ) {
  21175. super();
  21176. this.isMeshToonMaterial = true;
  21177. this.defines = { 'TOON': '' };
  21178. this.type = 'MeshToonMaterial';
  21179. this.color = new Color( 0xffffff );
  21180. this.map = null;
  21181. this.gradientMap = null;
  21182. this.lightMap = null;
  21183. this.lightMapIntensity = 1.0;
  21184. this.aoMap = null;
  21185. this.aoMapIntensity = 1.0;
  21186. this.emissive = new Color( 0x000000 );
  21187. this.emissiveIntensity = 1.0;
  21188. this.emissiveMap = null;
  21189. this.bumpMap = null;
  21190. this.bumpScale = 1;
  21191. this.normalMap = null;
  21192. this.normalMapType = TangentSpaceNormalMap;
  21193. this.normalScale = new Vector2( 1, 1 );
  21194. this.displacementMap = null;
  21195. this.displacementScale = 1;
  21196. this.displacementBias = 0;
  21197. this.alphaMap = null;
  21198. this.wireframe = false;
  21199. this.wireframeLinewidth = 1;
  21200. this.wireframeLinecap = 'round';
  21201. this.wireframeLinejoin = 'round';
  21202. this.fog = true;
  21203. this.setValues( parameters );
  21204. }
  21205. copy( source ) {
  21206. super.copy( source );
  21207. this.color.copy( source.color );
  21208. this.map = source.map;
  21209. this.gradientMap = source.gradientMap;
  21210. this.lightMap = source.lightMap;
  21211. this.lightMapIntensity = source.lightMapIntensity;
  21212. this.aoMap = source.aoMap;
  21213. this.aoMapIntensity = source.aoMapIntensity;
  21214. this.emissive.copy( source.emissive );
  21215. this.emissiveMap = source.emissiveMap;
  21216. this.emissiveIntensity = source.emissiveIntensity;
  21217. this.bumpMap = source.bumpMap;
  21218. this.bumpScale = source.bumpScale;
  21219. this.normalMap = source.normalMap;
  21220. this.normalMapType = source.normalMapType;
  21221. this.normalScale.copy( source.normalScale );
  21222. this.displacementMap = source.displacementMap;
  21223. this.displacementScale = source.displacementScale;
  21224. this.displacementBias = source.displacementBias;
  21225. this.alphaMap = source.alphaMap;
  21226. this.wireframe = source.wireframe;
  21227. this.wireframeLinewidth = source.wireframeLinewidth;
  21228. this.wireframeLinecap = source.wireframeLinecap;
  21229. this.wireframeLinejoin = source.wireframeLinejoin;
  21230. this.fog = source.fog;
  21231. return this;
  21232. }
  21233. }
  21234. class MeshNormalMaterial extends Material {
  21235. constructor( parameters ) {
  21236. super();
  21237. this.isMeshNormalMaterial = true;
  21238. this.type = 'MeshNormalMaterial';
  21239. this.bumpMap = null;
  21240. this.bumpScale = 1;
  21241. this.normalMap = null;
  21242. this.normalMapType = TangentSpaceNormalMap;
  21243. this.normalScale = new Vector2( 1, 1 );
  21244. this.displacementMap = null;
  21245. this.displacementScale = 1;
  21246. this.displacementBias = 0;
  21247. this.wireframe = false;
  21248. this.wireframeLinewidth = 1;
  21249. this.flatShading = false;
  21250. this.setValues( parameters );
  21251. }
  21252. copy( source ) {
  21253. super.copy( source );
  21254. this.bumpMap = source.bumpMap;
  21255. this.bumpScale = source.bumpScale;
  21256. this.normalMap = source.normalMap;
  21257. this.normalMapType = source.normalMapType;
  21258. this.normalScale.copy( source.normalScale );
  21259. this.displacementMap = source.displacementMap;
  21260. this.displacementScale = source.displacementScale;
  21261. this.displacementBias = source.displacementBias;
  21262. this.wireframe = source.wireframe;
  21263. this.wireframeLinewidth = source.wireframeLinewidth;
  21264. this.flatShading = source.flatShading;
  21265. return this;
  21266. }
  21267. }
  21268. class MeshLambertMaterial extends Material {
  21269. constructor( parameters ) {
  21270. super();
  21271. this.isMeshLambertMaterial = true;
  21272. this.type = 'MeshLambertMaterial';
  21273. this.color = new Color( 0xffffff ); // diffuse
  21274. this.map = null;
  21275. this.lightMap = null;
  21276. this.lightMapIntensity = 1.0;
  21277. this.aoMap = null;
  21278. this.aoMapIntensity = 1.0;
  21279. this.emissive = new Color( 0x000000 );
  21280. this.emissiveIntensity = 1.0;
  21281. this.emissiveMap = null;
  21282. this.bumpMap = null;
  21283. this.bumpScale = 1;
  21284. this.normalMap = null;
  21285. this.normalMapType = TangentSpaceNormalMap;
  21286. this.normalScale = new Vector2( 1, 1 );
  21287. this.displacementMap = null;
  21288. this.displacementScale = 1;
  21289. this.displacementBias = 0;
  21290. this.specularMap = null;
  21291. this.alphaMap = null;
  21292. this.envMap = null;
  21293. this.envMapRotation = new Euler();
  21294. this.combine = MultiplyOperation;
  21295. this.reflectivity = 1;
  21296. this.refractionRatio = 0.98;
  21297. this.wireframe = false;
  21298. this.wireframeLinewidth = 1;
  21299. this.wireframeLinecap = 'round';
  21300. this.wireframeLinejoin = 'round';
  21301. this.flatShading = false;
  21302. this.fog = true;
  21303. this.setValues( parameters );
  21304. }
  21305. copy( source ) {
  21306. super.copy( source );
  21307. this.color.copy( source.color );
  21308. this.map = source.map;
  21309. this.lightMap = source.lightMap;
  21310. this.lightMapIntensity = source.lightMapIntensity;
  21311. this.aoMap = source.aoMap;
  21312. this.aoMapIntensity = source.aoMapIntensity;
  21313. this.emissive.copy( source.emissive );
  21314. this.emissiveMap = source.emissiveMap;
  21315. this.emissiveIntensity = source.emissiveIntensity;
  21316. this.bumpMap = source.bumpMap;
  21317. this.bumpScale = source.bumpScale;
  21318. this.normalMap = source.normalMap;
  21319. this.normalMapType = source.normalMapType;
  21320. this.normalScale.copy( source.normalScale );
  21321. this.displacementMap = source.displacementMap;
  21322. this.displacementScale = source.displacementScale;
  21323. this.displacementBias = source.displacementBias;
  21324. this.specularMap = source.specularMap;
  21325. this.alphaMap = source.alphaMap;
  21326. this.envMap = source.envMap;
  21327. this.envMapRotation.copy( source.envMapRotation );
  21328. this.combine = source.combine;
  21329. this.reflectivity = source.reflectivity;
  21330. this.refractionRatio = source.refractionRatio;
  21331. this.wireframe = source.wireframe;
  21332. this.wireframeLinewidth = source.wireframeLinewidth;
  21333. this.wireframeLinecap = source.wireframeLinecap;
  21334. this.wireframeLinejoin = source.wireframeLinejoin;
  21335. this.flatShading = source.flatShading;
  21336. this.fog = source.fog;
  21337. return this;
  21338. }
  21339. }
  21340. class MeshDepthMaterial extends Material {
  21341. constructor( parameters ) {
  21342. super();
  21343. this.isMeshDepthMaterial = true;
  21344. this.type = 'MeshDepthMaterial';
  21345. this.depthPacking = BasicDepthPacking;
  21346. this.map = null;
  21347. this.alphaMap = null;
  21348. this.displacementMap = null;
  21349. this.displacementScale = 1;
  21350. this.displacementBias = 0;
  21351. this.wireframe = false;
  21352. this.wireframeLinewidth = 1;
  21353. this.setValues( parameters );
  21354. }
  21355. copy( source ) {
  21356. super.copy( source );
  21357. this.depthPacking = source.depthPacking;
  21358. this.map = source.map;
  21359. this.alphaMap = source.alphaMap;
  21360. this.displacementMap = source.displacementMap;
  21361. this.displacementScale = source.displacementScale;
  21362. this.displacementBias = source.displacementBias;
  21363. this.wireframe = source.wireframe;
  21364. this.wireframeLinewidth = source.wireframeLinewidth;
  21365. return this;
  21366. }
  21367. }
  21368. class MeshDistanceMaterial extends Material {
  21369. constructor( parameters ) {
  21370. super();
  21371. this.isMeshDistanceMaterial = true;
  21372. this.type = 'MeshDistanceMaterial';
  21373. this.map = null;
  21374. this.alphaMap = null;
  21375. this.displacementMap = null;
  21376. this.displacementScale = 1;
  21377. this.displacementBias = 0;
  21378. this.setValues( parameters );
  21379. }
  21380. copy( source ) {
  21381. super.copy( source );
  21382. this.map = source.map;
  21383. this.alphaMap = source.alphaMap;
  21384. this.displacementMap = source.displacementMap;
  21385. this.displacementScale = source.displacementScale;
  21386. this.displacementBias = source.displacementBias;
  21387. return this;
  21388. }
  21389. }
  21390. class MeshMatcapMaterial extends Material {
  21391. constructor( parameters ) {
  21392. super();
  21393. this.isMeshMatcapMaterial = true;
  21394. this.defines = { 'MATCAP': '' };
  21395. this.type = 'MeshMatcapMaterial';
  21396. this.color = new Color( 0xffffff ); // diffuse
  21397. this.matcap = null;
  21398. this.map = null;
  21399. this.bumpMap = null;
  21400. this.bumpScale = 1;
  21401. this.normalMap = null;
  21402. this.normalMapType = TangentSpaceNormalMap;
  21403. this.normalScale = new Vector2( 1, 1 );
  21404. this.displacementMap = null;
  21405. this.displacementScale = 1;
  21406. this.displacementBias = 0;
  21407. this.alphaMap = null;
  21408. this.flatShading = false;
  21409. this.fog = true;
  21410. this.setValues( parameters );
  21411. }
  21412. copy( source ) {
  21413. super.copy( source );
  21414. this.defines = { 'MATCAP': '' };
  21415. this.color.copy( source.color );
  21416. this.matcap = source.matcap;
  21417. this.map = source.map;
  21418. this.bumpMap = source.bumpMap;
  21419. this.bumpScale = source.bumpScale;
  21420. this.normalMap = source.normalMap;
  21421. this.normalMapType = source.normalMapType;
  21422. this.normalScale.copy( source.normalScale );
  21423. this.displacementMap = source.displacementMap;
  21424. this.displacementScale = source.displacementScale;
  21425. this.displacementBias = source.displacementBias;
  21426. this.alphaMap = source.alphaMap;
  21427. this.flatShading = source.flatShading;
  21428. this.fog = source.fog;
  21429. return this;
  21430. }
  21431. }
  21432. class LineDashedMaterial extends LineBasicMaterial {
  21433. constructor( parameters ) {
  21434. super();
  21435. this.isLineDashedMaterial = true;
  21436. this.type = 'LineDashedMaterial';
  21437. this.scale = 1;
  21438. this.dashSize = 3;
  21439. this.gapSize = 1;
  21440. this.setValues( parameters );
  21441. }
  21442. copy( source ) {
  21443. super.copy( source );
  21444. this.scale = source.scale;
  21445. this.dashSize = source.dashSize;
  21446. this.gapSize = source.gapSize;
  21447. return this;
  21448. }
  21449. }
  21450. // converts an array to a specific type
  21451. function convertArray( array, type, forceClone ) {
  21452. if ( ! array || // let 'undefined' and 'null' pass
  21453. ! forceClone && array.constructor === type ) return array;
  21454. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21455. return new type( array ); // create typed array
  21456. }
  21457. return Array.prototype.slice.call( array ); // create Array
  21458. }
  21459. function isTypedArray( object ) {
  21460. return ArrayBuffer.isView( object ) &&
  21461. ! ( object instanceof DataView );
  21462. }
  21463. // returns an array by which times and values can be sorted
  21464. function getKeyframeOrder( times ) {
  21465. function compareTime( i, j ) {
  21466. return times[ i ] - times[ j ];
  21467. }
  21468. const n = times.length;
  21469. const result = new Array( n );
  21470. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21471. result.sort( compareTime );
  21472. return result;
  21473. }
  21474. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21475. function sortedArray( values, stride, order ) {
  21476. const nValues = values.length;
  21477. const result = new values.constructor( nValues );
  21478. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21479. const srcOffset = order[ i ] * stride;
  21480. for ( let j = 0; j !== stride; ++ j ) {
  21481. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21482. }
  21483. }
  21484. return result;
  21485. }
  21486. // function for parsing AOS keyframe formats
  21487. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  21488. let i = 1, key = jsonKeys[ 0 ];
  21489. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21490. key = jsonKeys[ i ++ ];
  21491. }
  21492. if ( key === undefined ) return; // no data
  21493. let value = key[ valuePropertyName ];
  21494. if ( value === undefined ) return; // no data
  21495. if ( Array.isArray( value ) ) {
  21496. do {
  21497. value = key[ valuePropertyName ];
  21498. if ( value !== undefined ) {
  21499. times.push( key.time );
  21500. values.push( ...value ); // push all elements
  21501. }
  21502. key = jsonKeys[ i ++ ];
  21503. } while ( key !== undefined );
  21504. } else if ( value.toArray !== undefined ) {
  21505. // ...assume THREE.Math-ish
  21506. do {
  21507. value = key[ valuePropertyName ];
  21508. if ( value !== undefined ) {
  21509. times.push( key.time );
  21510. value.toArray( values, values.length );
  21511. }
  21512. key = jsonKeys[ i ++ ];
  21513. } while ( key !== undefined );
  21514. } else {
  21515. // otherwise push as-is
  21516. do {
  21517. value = key[ valuePropertyName ];
  21518. if ( value !== undefined ) {
  21519. times.push( key.time );
  21520. values.push( value );
  21521. }
  21522. key = jsonKeys[ i ++ ];
  21523. } while ( key !== undefined );
  21524. }
  21525. }
  21526. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21527. const clip = sourceClip.clone();
  21528. clip.name = name;
  21529. const tracks = [];
  21530. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21531. const track = clip.tracks[ i ];
  21532. const valueSize = track.getValueSize();
  21533. const times = [];
  21534. const values = [];
  21535. for ( let j = 0; j < track.times.length; ++ j ) {
  21536. const frame = track.times[ j ] * fps;
  21537. if ( frame < startFrame || frame >= endFrame ) continue;
  21538. times.push( track.times[ j ] );
  21539. for ( let k = 0; k < valueSize; ++ k ) {
  21540. values.push( track.values[ j * valueSize + k ] );
  21541. }
  21542. }
  21543. if ( times.length === 0 ) continue;
  21544. track.times = convertArray( times, track.times.constructor );
  21545. track.values = convertArray( values, track.values.constructor );
  21546. tracks.push( track );
  21547. }
  21548. clip.tracks = tracks;
  21549. // find minimum .times value across all tracks in the trimmed clip
  21550. let minStartTime = Infinity;
  21551. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21552. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21553. minStartTime = clip.tracks[ i ].times[ 0 ];
  21554. }
  21555. }
  21556. // shift all tracks such that clip begins at t=0
  21557. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21558. clip.tracks[ i ].shift( -1 * minStartTime );
  21559. }
  21560. clip.resetDuration();
  21561. return clip;
  21562. }
  21563. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21564. if ( fps <= 0 ) fps = 30;
  21565. const numTracks = referenceClip.tracks.length;
  21566. const referenceTime = referenceFrame / fps;
  21567. // Make each track's values relative to the values at the reference frame
  21568. for ( let i = 0; i < numTracks; ++ i ) {
  21569. const referenceTrack = referenceClip.tracks[ i ];
  21570. const referenceTrackType = referenceTrack.ValueTypeName;
  21571. // Skip this track if it's non-numeric
  21572. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21573. // Find the track in the target clip whose name and type matches the reference track
  21574. const targetTrack = targetClip.tracks.find( function ( track ) {
  21575. return track.name === referenceTrack.name
  21576. && track.ValueTypeName === referenceTrackType;
  21577. } );
  21578. if ( targetTrack === undefined ) continue;
  21579. let referenceOffset = 0;
  21580. const referenceValueSize = referenceTrack.getValueSize();
  21581. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21582. referenceOffset = referenceValueSize / 3;
  21583. }
  21584. let targetOffset = 0;
  21585. const targetValueSize = targetTrack.getValueSize();
  21586. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21587. targetOffset = targetValueSize / 3;
  21588. }
  21589. const lastIndex = referenceTrack.times.length - 1;
  21590. let referenceValue;
  21591. // Find the value to subtract out of the track
  21592. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21593. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21594. const startIndex = referenceOffset;
  21595. const endIndex = referenceValueSize - referenceOffset;
  21596. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  21597. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21598. // Reference frame is after the last keyframe, so just use the last keyframe
  21599. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21600. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21601. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  21602. } else {
  21603. // Interpolate to the reference value
  21604. const interpolant = referenceTrack.createInterpolant();
  21605. const startIndex = referenceOffset;
  21606. const endIndex = referenceValueSize - referenceOffset;
  21607. interpolant.evaluate( referenceTime );
  21608. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  21609. }
  21610. // Conjugate the quaternion
  21611. if ( referenceTrackType === 'quaternion' ) {
  21612. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21613. referenceQuat.toArray( referenceValue );
  21614. }
  21615. // Subtract the reference value from all of the track values
  21616. const numTimes = targetTrack.times.length;
  21617. for ( let j = 0; j < numTimes; ++ j ) {
  21618. const valueStart = j * targetValueSize + targetOffset;
  21619. if ( referenceTrackType === 'quaternion' ) {
  21620. // Multiply the conjugate for quaternion track types
  21621. Quaternion.multiplyQuaternionsFlat(
  21622. targetTrack.values,
  21623. valueStart,
  21624. referenceValue,
  21625. 0,
  21626. targetTrack.values,
  21627. valueStart
  21628. );
  21629. } else {
  21630. const valueEnd = targetValueSize - targetOffset * 2;
  21631. // Subtract each value for all other numeric track types
  21632. for ( let k = 0; k < valueEnd; ++ k ) {
  21633. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  21634. }
  21635. }
  21636. }
  21637. }
  21638. targetClip.blendMode = AdditiveAnimationBlendMode;
  21639. return targetClip;
  21640. }
  21641. const AnimationUtils = {
  21642. convertArray: convertArray,
  21643. isTypedArray: isTypedArray,
  21644. getKeyframeOrder: getKeyframeOrder,
  21645. sortedArray: sortedArray,
  21646. flattenJSON: flattenJSON,
  21647. subclip: subclip,
  21648. makeClipAdditive: makeClipAdditive
  21649. };
  21650. /**
  21651. * Abstract base class of interpolants over parametric samples.
  21652. *
  21653. * The parameter domain is one dimensional, typically the time or a path
  21654. * along a curve defined by the data.
  21655. *
  21656. * The sample values can have any dimensionality and derived classes may
  21657. * apply special interpretations to the data.
  21658. *
  21659. * This class provides the interval seek in a Template Method, deferring
  21660. * the actual interpolation to derived classes.
  21661. *
  21662. * Time complexity is O(1) for linear access crossing at most two points
  21663. * and O(log N) for random access, where N is the number of positions.
  21664. *
  21665. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  21666. *
  21667. * @abstract
  21668. */
  21669. class Interpolant {
  21670. /**
  21671. * Constructs a new interpolant.
  21672. *
  21673. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  21674. * @param {TypedArray} sampleValues - The sample values.
  21675. * @param {number} sampleSize - The sample size
  21676. * @param {TypedArray} [resultBuffer] - The result buffer.
  21677. */
  21678. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21679. /**
  21680. * The parameter positions.
  21681. *
  21682. * @type {TypedArray}
  21683. */
  21684. this.parameterPositions = parameterPositions;
  21685. /**
  21686. * A cache index.
  21687. *
  21688. * @private
  21689. * @type {number}
  21690. * @default 0
  21691. */
  21692. this._cachedIndex = 0;
  21693. /**
  21694. * The result buffer.
  21695. *
  21696. * @type {TypedArray}
  21697. */
  21698. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  21699. /**
  21700. * The sample values.
  21701. *
  21702. * @type {TypedArray}
  21703. */
  21704. this.sampleValues = sampleValues;
  21705. /**
  21706. * The value size.
  21707. *
  21708. * @type {TypedArray}
  21709. */
  21710. this.valueSize = sampleSize;
  21711. /**
  21712. * The interpolation settings.
  21713. *
  21714. * @type {?Object}
  21715. * @default null
  21716. */
  21717. this.settings = null;
  21718. /**
  21719. * The default settings object.
  21720. *
  21721. * @type {Object}
  21722. */
  21723. this.DefaultSettings_ = {};
  21724. }
  21725. /**
  21726. * Evaluate the interpolant at position `t`.
  21727. *
  21728. * @param {number} t - The interpolation factor.
  21729. * @return {TypedArray} The result buffer.
  21730. */
  21731. evaluate( t ) {
  21732. const pp = this.parameterPositions;
  21733. let i1 = this._cachedIndex,
  21734. t1 = pp[ i1 ],
  21735. t0 = pp[ i1 - 1 ];
  21736. validate_interval: {
  21737. seek: {
  21738. let right;
  21739. linear_scan: {
  21740. //- See http://jsperf.com/comparison-to-undefined/3
  21741. //- slower code:
  21742. //-
  21743. //- if ( t >= t1 || t1 === undefined ) {
  21744. forward_scan: if ( ! ( t < t1 ) ) {
  21745. for ( let giveUpAt = i1 + 2; ; ) {
  21746. if ( t1 === undefined ) {
  21747. if ( t < t0 ) break forward_scan;
  21748. // after end
  21749. i1 = pp.length;
  21750. this._cachedIndex = i1;
  21751. return this.copySampleValue_( i1 - 1 );
  21752. }
  21753. if ( i1 === giveUpAt ) break; // this loop
  21754. t0 = t1;
  21755. t1 = pp[ ++ i1 ];
  21756. if ( t < t1 ) {
  21757. // we have arrived at the sought interval
  21758. break seek;
  21759. }
  21760. }
  21761. // prepare binary search on the right side of the index
  21762. right = pp.length;
  21763. break linear_scan;
  21764. }
  21765. //- slower code:
  21766. //- if ( t < t0 || t0 === undefined ) {
  21767. if ( ! ( t >= t0 ) ) {
  21768. // looping?
  21769. const t1global = pp[ 1 ];
  21770. if ( t < t1global ) {
  21771. i1 = 2; // + 1, using the scan for the details
  21772. t0 = t1global;
  21773. }
  21774. // linear reverse scan
  21775. for ( let giveUpAt = i1 - 2; ; ) {
  21776. if ( t0 === undefined ) {
  21777. // before start
  21778. this._cachedIndex = 0;
  21779. return this.copySampleValue_( 0 );
  21780. }
  21781. if ( i1 === giveUpAt ) break; // this loop
  21782. t1 = t0;
  21783. t0 = pp[ -- i1 - 1 ];
  21784. if ( t >= t0 ) {
  21785. // we have arrived at the sought interval
  21786. break seek;
  21787. }
  21788. }
  21789. // prepare binary search on the left side of the index
  21790. right = i1;
  21791. i1 = 0;
  21792. break linear_scan;
  21793. }
  21794. // the interval is valid
  21795. break validate_interval;
  21796. } // linear scan
  21797. // binary search
  21798. while ( i1 < right ) {
  21799. const mid = ( i1 + right ) >>> 1;
  21800. if ( t < pp[ mid ] ) {
  21801. right = mid;
  21802. } else {
  21803. i1 = mid + 1;
  21804. }
  21805. }
  21806. t1 = pp[ i1 ];
  21807. t0 = pp[ i1 - 1 ];
  21808. // check boundary cases, again
  21809. if ( t0 === undefined ) {
  21810. this._cachedIndex = 0;
  21811. return this.copySampleValue_( 0 );
  21812. }
  21813. if ( t1 === undefined ) {
  21814. i1 = pp.length;
  21815. this._cachedIndex = i1;
  21816. return this.copySampleValue_( i1 - 1 );
  21817. }
  21818. } // seek
  21819. this._cachedIndex = i1;
  21820. this.intervalChanged_( i1, t0, t1 );
  21821. } // validate_interval
  21822. return this.interpolate_( i1, t0, t, t1 );
  21823. }
  21824. /**
  21825. * Returns the interpolation settings.
  21826. *
  21827. * @return {Object} The interpolation settings.
  21828. */
  21829. getSettings_() {
  21830. return this.settings || this.DefaultSettings_;
  21831. }
  21832. /**
  21833. * Copies a sample value to the result buffer.
  21834. *
  21835. * @param {number} index - An index into the sample value buffer.
  21836. * @return {TypedArray} The result buffer.
  21837. */
  21838. copySampleValue_( index ) {
  21839. // copies a sample value to the result buffer
  21840. const result = this.resultBuffer,
  21841. values = this.sampleValues,
  21842. stride = this.valueSize,
  21843. offset = index * stride;
  21844. for ( let i = 0; i !== stride; ++ i ) {
  21845. result[ i ] = values[ offset + i ];
  21846. }
  21847. return result;
  21848. }
  21849. /**
  21850. * Copies a sample value to the result buffer.
  21851. *
  21852. * @abstract
  21853. * @param {number} i1 - An index into the sample value buffer.
  21854. * @param {number} t0 - The previous interpolation factor.
  21855. * @param {number} t - The current interpolation factor.
  21856. * @param {number} t1 - The next interpolation factor.
  21857. * @return {TypedArray} The result buffer.
  21858. */
  21859. interpolate_( /* i1, t0, t, t1 */ ) {
  21860. throw new Error( 'call to abstract method' );
  21861. // implementations shall return this.resultBuffer
  21862. }
  21863. /**
  21864. * Optional method that is executed when the interval has changed.
  21865. *
  21866. * @param {number} i1 - An index into the sample value buffer.
  21867. * @param {number} t0 - The previous interpolation factor.
  21868. * @param {number} t - The current interpolation factor.
  21869. */
  21870. intervalChanged_( /* i1, t0, t1 */ ) {
  21871. // empty
  21872. }
  21873. }
  21874. /**
  21875. * Fast and simple cubic spline interpolant.
  21876. *
  21877. * It was derived from a Hermitian construction setting the first derivative
  21878. * at each sample position to the linear slope between neighboring positions
  21879. * over their parameter interval.
  21880. *
  21881. * @augments Interpolant
  21882. */
  21883. class CubicInterpolant extends Interpolant {
  21884. /**
  21885. * Constructs a new cubic interpolant.
  21886. *
  21887. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  21888. * @param {TypedArray} sampleValues - The sample values.
  21889. * @param {number} sampleSize - The sample size
  21890. * @param {TypedArray} [resultBuffer] - The result buffer.
  21891. */
  21892. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21893. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21894. this._weightPrev = -0;
  21895. this._offsetPrev = -0;
  21896. this._weightNext = -0;
  21897. this._offsetNext = -0;
  21898. this.DefaultSettings_ = {
  21899. endingStart: ZeroCurvatureEnding,
  21900. endingEnd: ZeroCurvatureEnding
  21901. };
  21902. }
  21903. intervalChanged_( i1, t0, t1 ) {
  21904. const pp = this.parameterPositions;
  21905. let iPrev = i1 - 2,
  21906. iNext = i1 + 1,
  21907. tPrev = pp[ iPrev ],
  21908. tNext = pp[ iNext ];
  21909. if ( tPrev === undefined ) {
  21910. switch ( this.getSettings_().endingStart ) {
  21911. case ZeroSlopeEnding:
  21912. // f'(t0) = 0
  21913. iPrev = i1;
  21914. tPrev = 2 * t0 - t1;
  21915. break;
  21916. case WrapAroundEnding:
  21917. // use the other end of the curve
  21918. iPrev = pp.length - 2;
  21919. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  21920. break;
  21921. default: // ZeroCurvatureEnding
  21922. // f''(t0) = 0 a.k.a. Natural Spline
  21923. iPrev = i1;
  21924. tPrev = t1;
  21925. }
  21926. }
  21927. if ( tNext === undefined ) {
  21928. switch ( this.getSettings_().endingEnd ) {
  21929. case ZeroSlopeEnding:
  21930. // f'(tN) = 0
  21931. iNext = i1;
  21932. tNext = 2 * t1 - t0;
  21933. break;
  21934. case WrapAroundEnding:
  21935. // use the other end of the curve
  21936. iNext = 1;
  21937. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  21938. break;
  21939. default: // ZeroCurvatureEnding
  21940. // f''(tN) = 0, a.k.a. Natural Spline
  21941. iNext = i1 - 1;
  21942. tNext = t0;
  21943. }
  21944. }
  21945. const halfDt = ( t1 - t0 ) * 0.5,
  21946. stride = this.valueSize;
  21947. this._weightPrev = halfDt / ( t0 - tPrev );
  21948. this._weightNext = halfDt / ( tNext - t1 );
  21949. this._offsetPrev = iPrev * stride;
  21950. this._offsetNext = iNext * stride;
  21951. }
  21952. interpolate_( i1, t0, t, t1 ) {
  21953. const result = this.resultBuffer,
  21954. values = this.sampleValues,
  21955. stride = this.valueSize,
  21956. o1 = i1 * stride, o0 = o1 - stride,
  21957. oP = this._offsetPrev, oN = this._offsetNext,
  21958. wP = this._weightPrev, wN = this._weightNext,
  21959. p = ( t - t0 ) / ( t1 - t0 ),
  21960. pp = p * p,
  21961. ppp = pp * p;
  21962. // evaluate polynomials
  21963. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  21964. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  21965. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  21966. const sN = wN * ppp - wN * pp;
  21967. // combine data linearly
  21968. for ( let i = 0; i !== stride; ++ i ) {
  21969. result[ i ] =
  21970. sP * values[ oP + i ] +
  21971. s0 * values[ o0 + i ] +
  21972. s1 * values[ o1 + i ] +
  21973. sN * values[ oN + i ];
  21974. }
  21975. return result;
  21976. }
  21977. }
  21978. /**
  21979. * A basic linear interpolant.
  21980. *
  21981. * @augments Interpolant
  21982. */
  21983. class LinearInterpolant extends Interpolant {
  21984. /**
  21985. * Constructs a new linear interpolant.
  21986. *
  21987. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  21988. * @param {TypedArray} sampleValues - The sample values.
  21989. * @param {number} sampleSize - The sample size
  21990. * @param {TypedArray} [resultBuffer] - The result buffer.
  21991. */
  21992. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21993. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21994. }
  21995. interpolate_( i1, t0, t, t1 ) {
  21996. const result = this.resultBuffer,
  21997. values = this.sampleValues,
  21998. stride = this.valueSize,
  21999. offset1 = i1 * stride,
  22000. offset0 = offset1 - stride,
  22001. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22002. weight0 = 1 - weight1;
  22003. for ( let i = 0; i !== stride; ++ i ) {
  22004. result[ i ] =
  22005. values[ offset0 + i ] * weight0 +
  22006. values[ offset1 + i ] * weight1;
  22007. }
  22008. return result;
  22009. }
  22010. }
  22011. /**
  22012. * Interpolant that evaluates to the sample value at the position preceding
  22013. * the parameter.
  22014. *
  22015. * @augments Interpolant
  22016. */
  22017. class DiscreteInterpolant extends Interpolant {
  22018. /**
  22019. * Constructs a new discrete interpolant.
  22020. *
  22021. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  22022. * @param {TypedArray} sampleValues - The sample values.
  22023. * @param {number} sampleSize - The sample size
  22024. * @param {TypedArray} [resultBuffer] - The result buffer.
  22025. */
  22026. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22027. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22028. }
  22029. interpolate_( i1 /*, t0, t, t1 */ ) {
  22030. return this.copySampleValue_( i1 - 1 );
  22031. }
  22032. }
  22033. class KeyframeTrack {
  22034. constructor( name, times, values, interpolation ) {
  22035. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22036. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22037. this.name = name;
  22038. this.times = convertArray( times, this.TimeBufferType );
  22039. this.values = convertArray( values, this.ValueBufferType );
  22040. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22041. }
  22042. // Serialization (in static context, because of constructor invocation
  22043. // and automatic invocation of .toJSON):
  22044. static toJSON( track ) {
  22045. const trackType = track.constructor;
  22046. let json;
  22047. // derived classes can define a static toJSON method
  22048. if ( trackType.toJSON !== this.toJSON ) {
  22049. json = trackType.toJSON( track );
  22050. } else {
  22051. // by default, we assume the data can be serialized as-is
  22052. json = {
  22053. 'name': track.name,
  22054. 'times': convertArray( track.times, Array ),
  22055. 'values': convertArray( track.values, Array )
  22056. };
  22057. const interpolation = track.getInterpolation();
  22058. if ( interpolation !== track.DefaultInterpolation ) {
  22059. json.interpolation = interpolation;
  22060. }
  22061. }
  22062. json.type = track.ValueTypeName; // mandatory
  22063. return json;
  22064. }
  22065. InterpolantFactoryMethodDiscrete( result ) {
  22066. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22067. }
  22068. InterpolantFactoryMethodLinear( result ) {
  22069. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22070. }
  22071. InterpolantFactoryMethodSmooth( result ) {
  22072. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22073. }
  22074. setInterpolation( interpolation ) {
  22075. let factoryMethod;
  22076. switch ( interpolation ) {
  22077. case InterpolateDiscrete:
  22078. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22079. break;
  22080. case InterpolateLinear:
  22081. factoryMethod = this.InterpolantFactoryMethodLinear;
  22082. break;
  22083. case InterpolateSmooth:
  22084. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22085. break;
  22086. }
  22087. if ( factoryMethod === undefined ) {
  22088. const message = 'unsupported interpolation for ' +
  22089. this.ValueTypeName + ' keyframe track named ' + this.name;
  22090. if ( this.createInterpolant === undefined ) {
  22091. // fall back to default, unless the default itself is messed up
  22092. if ( interpolation !== this.DefaultInterpolation ) {
  22093. this.setInterpolation( this.DefaultInterpolation );
  22094. } else {
  22095. throw new Error( message ); // fatal, in this case
  22096. }
  22097. }
  22098. console.warn( 'THREE.KeyframeTrack:', message );
  22099. return this;
  22100. }
  22101. this.createInterpolant = factoryMethod;
  22102. return this;
  22103. }
  22104. getInterpolation() {
  22105. switch ( this.createInterpolant ) {
  22106. case this.InterpolantFactoryMethodDiscrete:
  22107. return InterpolateDiscrete;
  22108. case this.InterpolantFactoryMethodLinear:
  22109. return InterpolateLinear;
  22110. case this.InterpolantFactoryMethodSmooth:
  22111. return InterpolateSmooth;
  22112. }
  22113. }
  22114. getValueSize() {
  22115. return this.values.length / this.times.length;
  22116. }
  22117. // move all keyframes either forwards or backwards in time
  22118. shift( timeOffset ) {
  22119. if ( timeOffset !== 0.0 ) {
  22120. const times = this.times;
  22121. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22122. times[ i ] += timeOffset;
  22123. }
  22124. }
  22125. return this;
  22126. }
  22127. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22128. scale( timeScale ) {
  22129. if ( timeScale !== 1.0 ) {
  22130. const times = this.times;
  22131. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22132. times[ i ] *= timeScale;
  22133. }
  22134. }
  22135. return this;
  22136. }
  22137. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22138. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22139. trim( startTime, endTime ) {
  22140. const times = this.times,
  22141. nKeys = times.length;
  22142. let from = 0,
  22143. to = nKeys - 1;
  22144. while ( from !== nKeys && times[ from ] < startTime ) {
  22145. ++ from;
  22146. }
  22147. while ( to !== -1 && times[ to ] > endTime ) {
  22148. -- to;
  22149. }
  22150. ++ to; // inclusive -> exclusive bound
  22151. if ( from !== 0 || to !== nKeys ) {
  22152. // empty tracks are forbidden, so keep at least one keyframe
  22153. if ( from >= to ) {
  22154. to = Math.max( to, 1 );
  22155. from = to - 1;
  22156. }
  22157. const stride = this.getValueSize();
  22158. this.times = times.slice( from, to );
  22159. this.values = this.values.slice( from * stride, to * stride );
  22160. }
  22161. return this;
  22162. }
  22163. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22164. validate() {
  22165. let valid = true;
  22166. const valueSize = this.getValueSize();
  22167. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22168. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22169. valid = false;
  22170. }
  22171. const times = this.times,
  22172. values = this.values,
  22173. nKeys = times.length;
  22174. if ( nKeys === 0 ) {
  22175. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22176. valid = false;
  22177. }
  22178. let prevTime = null;
  22179. for ( let i = 0; i !== nKeys; i ++ ) {
  22180. const currTime = times[ i ];
  22181. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22182. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22183. valid = false;
  22184. break;
  22185. }
  22186. if ( prevTime !== null && prevTime > currTime ) {
  22187. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22188. valid = false;
  22189. break;
  22190. }
  22191. prevTime = currTime;
  22192. }
  22193. if ( values !== undefined ) {
  22194. if ( isTypedArray( values ) ) {
  22195. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22196. const value = values[ i ];
  22197. if ( isNaN( value ) ) {
  22198. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22199. valid = false;
  22200. break;
  22201. }
  22202. }
  22203. }
  22204. }
  22205. return valid;
  22206. }
  22207. // removes equivalent sequential keys as common in morph target sequences
  22208. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22209. optimize() {
  22210. // times or values may be shared with other tracks, so overwriting is unsafe
  22211. const times = this.times.slice(),
  22212. values = this.values.slice(),
  22213. stride = this.getValueSize(),
  22214. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22215. lastIndex = times.length - 1;
  22216. let writeIndex = 1;
  22217. for ( let i = 1; i < lastIndex; ++ i ) {
  22218. let keep = false;
  22219. const time = times[ i ];
  22220. const timeNext = times[ i + 1 ];
  22221. // remove adjacent keyframes scheduled at the same time
  22222. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22223. if ( ! smoothInterpolation ) {
  22224. // remove unnecessary keyframes same as their neighbors
  22225. const offset = i * stride,
  22226. offsetP = offset - stride,
  22227. offsetN = offset + stride;
  22228. for ( let j = 0; j !== stride; ++ j ) {
  22229. const value = values[ offset + j ];
  22230. if ( value !== values[ offsetP + j ] ||
  22231. value !== values[ offsetN + j ] ) {
  22232. keep = true;
  22233. break;
  22234. }
  22235. }
  22236. } else {
  22237. keep = true;
  22238. }
  22239. }
  22240. // in-place compaction
  22241. if ( keep ) {
  22242. if ( i !== writeIndex ) {
  22243. times[ writeIndex ] = times[ i ];
  22244. const readOffset = i * stride,
  22245. writeOffset = writeIndex * stride;
  22246. for ( let j = 0; j !== stride; ++ j ) {
  22247. values[ writeOffset + j ] = values[ readOffset + j ];
  22248. }
  22249. }
  22250. ++ writeIndex;
  22251. }
  22252. }
  22253. // flush last keyframe (compaction looks ahead)
  22254. if ( lastIndex > 0 ) {
  22255. times[ writeIndex ] = times[ lastIndex ];
  22256. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22257. values[ writeOffset + j ] = values[ readOffset + j ];
  22258. }
  22259. ++ writeIndex;
  22260. }
  22261. if ( writeIndex !== times.length ) {
  22262. this.times = times.slice( 0, writeIndex );
  22263. this.values = values.slice( 0, writeIndex * stride );
  22264. } else {
  22265. this.times = times;
  22266. this.values = values;
  22267. }
  22268. return this;
  22269. }
  22270. clone() {
  22271. const times = this.times.slice();
  22272. const values = this.values.slice();
  22273. const TypedKeyframeTrack = this.constructor;
  22274. const track = new TypedKeyframeTrack( this.name, times, values );
  22275. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22276. track.createInterpolant = this.createInterpolant;
  22277. return track;
  22278. }
  22279. }
  22280. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22281. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22282. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22283. /**
  22284. * A Track of Boolean keyframe values.
  22285. */
  22286. class BooleanKeyframeTrack extends KeyframeTrack {
  22287. // No interpolation parameter because only InterpolateDiscrete is valid.
  22288. constructor( name, times, values ) {
  22289. super( name, times, values );
  22290. }
  22291. }
  22292. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22293. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22294. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22295. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22296. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22297. /**
  22298. * A Track of keyframe values that represent color.
  22299. */
  22300. class ColorKeyframeTrack extends KeyframeTrack {}
  22301. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22302. /**
  22303. * A Track of numeric keyframe values.
  22304. */
  22305. class NumberKeyframeTrack extends KeyframeTrack {}
  22306. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22307. /**
  22308. * Spherical linear unit quaternion interpolant.
  22309. *
  22310. * @augments Interpolant
  22311. */
  22312. class QuaternionLinearInterpolant extends Interpolant {
  22313. /**
  22314. * Constructs a new SLERP interpolant.
  22315. *
  22316. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  22317. * @param {TypedArray} sampleValues - The sample values.
  22318. * @param {number} sampleSize - The sample size
  22319. * @param {TypedArray} [resultBuffer] - The result buffer.
  22320. */
  22321. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22322. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22323. }
  22324. interpolate_( i1, t0, t, t1 ) {
  22325. const result = this.resultBuffer,
  22326. values = this.sampleValues,
  22327. stride = this.valueSize,
  22328. alpha = ( t - t0 ) / ( t1 - t0 );
  22329. let offset = i1 * stride;
  22330. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22331. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22332. }
  22333. return result;
  22334. }
  22335. }
  22336. /**
  22337. * A Track of quaternion keyframe values.
  22338. */
  22339. class QuaternionKeyframeTrack extends KeyframeTrack {
  22340. InterpolantFactoryMethodLinear( result ) {
  22341. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22342. }
  22343. }
  22344. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  22345. // ValueBufferType is inherited
  22346. // DefaultInterpolation is inherited;
  22347. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22348. /**
  22349. * A Track that interpolates Strings
  22350. */
  22351. class StringKeyframeTrack extends KeyframeTrack {
  22352. // No interpolation parameter because only InterpolateDiscrete is valid.
  22353. constructor( name, times, values ) {
  22354. super( name, times, values );
  22355. }
  22356. }
  22357. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22358. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22359. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22360. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22361. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22362. /**
  22363. * A Track of vectored keyframe values.
  22364. */
  22365. class VectorKeyframeTrack extends KeyframeTrack {}
  22366. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  22367. class AnimationClip {
  22368. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  22369. this.name = name;
  22370. this.tracks = tracks;
  22371. this.duration = duration;
  22372. this.blendMode = blendMode;
  22373. this.uuid = generateUUID();
  22374. // this means it should figure out its duration by scanning the tracks
  22375. if ( this.duration < 0 ) {
  22376. this.resetDuration();
  22377. }
  22378. }
  22379. static parse( json ) {
  22380. const tracks = [],
  22381. jsonTracks = json.tracks,
  22382. frameTime = 1.0 / ( json.fps || 1.0 );
  22383. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22384. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22385. }
  22386. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  22387. clip.uuid = json.uuid;
  22388. return clip;
  22389. }
  22390. static toJSON( clip ) {
  22391. const tracks = [],
  22392. clipTracks = clip.tracks;
  22393. const json = {
  22394. 'name': clip.name,
  22395. 'duration': clip.duration,
  22396. 'tracks': tracks,
  22397. 'uuid': clip.uuid,
  22398. 'blendMode': clip.blendMode
  22399. };
  22400. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22401. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22402. }
  22403. return json;
  22404. }
  22405. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  22406. const numMorphTargets = morphTargetSequence.length;
  22407. const tracks = [];
  22408. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22409. let times = [];
  22410. let values = [];
  22411. times.push(
  22412. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22413. i,
  22414. ( i + 1 ) % numMorphTargets );
  22415. values.push( 0, 1, 0 );
  22416. const order = getKeyframeOrder( times );
  22417. times = sortedArray( times, 1, order );
  22418. values = sortedArray( values, 1, order );
  22419. // if there is a key at the first frame, duplicate it as the
  22420. // last frame as well for perfect loop.
  22421. if ( ! noLoop && times[ 0 ] === 0 ) {
  22422. times.push( numMorphTargets );
  22423. values.push( values[ 0 ] );
  22424. }
  22425. tracks.push(
  22426. new NumberKeyframeTrack(
  22427. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22428. times, values
  22429. ).scale( 1.0 / fps ) );
  22430. }
  22431. return new this( name, -1, tracks );
  22432. }
  22433. static findByName( objectOrClipArray, name ) {
  22434. let clipArray = objectOrClipArray;
  22435. if ( ! Array.isArray( objectOrClipArray ) ) {
  22436. const o = objectOrClipArray;
  22437. clipArray = o.geometry && o.geometry.animations || o.animations;
  22438. }
  22439. for ( let i = 0; i < clipArray.length; i ++ ) {
  22440. if ( clipArray[ i ].name === name ) {
  22441. return clipArray[ i ];
  22442. }
  22443. }
  22444. return null;
  22445. }
  22446. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  22447. const animationToMorphTargets = {};
  22448. // tested with https://regex101.com/ on trick sequences
  22449. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22450. const pattern = /^([\w-]*?)([\d]+)$/;
  22451. // sort morph target names into animation groups based
  22452. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22453. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22454. const morphTarget = morphTargets[ i ];
  22455. const parts = morphTarget.name.match( pattern );
  22456. if ( parts && parts.length > 1 ) {
  22457. const name = parts[ 1 ];
  22458. let animationMorphTargets = animationToMorphTargets[ name ];
  22459. if ( ! animationMorphTargets ) {
  22460. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22461. }
  22462. animationMorphTargets.push( morphTarget );
  22463. }
  22464. }
  22465. const clips = [];
  22466. for ( const name in animationToMorphTargets ) {
  22467. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22468. }
  22469. return clips;
  22470. }
  22471. // parse the animation.hierarchy format
  22472. static parseAnimation( animation, bones ) {
  22473. if ( ! animation ) {
  22474. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22475. return null;
  22476. }
  22477. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22478. // only return track if there are actually keys.
  22479. if ( animationKeys.length !== 0 ) {
  22480. const times = [];
  22481. const values = [];
  22482. flattenJSON( animationKeys, times, values, propertyName );
  22483. // empty keys are filtered out, so check again
  22484. if ( times.length !== 0 ) {
  22485. destTracks.push( new trackType( trackName, times, values ) );
  22486. }
  22487. }
  22488. };
  22489. const tracks = [];
  22490. const clipName = animation.name || 'default';
  22491. const fps = animation.fps || 30;
  22492. const blendMode = animation.blendMode;
  22493. // automatic length determination in AnimationClip.
  22494. let duration = animation.length || -1;
  22495. const hierarchyTracks = animation.hierarchy || [];
  22496. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22497. const animationKeys = hierarchyTracks[ h ].keys;
  22498. // skip empty tracks
  22499. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22500. // process morph targets
  22501. if ( animationKeys[ 0 ].morphTargets ) {
  22502. // figure out all morph targets used in this track
  22503. const morphTargetNames = {};
  22504. let k;
  22505. for ( k = 0; k < animationKeys.length; k ++ ) {
  22506. if ( animationKeys[ k ].morphTargets ) {
  22507. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22508. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  22509. }
  22510. }
  22511. }
  22512. // create a track for each morph target with all zero
  22513. // morphTargetInfluences except for the keys in which
  22514. // the morphTarget is named.
  22515. for ( const morphTargetName in morphTargetNames ) {
  22516. const times = [];
  22517. const values = [];
  22518. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22519. const animationKey = animationKeys[ k ];
  22520. times.push( animationKey.time );
  22521. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22522. }
  22523. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22524. }
  22525. duration = morphTargetNames.length * fps;
  22526. } else {
  22527. // ...assume skeletal animation
  22528. const boneName = '.bones[' + bones[ h ].name + ']';
  22529. addNonemptyTrack(
  22530. VectorKeyframeTrack, boneName + '.position',
  22531. animationKeys, 'pos', tracks );
  22532. addNonemptyTrack(
  22533. QuaternionKeyframeTrack, boneName + '.quaternion',
  22534. animationKeys, 'rot', tracks );
  22535. addNonemptyTrack(
  22536. VectorKeyframeTrack, boneName + '.scale',
  22537. animationKeys, 'scl', tracks );
  22538. }
  22539. }
  22540. if ( tracks.length === 0 ) {
  22541. return null;
  22542. }
  22543. const clip = new this( clipName, duration, tracks, blendMode );
  22544. return clip;
  22545. }
  22546. resetDuration() {
  22547. const tracks = this.tracks;
  22548. let duration = 0;
  22549. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22550. const track = this.tracks[ i ];
  22551. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22552. }
  22553. this.duration = duration;
  22554. return this;
  22555. }
  22556. trim() {
  22557. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22558. this.tracks[ i ].trim( 0, this.duration );
  22559. }
  22560. return this;
  22561. }
  22562. validate() {
  22563. let valid = true;
  22564. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22565. valid = valid && this.tracks[ i ].validate();
  22566. }
  22567. return valid;
  22568. }
  22569. optimize() {
  22570. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22571. this.tracks[ i ].optimize();
  22572. }
  22573. return this;
  22574. }
  22575. clone() {
  22576. const tracks = [];
  22577. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22578. tracks.push( this.tracks[ i ].clone() );
  22579. }
  22580. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  22581. }
  22582. toJSON() {
  22583. return this.constructor.toJSON( this );
  22584. }
  22585. }
  22586. function getTrackTypeForValueTypeName( typeName ) {
  22587. switch ( typeName.toLowerCase() ) {
  22588. case 'scalar':
  22589. case 'double':
  22590. case 'float':
  22591. case 'number':
  22592. case 'integer':
  22593. return NumberKeyframeTrack;
  22594. case 'vector':
  22595. case 'vector2':
  22596. case 'vector3':
  22597. case 'vector4':
  22598. return VectorKeyframeTrack;
  22599. case 'color':
  22600. return ColorKeyframeTrack;
  22601. case 'quaternion':
  22602. return QuaternionKeyframeTrack;
  22603. case 'bool':
  22604. case 'boolean':
  22605. return BooleanKeyframeTrack;
  22606. case 'string':
  22607. return StringKeyframeTrack;
  22608. }
  22609. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22610. }
  22611. function parseKeyframeTrack( json ) {
  22612. if ( json.type === undefined ) {
  22613. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22614. }
  22615. const trackType = getTrackTypeForValueTypeName( json.type );
  22616. if ( json.times === undefined ) {
  22617. const times = [], values = [];
  22618. flattenJSON( json.keys, times, values, 'value' );
  22619. json.times = times;
  22620. json.values = values;
  22621. }
  22622. // derived classes can define a static parse method
  22623. if ( trackType.parse !== undefined ) {
  22624. return trackType.parse( json );
  22625. } else {
  22626. // by default, we assume a constructor compatible with the base
  22627. return new trackType( json.name, json.times, json.values, json.interpolation );
  22628. }
  22629. }
  22630. const Cache = {
  22631. enabled: false,
  22632. files: {},
  22633. add: function ( key, file ) {
  22634. if ( this.enabled === false ) return;
  22635. // console.log( 'THREE.Cache', 'Adding key:', key );
  22636. this.files[ key ] = file;
  22637. },
  22638. get: function ( key ) {
  22639. if ( this.enabled === false ) return;
  22640. // console.log( 'THREE.Cache', 'Checking key:', key );
  22641. return this.files[ key ];
  22642. },
  22643. remove: function ( key ) {
  22644. delete this.files[ key ];
  22645. },
  22646. clear: function () {
  22647. this.files = {};
  22648. }
  22649. };
  22650. class LoadingManager {
  22651. constructor( onLoad, onProgress, onError ) {
  22652. const scope = this;
  22653. let isLoading = false;
  22654. let itemsLoaded = 0;
  22655. let itemsTotal = 0;
  22656. let urlModifier = undefined;
  22657. const handlers = [];
  22658. // Refer to #5689 for the reason why we don't set .onStart
  22659. // in the constructor
  22660. this.onStart = undefined;
  22661. this.onLoad = onLoad;
  22662. this.onProgress = onProgress;
  22663. this.onError = onError;
  22664. this.itemStart = function ( url ) {
  22665. itemsTotal ++;
  22666. if ( isLoading === false ) {
  22667. if ( scope.onStart !== undefined ) {
  22668. scope.onStart( url, itemsLoaded, itemsTotal );
  22669. }
  22670. }
  22671. isLoading = true;
  22672. };
  22673. this.itemEnd = function ( url ) {
  22674. itemsLoaded ++;
  22675. if ( scope.onProgress !== undefined ) {
  22676. scope.onProgress( url, itemsLoaded, itemsTotal );
  22677. }
  22678. if ( itemsLoaded === itemsTotal ) {
  22679. isLoading = false;
  22680. if ( scope.onLoad !== undefined ) {
  22681. scope.onLoad();
  22682. }
  22683. }
  22684. };
  22685. this.itemError = function ( url ) {
  22686. if ( scope.onError !== undefined ) {
  22687. scope.onError( url );
  22688. }
  22689. };
  22690. this.resolveURL = function ( url ) {
  22691. if ( urlModifier ) {
  22692. return urlModifier( url );
  22693. }
  22694. return url;
  22695. };
  22696. this.setURLModifier = function ( transform ) {
  22697. urlModifier = transform;
  22698. return this;
  22699. };
  22700. this.addHandler = function ( regex, loader ) {
  22701. handlers.push( regex, loader );
  22702. return this;
  22703. };
  22704. this.removeHandler = function ( regex ) {
  22705. const index = handlers.indexOf( regex );
  22706. if ( index !== -1 ) {
  22707. handlers.splice( index, 2 );
  22708. }
  22709. return this;
  22710. };
  22711. this.getHandler = function ( file ) {
  22712. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22713. const regex = handlers[ i ];
  22714. const loader = handlers[ i + 1 ];
  22715. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22716. if ( regex.test( file ) ) {
  22717. return loader;
  22718. }
  22719. }
  22720. return null;
  22721. };
  22722. }
  22723. }
  22724. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  22725. /**
  22726. * Abstract base class for loaders.
  22727. *
  22728. * @abstract
  22729. */
  22730. class Loader {
  22731. /**
  22732. * Constructs a new loader.
  22733. *
  22734. * @param {LoadingManager} [manager] - The loading manager.
  22735. */
  22736. constructor( manager ) {
  22737. /**
  22738. * The loading manager.
  22739. *
  22740. * @type {LoadingManager}
  22741. * @default DefaultLoadingManager
  22742. */
  22743. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22744. /**
  22745. * The crossOrigin string to implement CORS for loading the url from a
  22746. * different domain that allows CORS.
  22747. *
  22748. * @type {string}
  22749. * @default 'anonymous'
  22750. */
  22751. this.crossOrigin = 'anonymous';
  22752. /**
  22753. * Whether the XMLHttpRequest uses credentials.
  22754. *
  22755. * @type {boolean}
  22756. * @default false
  22757. */
  22758. this.withCredentials = false;
  22759. /**
  22760. * The base path from which the asset will be loaded.
  22761. *
  22762. * @type {string}
  22763. */
  22764. this.path = '';
  22765. /**
  22766. * The base path from which additional resources like textures will be loaded.
  22767. *
  22768. * @type {string}
  22769. */
  22770. this.resourcePath = '';
  22771. /**
  22772. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  22773. * used in HTTP request.
  22774. *
  22775. * @type {Object}
  22776. */
  22777. this.requestHeader = {};
  22778. }
  22779. /**
  22780. * This method needs to be implemented by all concrete loaders. It holds the
  22781. * logic for loading assets from the backend.
  22782. *
  22783. * @param {string} url - The path/URL of the file to be loaded.
  22784. * @param {Function} onLoad - Executed when the loading process has been finished.
  22785. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  22786. * @param {onErrorCallback} onError - Executed when errors occur.
  22787. */
  22788. load( /* url, onLoad, onProgress, onError */ ) {}
  22789. /**
  22790. * A async version of {@link Loader#load}.
  22791. *
  22792. * @param {string} url - The path/URL of the file to be loaded.
  22793. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  22794. * @return {Promise} A Promise that resolves when the asset has been loaded.
  22795. */
  22796. loadAsync( url, onProgress ) {
  22797. const scope = this;
  22798. return new Promise( function ( resolve, reject ) {
  22799. scope.load( url, resolve, onProgress, reject );
  22800. } );
  22801. }
  22802. /**
  22803. * This method needs to be implemented by all concrete loaders. It holds the
  22804. * logic for parsing the asset into three.js entities.
  22805. *
  22806. * @param {any} data - The data to parse.
  22807. */
  22808. parse( /* data */ ) {}
  22809. /**
  22810. * Sets the `crossOrigin` String to implement CORS for loading the URL
  22811. * from a different domain that allows CORS.
  22812. *
  22813. * @param {string} crossOrigin - The `crossOrigin` value.
  22814. * @return {Loader} A reference to this instance.
  22815. */
  22816. setCrossOrigin( crossOrigin ) {
  22817. this.crossOrigin = crossOrigin;
  22818. return this;
  22819. }
  22820. /**
  22821. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  22822. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  22823. *
  22824. * Note: This setting has no effect if you are loading files locally or from the same domain.
  22825. *
  22826. * @param {boolean} value - The `withCredentials` value.
  22827. * @return {Loader} A reference to this instance.
  22828. */
  22829. setWithCredentials( value ) {
  22830. this.withCredentials = value;
  22831. return this;
  22832. }
  22833. /**
  22834. * Sets the base path for the asset.
  22835. *
  22836. * @param {string} path - The base path.
  22837. * @return {Loader} A reference to this instance.
  22838. */
  22839. setPath( path ) {
  22840. this.path = path;
  22841. return this;
  22842. }
  22843. /**
  22844. * Sets the base path for dependent resources like textures.
  22845. *
  22846. * @param {string} resourcePath - The resource path.
  22847. * @return {Loader} A reference to this instance.
  22848. */
  22849. setResourcePath( resourcePath ) {
  22850. this.resourcePath = resourcePath;
  22851. return this;
  22852. }
  22853. /**
  22854. * Sets the given request header.
  22855. *
  22856. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  22857. * for configuring the HTTP request.
  22858. * @return {Loader} A reference to this instance.
  22859. */
  22860. setRequestHeader( requestHeader ) {
  22861. this.requestHeader = requestHeader;
  22862. return this;
  22863. }
  22864. }
  22865. /**
  22866. * Callback for onProgress in loaders.
  22867. *
  22868. *
  22869. * @callback onProgressCallback
  22870. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  22871. */
  22872. /**
  22873. * Callback for onError in loaders.
  22874. *
  22875. *
  22876. * @callback onErrorCallback
  22877. * @param {Error} error - The error which occured during the loading process.
  22878. */
  22879. /**
  22880. * The default material name that is used by loaders
  22881. * when creating materials for loaded 3D objects.
  22882. *
  22883. * Note: Not all loaders might honor this setting.
  22884. *
  22885. * @static
  22886. * @type {string}
  22887. * @default '__DEFAULT'
  22888. */
  22889. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  22890. const loading = {};
  22891. class HttpError extends Error {
  22892. constructor( message, response ) {
  22893. super( message );
  22894. this.response = response;
  22895. }
  22896. }
  22897. class FileLoader extends Loader {
  22898. constructor( manager ) {
  22899. super( manager );
  22900. }
  22901. load( url, onLoad, onProgress, onError ) {
  22902. if ( url === undefined ) url = '';
  22903. if ( this.path !== undefined ) url = this.path + url;
  22904. url = this.manager.resolveURL( url );
  22905. const cached = Cache.get( url );
  22906. if ( cached !== undefined ) {
  22907. this.manager.itemStart( url );
  22908. setTimeout( () => {
  22909. if ( onLoad ) onLoad( cached );
  22910. this.manager.itemEnd( url );
  22911. }, 0 );
  22912. return cached;
  22913. }
  22914. // Check if request is duplicate
  22915. if ( loading[ url ] !== undefined ) {
  22916. loading[ url ].push( {
  22917. onLoad: onLoad,
  22918. onProgress: onProgress,
  22919. onError: onError
  22920. } );
  22921. return;
  22922. }
  22923. // Initialise array for duplicate requests
  22924. loading[ url ] = [];
  22925. loading[ url ].push( {
  22926. onLoad: onLoad,
  22927. onProgress: onProgress,
  22928. onError: onError,
  22929. } );
  22930. // create request
  22931. const req = new Request( url, {
  22932. headers: new Headers( this.requestHeader ),
  22933. credentials: this.withCredentials ? 'include' : 'same-origin',
  22934. // An abort controller could be added within a future PR
  22935. } );
  22936. // record states ( avoid data race )
  22937. const mimeType = this.mimeType;
  22938. const responseType = this.responseType;
  22939. // start the fetch
  22940. fetch( req )
  22941. .then( response => {
  22942. if ( response.status === 200 || response.status === 0 ) {
  22943. // Some browsers return HTTP Status 0 when using non-http protocol
  22944. // e.g. 'file://' or 'data://'. Handle as success.
  22945. if ( response.status === 0 ) {
  22946. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22947. }
  22948. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  22949. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  22950. return response;
  22951. }
  22952. const callbacks = loading[ url ];
  22953. const reader = response.body.getReader();
  22954. // Nginx needs X-File-Size check
  22955. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  22956. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  22957. const total = contentLength ? parseInt( contentLength ) : 0;
  22958. const lengthComputable = total !== 0;
  22959. let loaded = 0;
  22960. // periodically read data into the new stream tracking while download progress
  22961. const stream = new ReadableStream( {
  22962. start( controller ) {
  22963. readData();
  22964. function readData() {
  22965. reader.read().then( ( { done, value } ) => {
  22966. if ( done ) {
  22967. controller.close();
  22968. } else {
  22969. loaded += value.byteLength;
  22970. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  22971. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22972. const callback = callbacks[ i ];
  22973. if ( callback.onProgress ) callback.onProgress( event );
  22974. }
  22975. controller.enqueue( value );
  22976. readData();
  22977. }
  22978. }, ( e ) => {
  22979. controller.error( e );
  22980. } );
  22981. }
  22982. }
  22983. } );
  22984. return new Response( stream );
  22985. } else {
  22986. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  22987. }
  22988. } )
  22989. .then( response => {
  22990. switch ( responseType ) {
  22991. case 'arraybuffer':
  22992. return response.arrayBuffer();
  22993. case 'blob':
  22994. return response.blob();
  22995. case 'document':
  22996. return response.text()
  22997. .then( text => {
  22998. const parser = new DOMParser();
  22999. return parser.parseFromString( text, mimeType );
  23000. } );
  23001. case 'json':
  23002. return response.json();
  23003. default:
  23004. if ( mimeType === undefined ) {
  23005. return response.text();
  23006. } else {
  23007. // sniff encoding
  23008. const re = /charset="?([^;"\s]*)"?/i;
  23009. const exec = re.exec( mimeType );
  23010. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23011. const decoder = new TextDecoder( label );
  23012. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23013. }
  23014. }
  23015. } )
  23016. .then( data => {
  23017. // Add to cache only on HTTP success, so that we do not cache
  23018. // error response bodies as proper responses to requests.
  23019. Cache.add( url, data );
  23020. const callbacks = loading[ url ];
  23021. delete loading[ url ];
  23022. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23023. const callback = callbacks[ i ];
  23024. if ( callback.onLoad ) callback.onLoad( data );
  23025. }
  23026. } )
  23027. .catch( err => {
  23028. // Abort errors and other errors are handled the same
  23029. const callbacks = loading[ url ];
  23030. if ( callbacks === undefined ) {
  23031. // When onLoad was called and url was deleted in `loading`
  23032. this.manager.itemError( url );
  23033. throw err;
  23034. }
  23035. delete loading[ url ];
  23036. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23037. const callback = callbacks[ i ];
  23038. if ( callback.onError ) callback.onError( err );
  23039. }
  23040. this.manager.itemError( url );
  23041. } )
  23042. .finally( () => {
  23043. this.manager.itemEnd( url );
  23044. } );
  23045. this.manager.itemStart( url );
  23046. }
  23047. setResponseType( value ) {
  23048. this.responseType = value;
  23049. return this;
  23050. }
  23051. setMimeType( value ) {
  23052. this.mimeType = value;
  23053. return this;
  23054. }
  23055. }
  23056. class AnimationLoader extends Loader {
  23057. constructor( manager ) {
  23058. super( manager );
  23059. }
  23060. load( url, onLoad, onProgress, onError ) {
  23061. const scope = this;
  23062. const loader = new FileLoader( this.manager );
  23063. loader.setPath( this.path );
  23064. loader.setRequestHeader( this.requestHeader );
  23065. loader.setWithCredentials( this.withCredentials );
  23066. loader.load( url, function ( text ) {
  23067. try {
  23068. onLoad( scope.parse( JSON.parse( text ) ) );
  23069. } catch ( e ) {
  23070. if ( onError ) {
  23071. onError( e );
  23072. } else {
  23073. console.error( e );
  23074. }
  23075. scope.manager.itemError( url );
  23076. }
  23077. }, onProgress, onError );
  23078. }
  23079. parse( json ) {
  23080. const animations = [];
  23081. for ( let i = 0; i < json.length; i ++ ) {
  23082. const clip = AnimationClip.parse( json[ i ] );
  23083. animations.push( clip );
  23084. }
  23085. return animations;
  23086. }
  23087. }
  23088. /**
  23089. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23090. *
  23091. * Sub classes have to implement the parse() method which will be used in load().
  23092. */
  23093. class CompressedTextureLoader extends Loader {
  23094. constructor( manager ) {
  23095. super( manager );
  23096. }
  23097. load( url, onLoad, onProgress, onError ) {
  23098. const scope = this;
  23099. const images = [];
  23100. const texture = new CompressedTexture();
  23101. const loader = new FileLoader( this.manager );
  23102. loader.setPath( this.path );
  23103. loader.setResponseType( 'arraybuffer' );
  23104. loader.setRequestHeader( this.requestHeader );
  23105. loader.setWithCredentials( scope.withCredentials );
  23106. let loaded = 0;
  23107. function loadTexture( i ) {
  23108. loader.load( url[ i ], function ( buffer ) {
  23109. const texDatas = scope.parse( buffer, true );
  23110. images[ i ] = {
  23111. width: texDatas.width,
  23112. height: texDatas.height,
  23113. format: texDatas.format,
  23114. mipmaps: texDatas.mipmaps
  23115. };
  23116. loaded += 1;
  23117. if ( loaded === 6 ) {
  23118. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23119. texture.image = images;
  23120. texture.format = texDatas.format;
  23121. texture.needsUpdate = true;
  23122. if ( onLoad ) onLoad( texture );
  23123. }
  23124. }, onProgress, onError );
  23125. }
  23126. if ( Array.isArray( url ) ) {
  23127. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23128. loadTexture( i );
  23129. }
  23130. } else {
  23131. // compressed cubemap texture stored in a single DDS file
  23132. loader.load( url, function ( buffer ) {
  23133. const texDatas = scope.parse( buffer, true );
  23134. if ( texDatas.isCubemap ) {
  23135. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23136. for ( let f = 0; f < faces; f ++ ) {
  23137. images[ f ] = { mipmaps: [] };
  23138. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23139. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23140. images[ f ].format = texDatas.format;
  23141. images[ f ].width = texDatas.width;
  23142. images[ f ].height = texDatas.height;
  23143. }
  23144. }
  23145. texture.image = images;
  23146. } else {
  23147. texture.image.width = texDatas.width;
  23148. texture.image.height = texDatas.height;
  23149. texture.mipmaps = texDatas.mipmaps;
  23150. }
  23151. if ( texDatas.mipmapCount === 1 ) {
  23152. texture.minFilter = LinearFilter;
  23153. }
  23154. texture.format = texDatas.format;
  23155. texture.needsUpdate = true;
  23156. if ( onLoad ) onLoad( texture );
  23157. }, onProgress, onError );
  23158. }
  23159. return texture;
  23160. }
  23161. }
  23162. class ImageLoader extends Loader {
  23163. constructor( manager ) {
  23164. super( manager );
  23165. }
  23166. load( url, onLoad, onProgress, onError ) {
  23167. if ( this.path !== undefined ) url = this.path + url;
  23168. url = this.manager.resolveURL( url );
  23169. const scope = this;
  23170. const cached = Cache.get( url );
  23171. if ( cached !== undefined ) {
  23172. scope.manager.itemStart( url );
  23173. setTimeout( function () {
  23174. if ( onLoad ) onLoad( cached );
  23175. scope.manager.itemEnd( url );
  23176. }, 0 );
  23177. return cached;
  23178. }
  23179. const image = createElementNS( 'img' );
  23180. function onImageLoad() {
  23181. removeEventListeners();
  23182. Cache.add( url, this );
  23183. if ( onLoad ) onLoad( this );
  23184. scope.manager.itemEnd( url );
  23185. }
  23186. function onImageError( event ) {
  23187. removeEventListeners();
  23188. if ( onError ) onError( event );
  23189. scope.manager.itemError( url );
  23190. scope.manager.itemEnd( url );
  23191. }
  23192. function removeEventListeners() {
  23193. image.removeEventListener( 'load', onImageLoad, false );
  23194. image.removeEventListener( 'error', onImageError, false );
  23195. }
  23196. image.addEventListener( 'load', onImageLoad, false );
  23197. image.addEventListener( 'error', onImageError, false );
  23198. if ( url.slice( 0, 5 ) !== 'data:' ) {
  23199. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23200. }
  23201. scope.manager.itemStart( url );
  23202. image.src = url;
  23203. return image;
  23204. }
  23205. }
  23206. class CubeTextureLoader extends Loader {
  23207. constructor( manager ) {
  23208. super( manager );
  23209. }
  23210. load( urls, onLoad, onProgress, onError ) {
  23211. const texture = new CubeTexture();
  23212. texture.colorSpace = SRGBColorSpace;
  23213. const loader = new ImageLoader( this.manager );
  23214. loader.setCrossOrigin( this.crossOrigin );
  23215. loader.setPath( this.path );
  23216. let loaded = 0;
  23217. function loadTexture( i ) {
  23218. loader.load( urls[ i ], function ( image ) {
  23219. texture.images[ i ] = image;
  23220. loaded ++;
  23221. if ( loaded === 6 ) {
  23222. texture.needsUpdate = true;
  23223. if ( onLoad ) onLoad( texture );
  23224. }
  23225. }, undefined, onError );
  23226. }
  23227. for ( let i = 0; i < urls.length; ++ i ) {
  23228. loadTexture( i );
  23229. }
  23230. return texture;
  23231. }
  23232. }
  23233. /**
  23234. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23235. *
  23236. * Sub classes have to implement the parse() method which will be used in load().
  23237. */
  23238. class DataTextureLoader extends Loader {
  23239. constructor( manager ) {
  23240. super( manager );
  23241. }
  23242. load( url, onLoad, onProgress, onError ) {
  23243. const scope = this;
  23244. const texture = new DataTexture();
  23245. const loader = new FileLoader( this.manager );
  23246. loader.setResponseType( 'arraybuffer' );
  23247. loader.setRequestHeader( this.requestHeader );
  23248. loader.setPath( this.path );
  23249. loader.setWithCredentials( scope.withCredentials );
  23250. loader.load( url, function ( buffer ) {
  23251. let texData;
  23252. try {
  23253. texData = scope.parse( buffer );
  23254. } catch ( error ) {
  23255. if ( onError !== undefined ) {
  23256. onError( error );
  23257. } else {
  23258. console.error( error );
  23259. return;
  23260. }
  23261. }
  23262. if ( texData.image !== undefined ) {
  23263. texture.image = texData.image;
  23264. } else if ( texData.data !== undefined ) {
  23265. texture.image.width = texData.width;
  23266. texture.image.height = texData.height;
  23267. texture.image.data = texData.data;
  23268. }
  23269. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23270. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23271. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23272. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23273. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23274. if ( texData.colorSpace !== undefined ) {
  23275. texture.colorSpace = texData.colorSpace;
  23276. }
  23277. if ( texData.flipY !== undefined ) {
  23278. texture.flipY = texData.flipY;
  23279. }
  23280. if ( texData.format !== undefined ) {
  23281. texture.format = texData.format;
  23282. }
  23283. if ( texData.type !== undefined ) {
  23284. texture.type = texData.type;
  23285. }
  23286. if ( texData.mipmaps !== undefined ) {
  23287. texture.mipmaps = texData.mipmaps;
  23288. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23289. }
  23290. if ( texData.mipmapCount === 1 ) {
  23291. texture.minFilter = LinearFilter;
  23292. }
  23293. if ( texData.generateMipmaps !== undefined ) {
  23294. texture.generateMipmaps = texData.generateMipmaps;
  23295. }
  23296. texture.needsUpdate = true;
  23297. if ( onLoad ) onLoad( texture, texData );
  23298. }, onProgress, onError );
  23299. return texture;
  23300. }
  23301. }
  23302. class TextureLoader extends Loader {
  23303. constructor( manager ) {
  23304. super( manager );
  23305. }
  23306. load( url, onLoad, onProgress, onError ) {
  23307. const texture = new Texture();
  23308. const loader = new ImageLoader( this.manager );
  23309. loader.setCrossOrigin( this.crossOrigin );
  23310. loader.setPath( this.path );
  23311. loader.load( url, function ( image ) {
  23312. texture.image = image;
  23313. texture.needsUpdate = true;
  23314. if ( onLoad !== undefined ) {
  23315. onLoad( texture );
  23316. }
  23317. }, onProgress, onError );
  23318. return texture;
  23319. }
  23320. }
  23321. class Light extends Object3D {
  23322. constructor( color, intensity = 1 ) {
  23323. super();
  23324. this.isLight = true;
  23325. this.type = 'Light';
  23326. this.color = new Color( color );
  23327. this.intensity = intensity;
  23328. }
  23329. dispose() {
  23330. // Empty here in base class; some subclasses override.
  23331. }
  23332. copy( source, recursive ) {
  23333. super.copy( source, recursive );
  23334. this.color.copy( source.color );
  23335. this.intensity = source.intensity;
  23336. return this;
  23337. }
  23338. toJSON( meta ) {
  23339. const data = super.toJSON( meta );
  23340. data.object.color = this.color.getHex();
  23341. data.object.intensity = this.intensity;
  23342. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23343. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23344. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23345. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23346. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23347. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23348. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  23349. return data;
  23350. }
  23351. }
  23352. class HemisphereLight extends Light {
  23353. constructor( skyColor, groundColor, intensity ) {
  23354. super( skyColor, intensity );
  23355. this.isHemisphereLight = true;
  23356. this.type = 'HemisphereLight';
  23357. this.position.copy( Object3D.DEFAULT_UP );
  23358. this.updateMatrix();
  23359. this.groundColor = new Color( groundColor );
  23360. }
  23361. copy( source, recursive ) {
  23362. super.copy( source, recursive );
  23363. this.groundColor.copy( source.groundColor );
  23364. return this;
  23365. }
  23366. }
  23367. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23368. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23369. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23370. class LightShadow {
  23371. constructor( camera ) {
  23372. this.camera = camera;
  23373. this.intensity = 1;
  23374. this.bias = 0;
  23375. this.normalBias = 0;
  23376. this.radius = 1;
  23377. this.blurSamples = 8;
  23378. this.mapSize = new Vector2( 512, 512 );
  23379. this.map = null;
  23380. this.mapPass = null;
  23381. this.matrix = new Matrix4();
  23382. this.autoUpdate = true;
  23383. this.needsUpdate = false;
  23384. this._frustum = new Frustum();
  23385. this._frameExtents = new Vector2( 1, 1 );
  23386. this._viewportCount = 1;
  23387. this._viewports = [
  23388. new Vector4( 0, 0, 1, 1 )
  23389. ];
  23390. }
  23391. getViewportCount() {
  23392. return this._viewportCount;
  23393. }
  23394. getFrustum() {
  23395. return this._frustum;
  23396. }
  23397. updateMatrices( light ) {
  23398. const shadowCamera = this.camera;
  23399. const shadowMatrix = this.matrix;
  23400. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23401. shadowCamera.position.copy( _lightPositionWorld$1 );
  23402. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23403. shadowCamera.lookAt( _lookTarget$1 );
  23404. shadowCamera.updateMatrixWorld();
  23405. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23406. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23407. shadowMatrix.set(
  23408. 0.5, 0.0, 0.0, 0.5,
  23409. 0.0, 0.5, 0.0, 0.5,
  23410. 0.0, 0.0, 0.5, 0.5,
  23411. 0.0, 0.0, 0.0, 1.0
  23412. );
  23413. shadowMatrix.multiply( _projScreenMatrix$1 );
  23414. }
  23415. getViewport( viewportIndex ) {
  23416. return this._viewports[ viewportIndex ];
  23417. }
  23418. getFrameExtents() {
  23419. return this._frameExtents;
  23420. }
  23421. dispose() {
  23422. if ( this.map ) {
  23423. this.map.dispose();
  23424. }
  23425. if ( this.mapPass ) {
  23426. this.mapPass.dispose();
  23427. }
  23428. }
  23429. copy( source ) {
  23430. this.camera = source.camera.clone();
  23431. this.intensity = source.intensity;
  23432. this.bias = source.bias;
  23433. this.radius = source.radius;
  23434. this.mapSize.copy( source.mapSize );
  23435. return this;
  23436. }
  23437. clone() {
  23438. return new this.constructor().copy( this );
  23439. }
  23440. toJSON() {
  23441. const object = {};
  23442. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  23443. if ( this.bias !== 0 ) object.bias = this.bias;
  23444. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23445. if ( this.radius !== 1 ) object.radius = this.radius;
  23446. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23447. object.camera = this.camera.toJSON( false ).object;
  23448. delete object.camera.matrix;
  23449. return object;
  23450. }
  23451. }
  23452. class SpotLightShadow extends LightShadow {
  23453. constructor() {
  23454. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23455. this.isSpotLightShadow = true;
  23456. this.focus = 1;
  23457. }
  23458. updateMatrices( light ) {
  23459. const camera = this.camera;
  23460. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23461. const aspect = this.mapSize.width / this.mapSize.height;
  23462. const far = light.distance || camera.far;
  23463. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23464. camera.fov = fov;
  23465. camera.aspect = aspect;
  23466. camera.far = far;
  23467. camera.updateProjectionMatrix();
  23468. }
  23469. super.updateMatrices( light );
  23470. }
  23471. copy( source ) {
  23472. super.copy( source );
  23473. this.focus = source.focus;
  23474. return this;
  23475. }
  23476. }
  23477. class SpotLight extends Light {
  23478. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  23479. super( color, intensity );
  23480. this.isSpotLight = true;
  23481. this.type = 'SpotLight';
  23482. this.position.copy( Object3D.DEFAULT_UP );
  23483. this.updateMatrix();
  23484. this.target = new Object3D();
  23485. this.distance = distance;
  23486. this.angle = angle;
  23487. this.penumbra = penumbra;
  23488. this.decay = decay;
  23489. this.map = null;
  23490. this.shadow = new SpotLightShadow();
  23491. }
  23492. get power() {
  23493. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23494. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23495. return this.intensity * Math.PI;
  23496. }
  23497. set power( power ) {
  23498. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23499. this.intensity = power / Math.PI;
  23500. }
  23501. dispose() {
  23502. this.shadow.dispose();
  23503. }
  23504. copy( source, recursive ) {
  23505. super.copy( source, recursive );
  23506. this.distance = source.distance;
  23507. this.angle = source.angle;
  23508. this.penumbra = source.penumbra;
  23509. this.decay = source.decay;
  23510. this.target = source.target.clone();
  23511. this.shadow = source.shadow.clone();
  23512. return this;
  23513. }
  23514. }
  23515. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  23516. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  23517. const _lookTarget = /*@__PURE__*/ new Vector3();
  23518. class PointLightShadow extends LightShadow {
  23519. constructor() {
  23520. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23521. this.isPointLightShadow = true;
  23522. this._frameExtents = new Vector2( 4, 2 );
  23523. this._viewportCount = 6;
  23524. this._viewports = [
  23525. // These viewports map a cube-map onto a 2D texture with the
  23526. // following orientation:
  23527. //
  23528. // xzXZ
  23529. // y Y
  23530. //
  23531. // X - Positive x direction
  23532. // x - Negative x direction
  23533. // Y - Positive y direction
  23534. // y - Negative y direction
  23535. // Z - Positive z direction
  23536. // z - Negative z direction
  23537. // positive X
  23538. new Vector4( 2, 1, 1, 1 ),
  23539. // negative X
  23540. new Vector4( 0, 1, 1, 1 ),
  23541. // positive Z
  23542. new Vector4( 3, 1, 1, 1 ),
  23543. // negative Z
  23544. new Vector4( 1, 1, 1, 1 ),
  23545. // positive Y
  23546. new Vector4( 3, 0, 1, 1 ),
  23547. // negative Y
  23548. new Vector4( 1, 0, 1, 1 )
  23549. ];
  23550. this._cubeDirections = [
  23551. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23552. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  23553. ];
  23554. this._cubeUps = [
  23555. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23556. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  23557. ];
  23558. }
  23559. updateMatrices( light, viewportIndex = 0 ) {
  23560. const camera = this.camera;
  23561. const shadowMatrix = this.matrix;
  23562. const far = light.distance || camera.far;
  23563. if ( far !== camera.far ) {
  23564. camera.far = far;
  23565. camera.updateProjectionMatrix();
  23566. }
  23567. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23568. camera.position.copy( _lightPositionWorld );
  23569. _lookTarget.copy( camera.position );
  23570. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23571. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23572. camera.lookAt( _lookTarget );
  23573. camera.updateMatrixWorld();
  23574. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  23575. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23576. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  23577. }
  23578. }
  23579. class PointLight extends Light {
  23580. constructor( color, intensity, distance = 0, decay = 2 ) {
  23581. super( color, intensity );
  23582. this.isPointLight = true;
  23583. this.type = 'PointLight';
  23584. this.distance = distance;
  23585. this.decay = decay;
  23586. this.shadow = new PointLightShadow();
  23587. }
  23588. get power() {
  23589. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23590. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23591. return this.intensity * 4 * Math.PI;
  23592. }
  23593. set power( power ) {
  23594. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23595. this.intensity = power / ( 4 * Math.PI );
  23596. }
  23597. dispose() {
  23598. this.shadow.dispose();
  23599. }
  23600. copy( source, recursive ) {
  23601. super.copy( source, recursive );
  23602. this.distance = source.distance;
  23603. this.decay = source.decay;
  23604. this.shadow = source.shadow.clone();
  23605. return this;
  23606. }
  23607. }
  23608. /**
  23609. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  23610. *
  23611. * In this projection mode, an object's size in the rendered image stays
  23612. * constant regardless of its distance from the camera. This can be useful
  23613. * for rendering 2D scenes and UI elements, amongst other things.
  23614. *
  23615. * @augments Camera
  23616. */
  23617. class OrthographicCamera extends Camera {
  23618. /**
  23619. * Constructs a new orthographic camera.
  23620. *
  23621. * @param {number} [left=-1] - The left plane of the camera's frustum.
  23622. * @param {number} [right=1] - The right plane of the camera's frustum.
  23623. * @param {number} [top=1] - The top plane of the camera's frustum.
  23624. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  23625. * @param {number} [near=0.1] - The camera's near plane.
  23626. * @param {number} [far=2000] - The camera's far plane.
  23627. */
  23628. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  23629. super();
  23630. /**
  23631. * This flag can be used for type testing.
  23632. *
  23633. * @type {boolean}
  23634. * @readonly
  23635. * @default true
  23636. */
  23637. this.isOrthographicCamera = true;
  23638. this.type = 'OrthographicCamera';
  23639. /**
  23640. * The zoom factor of the camera.
  23641. *
  23642. * @type {number}
  23643. * @default 1
  23644. */
  23645. this.zoom = 1;
  23646. /**
  23647. * Represents the frustum window specification. This property should not be edited
  23648. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  23649. *
  23650. * @type {?Object}
  23651. * @default null
  23652. */
  23653. this.view = null;
  23654. /**
  23655. * The left plane of the camera's frustum.
  23656. *
  23657. * @type {number}
  23658. * @default -1
  23659. */
  23660. this.left = left;
  23661. /**
  23662. * The right plane of the camera's frustum.
  23663. *
  23664. * @type {number}
  23665. * @default 1
  23666. */
  23667. this.right = right;
  23668. /**
  23669. * The top plane of the camera's frustum.
  23670. *
  23671. * @type {number}
  23672. * @default 1
  23673. */
  23674. this.top = top;
  23675. /**
  23676. * The bottom plane of the camera's frustum.
  23677. *
  23678. * @type {number}
  23679. * @default -1
  23680. */
  23681. this.bottom = bottom;
  23682. /**
  23683. * The camera's near plane. The valid range is greater than `0`
  23684. * and less than the current value of {@link OrthographicCamera#far}.
  23685. *
  23686. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  23687. * valid value for an orthographic camera's near plane.
  23688. *
  23689. * @type {number}
  23690. * @default 0.1
  23691. */
  23692. this.near = near;
  23693. /**
  23694. * The camera's far plane. Must be greater than the
  23695. * current value of {@link OrthographicCamera#near}.
  23696. *
  23697. * @type {number}
  23698. * @default 2000
  23699. */
  23700. this.far = far;
  23701. this.updateProjectionMatrix();
  23702. }
  23703. copy( source, recursive ) {
  23704. super.copy( source, recursive );
  23705. this.left = source.left;
  23706. this.right = source.right;
  23707. this.top = source.top;
  23708. this.bottom = source.bottom;
  23709. this.near = source.near;
  23710. this.far = source.far;
  23711. this.zoom = source.zoom;
  23712. this.view = source.view === null ? null : Object.assign( {}, source.view );
  23713. return this;
  23714. }
  23715. /**
  23716. * Sets an offset in a larger frustum. This is useful for multi-window or
  23717. * multi-monitor/multi-machine setups.
  23718. *
  23719. * @param {number} fullWidth - The full width of multiview setup.
  23720. * @param {number} fullHeight - The full height of multiview setup.
  23721. * @param {number} x - The horizontal offset of the subcamera.
  23722. * @param {number} y - The vertical offset of the subcamera.
  23723. * @param {number} width - The width of subcamera.
  23724. * @param {number} height - The height of subcamera.
  23725. * @see {@link PerspectiveCamera#setViewOffset}
  23726. */
  23727. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  23728. if ( this.view === null ) {
  23729. this.view = {
  23730. enabled: true,
  23731. fullWidth: 1,
  23732. fullHeight: 1,
  23733. offsetX: 0,
  23734. offsetY: 0,
  23735. width: 1,
  23736. height: 1
  23737. };
  23738. }
  23739. this.view.enabled = true;
  23740. this.view.fullWidth = fullWidth;
  23741. this.view.fullHeight = fullHeight;
  23742. this.view.offsetX = x;
  23743. this.view.offsetY = y;
  23744. this.view.width = width;
  23745. this.view.height = height;
  23746. this.updateProjectionMatrix();
  23747. }
  23748. /**
  23749. * Removes the view offset from the projection matrix.
  23750. */
  23751. clearViewOffset() {
  23752. if ( this.view !== null ) {
  23753. this.view.enabled = false;
  23754. }
  23755. this.updateProjectionMatrix();
  23756. }
  23757. /**
  23758. * Updates the camera's projection matrix. Must be called after any change of
  23759. * camera properties.
  23760. */
  23761. updateProjectionMatrix() {
  23762. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  23763. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  23764. const cx = ( this.right + this.left ) / 2;
  23765. const cy = ( this.top + this.bottom ) / 2;
  23766. let left = cx - dx;
  23767. let right = cx + dx;
  23768. let top = cy + dy;
  23769. let bottom = cy - dy;
  23770. if ( this.view !== null && this.view.enabled ) {
  23771. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  23772. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  23773. left += scaleW * this.view.offsetX;
  23774. right = left + scaleW * this.view.width;
  23775. top -= scaleH * this.view.offsetY;
  23776. bottom = top - scaleH * this.view.height;
  23777. }
  23778. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  23779. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  23780. }
  23781. toJSON( meta ) {
  23782. const data = super.toJSON( meta );
  23783. data.object.zoom = this.zoom;
  23784. data.object.left = this.left;
  23785. data.object.right = this.right;
  23786. data.object.top = this.top;
  23787. data.object.bottom = this.bottom;
  23788. data.object.near = this.near;
  23789. data.object.far = this.far;
  23790. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  23791. return data;
  23792. }
  23793. }
  23794. class DirectionalLightShadow extends LightShadow {
  23795. constructor() {
  23796. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  23797. this.isDirectionalLightShadow = true;
  23798. }
  23799. }
  23800. class DirectionalLight extends Light {
  23801. constructor( color, intensity ) {
  23802. super( color, intensity );
  23803. this.isDirectionalLight = true;
  23804. this.type = 'DirectionalLight';
  23805. this.position.copy( Object3D.DEFAULT_UP );
  23806. this.updateMatrix();
  23807. this.target = new Object3D();
  23808. this.shadow = new DirectionalLightShadow();
  23809. }
  23810. dispose() {
  23811. this.shadow.dispose();
  23812. }
  23813. copy( source ) {
  23814. super.copy( source );
  23815. this.target = source.target.clone();
  23816. this.shadow = source.shadow.clone();
  23817. return this;
  23818. }
  23819. }
  23820. class AmbientLight extends Light {
  23821. constructor( color, intensity ) {
  23822. super( color, intensity );
  23823. this.isAmbientLight = true;
  23824. this.type = 'AmbientLight';
  23825. }
  23826. }
  23827. class RectAreaLight extends Light {
  23828. constructor( color, intensity, width = 10, height = 10 ) {
  23829. super( color, intensity );
  23830. this.isRectAreaLight = true;
  23831. this.type = 'RectAreaLight';
  23832. this.width = width;
  23833. this.height = height;
  23834. }
  23835. get power() {
  23836. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23837. return this.intensity * this.width * this.height * Math.PI;
  23838. }
  23839. set power( power ) {
  23840. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23841. this.intensity = power / ( this.width * this.height * Math.PI );
  23842. }
  23843. copy( source ) {
  23844. super.copy( source );
  23845. this.width = source.width;
  23846. this.height = source.height;
  23847. return this;
  23848. }
  23849. toJSON( meta ) {
  23850. const data = super.toJSON( meta );
  23851. data.object.width = this.width;
  23852. data.object.height = this.height;
  23853. return data;
  23854. }
  23855. }
  23856. /**
  23857. * Represents a third-order spherical harmonics (SH). Light probes use this class
  23858. * to encode lighting information.
  23859. *
  23860. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  23861. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  23862. */
  23863. class SphericalHarmonics3 {
  23864. /**
  23865. * Constructs a new spherical harmonics.
  23866. */
  23867. constructor() {
  23868. /**
  23869. * This flag can be used for type testing.
  23870. *
  23871. * @type {boolean}
  23872. * @readonly
  23873. * @default true
  23874. */
  23875. this.isSphericalHarmonics3 = true;
  23876. /**
  23877. * An array holding the (9) SH coefficients.
  23878. *
  23879. * @type {Array<Vector3>}
  23880. */
  23881. this.coefficients = [];
  23882. for ( let i = 0; i < 9; i ++ ) {
  23883. this.coefficients.push( new Vector3() );
  23884. }
  23885. }
  23886. /**
  23887. * Sets the given SH coefficients to this instance by copying
  23888. * the values.
  23889. *
  23890. * @param {Array<Vector3>} coefficients - The SH coefficients.
  23891. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23892. */
  23893. set( coefficients ) {
  23894. for ( let i = 0; i < 9; i ++ ) {
  23895. this.coefficients[ i ].copy( coefficients[ i ] );
  23896. }
  23897. return this;
  23898. }
  23899. /**
  23900. * Sets all SH coefficients to `0`.
  23901. *
  23902. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23903. */
  23904. zero() {
  23905. for ( let i = 0; i < 9; i ++ ) {
  23906. this.coefficients[ i ].set( 0, 0, 0 );
  23907. }
  23908. return this;
  23909. }
  23910. /**
  23911. * Returns the radiance in the direction of the given normal.
  23912. *
  23913. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  23914. * @param {Vector3} target - The target vector that is used to store the method's result.
  23915. * @return {Vector3} The radiance.
  23916. */
  23917. getAt( normal, target ) {
  23918. // normal is assumed to be unit length
  23919. const x = normal.x, y = normal.y, z = normal.z;
  23920. const coeff = this.coefficients;
  23921. // band 0
  23922. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23923. // band 1
  23924. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23925. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23926. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23927. // band 2
  23928. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23929. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23930. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23931. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23932. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23933. return target;
  23934. }
  23935. /**
  23936. * Returns the irradiance (radiance convolved with cosine lobe) in the
  23937. * direction of the given normal.
  23938. *
  23939. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  23940. * @param {Vector3} target - The target vector that is used to store the method's result.
  23941. * @return {Vector3} The irradiance.
  23942. */
  23943. getIrradianceAt( normal, target ) {
  23944. // normal is assumed to be unit length
  23945. const x = normal.x, y = normal.y, z = normal.z;
  23946. const coeff = this.coefficients;
  23947. // band 0
  23948. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23949. // band 1
  23950. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23951. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23952. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23953. // band 2
  23954. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23955. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23956. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23957. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23958. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23959. return target;
  23960. }
  23961. /**
  23962. * Adds the given SH to this instance.
  23963. *
  23964. * @param {SphericalHarmonics3} sh - The SH to add.
  23965. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23966. */
  23967. add( sh ) {
  23968. for ( let i = 0; i < 9; i ++ ) {
  23969. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23970. }
  23971. return this;
  23972. }
  23973. /**
  23974. * A convenience method for performing {@link SphericalHarmonics3#add} and
  23975. * {@link SphericalHarmonics3#scale} at once.
  23976. *
  23977. * @param {SphericalHarmonics3} sh - The SH to add.
  23978. * @param {number} s - The scale factor.
  23979. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23980. */
  23981. addScaledSH( sh, s ) {
  23982. for ( let i = 0; i < 9; i ++ ) {
  23983. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23984. }
  23985. return this;
  23986. }
  23987. /**
  23988. * Scales this SH by the given scale factor.
  23989. *
  23990. * @param {number} s - The scale factor.
  23991. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23992. */
  23993. scale( s ) {
  23994. for ( let i = 0; i < 9; i ++ ) {
  23995. this.coefficients[ i ].multiplyScalar( s );
  23996. }
  23997. return this;
  23998. }
  23999. /**
  24000. * Linear interpolates between the given SH and this instance by the given
  24001. * alpha factor.
  24002. *
  24003. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  24004. * @param {number} alpha - The alpha factor.
  24005. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  24006. */
  24007. lerp( sh, alpha ) {
  24008. for ( let i = 0; i < 9; i ++ ) {
  24009. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24010. }
  24011. return this;
  24012. }
  24013. /**
  24014. * Returns `true` if this spherical harmonics is equal with the given one.
  24015. *
  24016. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  24017. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  24018. */
  24019. equals( sh ) {
  24020. for ( let i = 0; i < 9; i ++ ) {
  24021. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24022. return false;
  24023. }
  24024. }
  24025. return true;
  24026. }
  24027. /**
  24028. * Copies the values of the given spherical harmonics to this instance.
  24029. *
  24030. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  24031. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  24032. */
  24033. copy( sh ) {
  24034. return this.set( sh.coefficients );
  24035. }
  24036. /**
  24037. * Returns a new spherical harmonics with copied values from this instance.
  24038. *
  24039. * @return {SphericalHarmonics3} A clone of this instance.
  24040. */
  24041. clone() {
  24042. return new this.constructor().copy( this );
  24043. }
  24044. /**
  24045. * Sets the SH coefficients of this instance from the given array.
  24046. *
  24047. * @param {Array<number>} array - An array holding the SH coefficients.
  24048. * @param {number} [offset=0] - The array offset where to start copying.
  24049. * @return {SphericalHarmonics3} A clone of this instance.
  24050. */
  24051. fromArray( array, offset = 0 ) {
  24052. const coefficients = this.coefficients;
  24053. for ( let i = 0; i < 9; i ++ ) {
  24054. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24055. }
  24056. return this;
  24057. }
  24058. /**
  24059. * Returns an array with the SH coefficients, or copies them into the provided
  24060. * array. The coefficients are represented as numbers.
  24061. *
  24062. * @param {Array<number>} [array=[]] - The target array.
  24063. * @param {number} [offset=0] - The array offset where to start copying.
  24064. * @return {Array<number>} An array with flat SH coefficients.
  24065. */
  24066. toArray( array = [], offset = 0 ) {
  24067. const coefficients = this.coefficients;
  24068. for ( let i = 0; i < 9; i ++ ) {
  24069. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24070. }
  24071. return array;
  24072. }
  24073. /**
  24074. * Computes the SH basis for the given normal vector.
  24075. *
  24076. * @param {Vector3} normal - The normal.
  24077. * @param {Array<number>} shBasis - The target array holding the SH basis.
  24078. */
  24079. static getBasisAt( normal, shBasis ) {
  24080. // normal is assumed to be unit length
  24081. const x = normal.x, y = normal.y, z = normal.z;
  24082. // band 0
  24083. shBasis[ 0 ] = 0.282095;
  24084. // band 1
  24085. shBasis[ 1 ] = 0.488603 * y;
  24086. shBasis[ 2 ] = 0.488603 * z;
  24087. shBasis[ 3 ] = 0.488603 * x;
  24088. // band 2
  24089. shBasis[ 4 ] = 1.092548 * x * y;
  24090. shBasis[ 5 ] = 1.092548 * y * z;
  24091. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24092. shBasis[ 7 ] = 1.092548 * x * z;
  24093. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24094. }
  24095. }
  24096. class LightProbe extends Light {
  24097. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24098. super( undefined, intensity );
  24099. this.isLightProbe = true;
  24100. this.sh = sh;
  24101. }
  24102. copy( source ) {
  24103. super.copy( source );
  24104. this.sh.copy( source.sh );
  24105. return this;
  24106. }
  24107. fromJSON( json ) {
  24108. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24109. this.sh.fromArray( json.sh );
  24110. return this;
  24111. }
  24112. toJSON( meta ) {
  24113. const data = super.toJSON( meta );
  24114. data.object.sh = this.sh.toArray();
  24115. return data;
  24116. }
  24117. }
  24118. class MaterialLoader extends Loader {
  24119. constructor( manager ) {
  24120. super( manager );
  24121. this.textures = {};
  24122. }
  24123. load( url, onLoad, onProgress, onError ) {
  24124. const scope = this;
  24125. const loader = new FileLoader( scope.manager );
  24126. loader.setPath( scope.path );
  24127. loader.setRequestHeader( scope.requestHeader );
  24128. loader.setWithCredentials( scope.withCredentials );
  24129. loader.load( url, function ( text ) {
  24130. try {
  24131. onLoad( scope.parse( JSON.parse( text ) ) );
  24132. } catch ( e ) {
  24133. if ( onError ) {
  24134. onError( e );
  24135. } else {
  24136. console.error( e );
  24137. }
  24138. scope.manager.itemError( url );
  24139. }
  24140. }, onProgress, onError );
  24141. }
  24142. parse( json ) {
  24143. const textures = this.textures;
  24144. function getTexture( name ) {
  24145. if ( textures[ name ] === undefined ) {
  24146. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24147. }
  24148. return textures[ name ];
  24149. }
  24150. const material = this.createMaterialFromType( json.type );
  24151. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24152. if ( json.name !== undefined ) material.name = json.name;
  24153. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24154. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24155. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24156. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24157. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24158. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24159. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24160. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24161. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24162. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24163. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24164. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24165. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24166. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  24167. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24168. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24169. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24170. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24171. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24172. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24173. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24174. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  24175. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  24176. if ( json.fog !== undefined ) material.fog = json.fog;
  24177. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24178. if ( json.blending !== undefined ) material.blending = json.blending;
  24179. if ( json.combine !== undefined ) material.combine = json.combine;
  24180. if ( json.side !== undefined ) material.side = json.side;
  24181. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24182. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24183. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24184. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24185. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  24186. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  24187. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24188. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24189. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24190. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  24191. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  24192. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  24193. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  24194. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  24195. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  24196. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  24197. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  24198. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24199. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24200. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24201. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24202. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24203. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24204. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24205. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24206. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24207. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24208. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24209. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24210. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24211. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  24212. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24213. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24214. if ( json.scale !== undefined ) material.scale = json.scale;
  24215. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24216. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24217. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24218. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24219. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24220. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24221. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24222. if ( json.visible !== undefined ) material.visible = json.visible;
  24223. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24224. if ( json.userData !== undefined ) material.userData = json.userData;
  24225. if ( json.vertexColors !== undefined ) {
  24226. if ( typeof json.vertexColors === 'number' ) {
  24227. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24228. } else {
  24229. material.vertexColors = json.vertexColors;
  24230. }
  24231. }
  24232. // Shader Material
  24233. if ( json.uniforms !== undefined ) {
  24234. for ( const name in json.uniforms ) {
  24235. const uniform = json.uniforms[ name ];
  24236. material.uniforms[ name ] = {};
  24237. switch ( uniform.type ) {
  24238. case 't':
  24239. material.uniforms[ name ].value = getTexture( uniform.value );
  24240. break;
  24241. case 'c':
  24242. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24243. break;
  24244. case 'v2':
  24245. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24246. break;
  24247. case 'v3':
  24248. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24249. break;
  24250. case 'v4':
  24251. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24252. break;
  24253. case 'm3':
  24254. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24255. break;
  24256. case 'm4':
  24257. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24258. break;
  24259. default:
  24260. material.uniforms[ name ].value = uniform.value;
  24261. }
  24262. }
  24263. }
  24264. if ( json.defines !== undefined ) material.defines = json.defines;
  24265. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24266. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24267. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24268. if ( json.extensions !== undefined ) {
  24269. for ( const key in json.extensions ) {
  24270. material.extensions[ key ] = json.extensions[ key ];
  24271. }
  24272. }
  24273. if ( json.lights !== undefined ) material.lights = json.lights;
  24274. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  24275. // for PointsMaterial
  24276. if ( json.size !== undefined ) material.size = json.size;
  24277. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24278. // maps
  24279. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24280. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24281. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24282. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24283. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24284. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24285. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24286. if ( json.normalScale !== undefined ) {
  24287. let normalScale = json.normalScale;
  24288. if ( Array.isArray( normalScale ) === false ) {
  24289. // Blender exporter used to export a scalar. See #7459
  24290. normalScale = [ normalScale, normalScale ];
  24291. }
  24292. material.normalScale = new Vector2().fromArray( normalScale );
  24293. }
  24294. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24295. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24296. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24297. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24298. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24299. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24300. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24301. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24302. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24303. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24304. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24305. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  24306. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24307. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24308. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24309. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24310. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24311. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24312. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24313. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24314. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24315. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24316. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24317. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24318. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24319. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24320. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24321. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24322. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  24323. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24324. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24325. return material;
  24326. }
  24327. setTextures( value ) {
  24328. this.textures = value;
  24329. return this;
  24330. }
  24331. createMaterialFromType( type ) {
  24332. return MaterialLoader.createMaterialFromType( type );
  24333. }
  24334. static createMaterialFromType( type ) {
  24335. const materialLib = {
  24336. ShadowMaterial,
  24337. SpriteMaterial,
  24338. RawShaderMaterial,
  24339. ShaderMaterial,
  24340. PointsMaterial,
  24341. MeshPhysicalMaterial,
  24342. MeshStandardMaterial,
  24343. MeshPhongMaterial,
  24344. MeshToonMaterial,
  24345. MeshNormalMaterial,
  24346. MeshLambertMaterial,
  24347. MeshDepthMaterial,
  24348. MeshDistanceMaterial,
  24349. MeshBasicMaterial,
  24350. MeshMatcapMaterial,
  24351. LineDashedMaterial,
  24352. LineBasicMaterial,
  24353. Material
  24354. };
  24355. return new materialLib[ type ]();
  24356. }
  24357. }
  24358. class LoaderUtils {
  24359. static decodeText( array ) { // @deprecated, r165
  24360. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  24361. if ( typeof TextDecoder !== 'undefined' ) {
  24362. return new TextDecoder().decode( array );
  24363. }
  24364. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24365. // throws a "maximum call stack size exceeded" error for large arrays.
  24366. let s = '';
  24367. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24368. // Implicitly assumes little-endian.
  24369. s += String.fromCharCode( array[ i ] );
  24370. }
  24371. try {
  24372. // merges multi-byte utf-8 characters.
  24373. return decodeURIComponent( escape( s ) );
  24374. } catch ( e ) { // see #16358
  24375. return s;
  24376. }
  24377. }
  24378. static extractUrlBase( url ) {
  24379. const index = url.lastIndexOf( '/' );
  24380. if ( index === -1 ) return './';
  24381. return url.slice( 0, index + 1 );
  24382. }
  24383. static resolveURL( url, path ) {
  24384. // Invalid URL
  24385. if ( typeof url !== 'string' || url === '' ) return '';
  24386. // Host Relative URL
  24387. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24388. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24389. }
  24390. // Absolute URL http://,https://,//
  24391. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24392. // Data URI
  24393. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24394. // Blob URL
  24395. if ( /^blob:.*$/i.test( url ) ) return url;
  24396. // Relative URL
  24397. return path + url;
  24398. }
  24399. }
  24400. class InstancedBufferGeometry extends BufferGeometry {
  24401. constructor() {
  24402. super();
  24403. this.isInstancedBufferGeometry = true;
  24404. this.type = 'InstancedBufferGeometry';
  24405. this.instanceCount = Infinity;
  24406. }
  24407. copy( source ) {
  24408. super.copy( source );
  24409. this.instanceCount = source.instanceCount;
  24410. return this;
  24411. }
  24412. toJSON() {
  24413. const data = super.toJSON();
  24414. data.instanceCount = this.instanceCount;
  24415. data.isInstancedBufferGeometry = true;
  24416. return data;
  24417. }
  24418. }
  24419. class BufferGeometryLoader extends Loader {
  24420. constructor( manager ) {
  24421. super( manager );
  24422. }
  24423. load( url, onLoad, onProgress, onError ) {
  24424. const scope = this;
  24425. const loader = new FileLoader( scope.manager );
  24426. loader.setPath( scope.path );
  24427. loader.setRequestHeader( scope.requestHeader );
  24428. loader.setWithCredentials( scope.withCredentials );
  24429. loader.load( url, function ( text ) {
  24430. try {
  24431. onLoad( scope.parse( JSON.parse( text ) ) );
  24432. } catch ( e ) {
  24433. if ( onError ) {
  24434. onError( e );
  24435. } else {
  24436. console.error( e );
  24437. }
  24438. scope.manager.itemError( url );
  24439. }
  24440. }, onProgress, onError );
  24441. }
  24442. parse( json ) {
  24443. const interleavedBufferMap = {};
  24444. const arrayBufferMap = {};
  24445. function getInterleavedBuffer( json, uuid ) {
  24446. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24447. const interleavedBuffers = json.interleavedBuffers;
  24448. const interleavedBuffer = interleavedBuffers[ uuid ];
  24449. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24450. const array = getTypedArray( interleavedBuffer.type, buffer );
  24451. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24452. ib.uuid = interleavedBuffer.uuid;
  24453. interleavedBufferMap[ uuid ] = ib;
  24454. return ib;
  24455. }
  24456. function getArrayBuffer( json, uuid ) {
  24457. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24458. const arrayBuffers = json.arrayBuffers;
  24459. const arrayBuffer = arrayBuffers[ uuid ];
  24460. const ab = new Uint32Array( arrayBuffer ).buffer;
  24461. arrayBufferMap[ uuid ] = ab;
  24462. return ab;
  24463. }
  24464. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24465. const index = json.data.index;
  24466. if ( index !== undefined ) {
  24467. const typedArray = getTypedArray( index.type, index.array );
  24468. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24469. }
  24470. const attributes = json.data.attributes;
  24471. for ( const key in attributes ) {
  24472. const attribute = attributes[ key ];
  24473. let bufferAttribute;
  24474. if ( attribute.isInterleavedBufferAttribute ) {
  24475. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24476. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24477. } else {
  24478. const typedArray = getTypedArray( attribute.type, attribute.array );
  24479. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24480. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24481. }
  24482. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24483. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24484. geometry.setAttribute( key, bufferAttribute );
  24485. }
  24486. const morphAttributes = json.data.morphAttributes;
  24487. if ( morphAttributes ) {
  24488. for ( const key in morphAttributes ) {
  24489. const attributeArray = morphAttributes[ key ];
  24490. const array = [];
  24491. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24492. const attribute = attributeArray[ i ];
  24493. let bufferAttribute;
  24494. if ( attribute.isInterleavedBufferAttribute ) {
  24495. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24496. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24497. } else {
  24498. const typedArray = getTypedArray( attribute.type, attribute.array );
  24499. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24500. }
  24501. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24502. array.push( bufferAttribute );
  24503. }
  24504. geometry.morphAttributes[ key ] = array;
  24505. }
  24506. }
  24507. const morphTargetsRelative = json.data.morphTargetsRelative;
  24508. if ( morphTargetsRelative ) {
  24509. geometry.morphTargetsRelative = true;
  24510. }
  24511. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24512. if ( groups !== undefined ) {
  24513. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24514. const group = groups[ i ];
  24515. geometry.addGroup( group.start, group.count, group.materialIndex );
  24516. }
  24517. }
  24518. const boundingSphere = json.data.boundingSphere;
  24519. if ( boundingSphere !== undefined ) {
  24520. const center = new Vector3();
  24521. if ( boundingSphere.center !== undefined ) {
  24522. center.fromArray( boundingSphere.center );
  24523. }
  24524. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24525. }
  24526. if ( json.name ) geometry.name = json.name;
  24527. if ( json.userData ) geometry.userData = json.userData;
  24528. return geometry;
  24529. }
  24530. }
  24531. class ObjectLoader extends Loader {
  24532. constructor( manager ) {
  24533. super( manager );
  24534. }
  24535. load( url, onLoad, onProgress, onError ) {
  24536. const scope = this;
  24537. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24538. this.resourcePath = this.resourcePath || path;
  24539. const loader = new FileLoader( this.manager );
  24540. loader.setPath( this.path );
  24541. loader.setRequestHeader( this.requestHeader );
  24542. loader.setWithCredentials( this.withCredentials );
  24543. loader.load( url, function ( text ) {
  24544. let json = null;
  24545. try {
  24546. json = JSON.parse( text );
  24547. } catch ( error ) {
  24548. if ( onError !== undefined ) onError( error );
  24549. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24550. return;
  24551. }
  24552. const metadata = json.metadata;
  24553. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24554. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  24555. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24556. return;
  24557. }
  24558. scope.parse( json, onLoad );
  24559. }, onProgress, onError );
  24560. }
  24561. async loadAsync( url, onProgress ) {
  24562. const scope = this;
  24563. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24564. this.resourcePath = this.resourcePath || path;
  24565. const loader = new FileLoader( this.manager );
  24566. loader.setPath( this.path );
  24567. loader.setRequestHeader( this.requestHeader );
  24568. loader.setWithCredentials( this.withCredentials );
  24569. const text = await loader.loadAsync( url, onProgress );
  24570. const json = JSON.parse( text );
  24571. const metadata = json.metadata;
  24572. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24573. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24574. }
  24575. return await scope.parseAsync( json );
  24576. }
  24577. parse( json, onLoad ) {
  24578. const animations = this.parseAnimations( json.animations );
  24579. const shapes = this.parseShapes( json.shapes );
  24580. const geometries = this.parseGeometries( json.geometries, shapes );
  24581. const images = this.parseImages( json.images, function () {
  24582. if ( onLoad !== undefined ) onLoad( object );
  24583. } );
  24584. const textures = this.parseTextures( json.textures, images );
  24585. const materials = this.parseMaterials( json.materials, textures );
  24586. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24587. const skeletons = this.parseSkeletons( json.skeletons, object );
  24588. this.bindSkeletons( object, skeletons );
  24589. this.bindLightTargets( object );
  24590. //
  24591. if ( onLoad !== undefined ) {
  24592. let hasImages = false;
  24593. for ( const uuid in images ) {
  24594. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  24595. hasImages = true;
  24596. break;
  24597. }
  24598. }
  24599. if ( hasImages === false ) onLoad( object );
  24600. }
  24601. return object;
  24602. }
  24603. async parseAsync( json ) {
  24604. const animations = this.parseAnimations( json.animations );
  24605. const shapes = this.parseShapes( json.shapes );
  24606. const geometries = this.parseGeometries( json.geometries, shapes );
  24607. const images = await this.parseImagesAsync( json.images );
  24608. const textures = this.parseTextures( json.textures, images );
  24609. const materials = this.parseMaterials( json.materials, textures );
  24610. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24611. const skeletons = this.parseSkeletons( json.skeletons, object );
  24612. this.bindSkeletons( object, skeletons );
  24613. this.bindLightTargets( object );
  24614. return object;
  24615. }
  24616. parseShapes( json ) {
  24617. const shapes = {};
  24618. if ( json !== undefined ) {
  24619. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24620. const shape = new Shape().fromJSON( json[ i ] );
  24621. shapes[ shape.uuid ] = shape;
  24622. }
  24623. }
  24624. return shapes;
  24625. }
  24626. parseSkeletons( json, object ) {
  24627. const skeletons = {};
  24628. const bones = {};
  24629. // generate bone lookup table
  24630. object.traverse( function ( child ) {
  24631. if ( child.isBone ) bones[ child.uuid ] = child;
  24632. } );
  24633. // create skeletons
  24634. if ( json !== undefined ) {
  24635. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24636. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24637. skeletons[ skeleton.uuid ] = skeleton;
  24638. }
  24639. }
  24640. return skeletons;
  24641. }
  24642. parseGeometries( json, shapes ) {
  24643. const geometries = {};
  24644. if ( json !== undefined ) {
  24645. const bufferGeometryLoader = new BufferGeometryLoader();
  24646. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24647. let geometry;
  24648. const data = json[ i ];
  24649. switch ( data.type ) {
  24650. case 'BufferGeometry':
  24651. case 'InstancedBufferGeometry':
  24652. geometry = bufferGeometryLoader.parse( data );
  24653. break;
  24654. default:
  24655. if ( data.type in Geometries ) {
  24656. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24657. } else {
  24658. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24659. }
  24660. }
  24661. geometry.uuid = data.uuid;
  24662. if ( data.name !== undefined ) geometry.name = data.name;
  24663. if ( data.userData !== undefined ) geometry.userData = data.userData;
  24664. geometries[ data.uuid ] = geometry;
  24665. }
  24666. }
  24667. return geometries;
  24668. }
  24669. parseMaterials( json, textures ) {
  24670. const cache = {}; // MultiMaterial
  24671. const materials = {};
  24672. if ( json !== undefined ) {
  24673. const loader = new MaterialLoader();
  24674. loader.setTextures( textures );
  24675. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24676. const data = json[ i ];
  24677. if ( cache[ data.uuid ] === undefined ) {
  24678. cache[ data.uuid ] = loader.parse( data );
  24679. }
  24680. materials[ data.uuid ] = cache[ data.uuid ];
  24681. }
  24682. }
  24683. return materials;
  24684. }
  24685. parseAnimations( json ) {
  24686. const animations = {};
  24687. if ( json !== undefined ) {
  24688. for ( let i = 0; i < json.length; i ++ ) {
  24689. const data = json[ i ];
  24690. const clip = AnimationClip.parse( data );
  24691. animations[ clip.uuid ] = clip;
  24692. }
  24693. }
  24694. return animations;
  24695. }
  24696. parseImages( json, onLoad ) {
  24697. const scope = this;
  24698. const images = {};
  24699. let loader;
  24700. function loadImage( url ) {
  24701. scope.manager.itemStart( url );
  24702. return loader.load( url, function () {
  24703. scope.manager.itemEnd( url );
  24704. }, undefined, function () {
  24705. scope.manager.itemError( url );
  24706. scope.manager.itemEnd( url );
  24707. } );
  24708. }
  24709. function deserializeImage( image ) {
  24710. if ( typeof image === 'string' ) {
  24711. const url = image;
  24712. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24713. return loadImage( path );
  24714. } else {
  24715. if ( image.data ) {
  24716. return {
  24717. data: getTypedArray( image.type, image.data ),
  24718. width: image.width,
  24719. height: image.height
  24720. };
  24721. } else {
  24722. return null;
  24723. }
  24724. }
  24725. }
  24726. if ( json !== undefined && json.length > 0 ) {
  24727. const manager = new LoadingManager( onLoad );
  24728. loader = new ImageLoader( manager );
  24729. loader.setCrossOrigin( this.crossOrigin );
  24730. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24731. const image = json[ i ];
  24732. const url = image.url;
  24733. if ( Array.isArray( url ) ) {
  24734. // load array of images e.g CubeTexture
  24735. const imageArray = [];
  24736. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24737. const currentUrl = url[ j ];
  24738. const deserializedImage = deserializeImage( currentUrl );
  24739. if ( deserializedImage !== null ) {
  24740. if ( deserializedImage instanceof HTMLImageElement ) {
  24741. imageArray.push( deserializedImage );
  24742. } else {
  24743. // special case: handle array of data textures for cube textures
  24744. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24745. }
  24746. }
  24747. }
  24748. images[ image.uuid ] = new Source( imageArray );
  24749. } else {
  24750. // load single image
  24751. const deserializedImage = deserializeImage( image.url );
  24752. images[ image.uuid ] = new Source( deserializedImage );
  24753. }
  24754. }
  24755. }
  24756. return images;
  24757. }
  24758. async parseImagesAsync( json ) {
  24759. const scope = this;
  24760. const images = {};
  24761. let loader;
  24762. async function deserializeImage( image ) {
  24763. if ( typeof image === 'string' ) {
  24764. const url = image;
  24765. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24766. return await loader.loadAsync( path );
  24767. } else {
  24768. if ( image.data ) {
  24769. return {
  24770. data: getTypedArray( image.type, image.data ),
  24771. width: image.width,
  24772. height: image.height
  24773. };
  24774. } else {
  24775. return null;
  24776. }
  24777. }
  24778. }
  24779. if ( json !== undefined && json.length > 0 ) {
  24780. loader = new ImageLoader( this.manager );
  24781. loader.setCrossOrigin( this.crossOrigin );
  24782. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24783. const image = json[ i ];
  24784. const url = image.url;
  24785. if ( Array.isArray( url ) ) {
  24786. // load array of images e.g CubeTexture
  24787. const imageArray = [];
  24788. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24789. const currentUrl = url[ j ];
  24790. const deserializedImage = await deserializeImage( currentUrl );
  24791. if ( deserializedImage !== null ) {
  24792. if ( deserializedImage instanceof HTMLImageElement ) {
  24793. imageArray.push( deserializedImage );
  24794. } else {
  24795. // special case: handle array of data textures for cube textures
  24796. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24797. }
  24798. }
  24799. }
  24800. images[ image.uuid ] = new Source( imageArray );
  24801. } else {
  24802. // load single image
  24803. const deserializedImage = await deserializeImage( image.url );
  24804. images[ image.uuid ] = new Source( deserializedImage );
  24805. }
  24806. }
  24807. }
  24808. return images;
  24809. }
  24810. parseTextures( json, images ) {
  24811. function parseConstant( value, type ) {
  24812. if ( typeof value === 'number' ) return value;
  24813. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24814. return type[ value ];
  24815. }
  24816. const textures = {};
  24817. if ( json !== undefined ) {
  24818. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24819. const data = json[ i ];
  24820. if ( data.image === undefined ) {
  24821. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24822. }
  24823. if ( images[ data.image ] === undefined ) {
  24824. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24825. }
  24826. const source = images[ data.image ];
  24827. const image = source.data;
  24828. let texture;
  24829. if ( Array.isArray( image ) ) {
  24830. texture = new CubeTexture();
  24831. if ( image.length === 6 ) texture.needsUpdate = true;
  24832. } else {
  24833. if ( image && image.data ) {
  24834. texture = new DataTexture();
  24835. } else {
  24836. texture = new Texture();
  24837. }
  24838. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24839. }
  24840. texture.source = source;
  24841. texture.uuid = data.uuid;
  24842. if ( data.name !== undefined ) texture.name = data.name;
  24843. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24844. if ( data.channel !== undefined ) texture.channel = data.channel;
  24845. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24846. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24847. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24848. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24849. if ( data.wrap !== undefined ) {
  24850. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24851. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24852. }
  24853. if ( data.format !== undefined ) texture.format = data.format;
  24854. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  24855. if ( data.type !== undefined ) texture.type = data.type;
  24856. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  24857. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24858. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24859. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24860. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24861. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  24862. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24863. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24864. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  24865. if ( data.userData !== undefined ) texture.userData = data.userData;
  24866. textures[ data.uuid ] = texture;
  24867. }
  24868. }
  24869. return textures;
  24870. }
  24871. parseObject( data, geometries, materials, textures, animations ) {
  24872. let object;
  24873. function getGeometry( name ) {
  24874. if ( geometries[ name ] === undefined ) {
  24875. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24876. }
  24877. return geometries[ name ];
  24878. }
  24879. function getMaterial( name ) {
  24880. if ( name === undefined ) return undefined;
  24881. if ( Array.isArray( name ) ) {
  24882. const array = [];
  24883. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24884. const uuid = name[ i ];
  24885. if ( materials[ uuid ] === undefined ) {
  24886. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24887. }
  24888. array.push( materials[ uuid ] );
  24889. }
  24890. return array;
  24891. }
  24892. if ( materials[ name ] === undefined ) {
  24893. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24894. }
  24895. return materials[ name ];
  24896. }
  24897. function getTexture( uuid ) {
  24898. if ( textures[ uuid ] === undefined ) {
  24899. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  24900. }
  24901. return textures[ uuid ];
  24902. }
  24903. let geometry, material;
  24904. switch ( data.type ) {
  24905. case 'Scene':
  24906. object = new Scene();
  24907. if ( data.background !== undefined ) {
  24908. if ( Number.isInteger( data.background ) ) {
  24909. object.background = new Color( data.background );
  24910. } else {
  24911. object.background = getTexture( data.background );
  24912. }
  24913. }
  24914. if ( data.environment !== undefined ) {
  24915. object.environment = getTexture( data.environment );
  24916. }
  24917. if ( data.fog !== undefined ) {
  24918. if ( data.fog.type === 'Fog' ) {
  24919. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24920. } else if ( data.fog.type === 'FogExp2' ) {
  24921. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24922. }
  24923. if ( data.fog.name !== '' ) {
  24924. object.fog.name = data.fog.name;
  24925. }
  24926. }
  24927. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  24928. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  24929. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  24930. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  24931. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  24932. break;
  24933. case 'PerspectiveCamera':
  24934. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24935. if ( data.focus !== undefined ) object.focus = data.focus;
  24936. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24937. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24938. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24939. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24940. break;
  24941. case 'OrthographicCamera':
  24942. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24943. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24944. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24945. break;
  24946. case 'AmbientLight':
  24947. object = new AmbientLight( data.color, data.intensity );
  24948. break;
  24949. case 'DirectionalLight':
  24950. object = new DirectionalLight( data.color, data.intensity );
  24951. object.target = data.target || '';
  24952. break;
  24953. case 'PointLight':
  24954. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24955. break;
  24956. case 'RectAreaLight':
  24957. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24958. break;
  24959. case 'SpotLight':
  24960. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24961. object.target = data.target || '';
  24962. break;
  24963. case 'HemisphereLight':
  24964. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24965. break;
  24966. case 'LightProbe':
  24967. object = new LightProbe().fromJSON( data );
  24968. break;
  24969. case 'SkinnedMesh':
  24970. geometry = getGeometry( data.geometry );
  24971. material = getMaterial( data.material );
  24972. object = new SkinnedMesh( geometry, material );
  24973. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24974. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24975. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24976. break;
  24977. case 'Mesh':
  24978. geometry = getGeometry( data.geometry );
  24979. material = getMaterial( data.material );
  24980. object = new Mesh( geometry, material );
  24981. break;
  24982. case 'InstancedMesh':
  24983. geometry = getGeometry( data.geometry );
  24984. material = getMaterial( data.material );
  24985. const count = data.count;
  24986. const instanceMatrix = data.instanceMatrix;
  24987. const instanceColor = data.instanceColor;
  24988. object = new InstancedMesh( geometry, material, count );
  24989. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24990. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  24991. break;
  24992. case 'BatchedMesh':
  24993. geometry = getGeometry( data.geometry );
  24994. material = getMaterial( data.material );
  24995. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  24996. object.geometry = geometry;
  24997. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  24998. object.sortObjects = data.sortObjects;
  24999. object._drawRanges = data.drawRanges;
  25000. object._reservedRanges = data.reservedRanges;
  25001. object._visibility = data.visibility;
  25002. object._active = data.active;
  25003. object._bounds = data.bounds.map( bound => {
  25004. const box = new Box3();
  25005. box.min.fromArray( bound.boxMin );
  25006. box.max.fromArray( bound.boxMax );
  25007. const sphere = new Sphere();
  25008. sphere.radius = bound.sphereRadius;
  25009. sphere.center.fromArray( bound.sphereCenter );
  25010. return {
  25011. boxInitialized: bound.boxInitialized,
  25012. box: box,
  25013. sphereInitialized: bound.sphereInitialized,
  25014. sphere: sphere
  25015. };
  25016. } );
  25017. object._maxInstanceCount = data.maxInstanceCount;
  25018. object._maxVertexCount = data.maxVertexCount;
  25019. object._maxIndexCount = data.maxIndexCount;
  25020. object._geometryInitialized = data.geometryInitialized;
  25021. object._geometryCount = data.geometryCount;
  25022. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  25023. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  25024. break;
  25025. case 'LOD':
  25026. object = new LOD();
  25027. break;
  25028. case 'Line':
  25029. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25030. break;
  25031. case 'LineLoop':
  25032. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25033. break;
  25034. case 'LineSegments':
  25035. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25036. break;
  25037. case 'PointCloud':
  25038. case 'Points':
  25039. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25040. break;
  25041. case 'Sprite':
  25042. object = new Sprite( getMaterial( data.material ) );
  25043. break;
  25044. case 'Group':
  25045. object = new Group();
  25046. break;
  25047. case 'Bone':
  25048. object = new Bone();
  25049. break;
  25050. default:
  25051. object = new Object3D();
  25052. }
  25053. object.uuid = data.uuid;
  25054. if ( data.name !== undefined ) object.name = data.name;
  25055. if ( data.matrix !== undefined ) {
  25056. object.matrix.fromArray( data.matrix );
  25057. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25058. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25059. } else {
  25060. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25061. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25062. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25063. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25064. }
  25065. if ( data.up !== undefined ) object.up.fromArray( data.up );
  25066. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25067. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25068. if ( data.shadow ) {
  25069. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  25070. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25071. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25072. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25073. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25074. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25075. }
  25076. if ( data.visible !== undefined ) object.visible = data.visible;
  25077. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25078. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25079. if ( data.userData !== undefined ) object.userData = data.userData;
  25080. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25081. if ( data.children !== undefined ) {
  25082. const children = data.children;
  25083. for ( let i = 0; i < children.length; i ++ ) {
  25084. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25085. }
  25086. }
  25087. if ( data.animations !== undefined ) {
  25088. const objectAnimations = data.animations;
  25089. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25090. const uuid = objectAnimations[ i ];
  25091. object.animations.push( animations[ uuid ] );
  25092. }
  25093. }
  25094. if ( data.type === 'LOD' ) {
  25095. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25096. const levels = data.levels;
  25097. for ( let l = 0; l < levels.length; l ++ ) {
  25098. const level = levels[ l ];
  25099. const child = object.getObjectByProperty( 'uuid', level.object );
  25100. if ( child !== undefined ) {
  25101. object.addLevel( child, level.distance, level.hysteresis );
  25102. }
  25103. }
  25104. }
  25105. return object;
  25106. }
  25107. bindSkeletons( object, skeletons ) {
  25108. if ( Object.keys( skeletons ).length === 0 ) return;
  25109. object.traverse( function ( child ) {
  25110. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25111. const skeleton = skeletons[ child.skeleton ];
  25112. if ( skeleton === undefined ) {
  25113. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25114. } else {
  25115. child.bind( skeleton, child.bindMatrix );
  25116. }
  25117. }
  25118. } );
  25119. }
  25120. bindLightTargets( object ) {
  25121. object.traverse( function ( child ) {
  25122. if ( child.isDirectionalLight || child.isSpotLight ) {
  25123. const uuid = child.target;
  25124. const target = object.getObjectByProperty( 'uuid', uuid );
  25125. if ( target !== undefined ) {
  25126. child.target = target;
  25127. } else {
  25128. child.target = new Object3D();
  25129. }
  25130. }
  25131. } );
  25132. }
  25133. }
  25134. const TEXTURE_MAPPING = {
  25135. UVMapping: UVMapping,
  25136. CubeReflectionMapping: CubeReflectionMapping,
  25137. CubeRefractionMapping: CubeRefractionMapping,
  25138. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25139. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25140. CubeUVReflectionMapping: CubeUVReflectionMapping
  25141. };
  25142. const TEXTURE_WRAPPING = {
  25143. RepeatWrapping: RepeatWrapping,
  25144. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25145. MirroredRepeatWrapping: MirroredRepeatWrapping
  25146. };
  25147. const TEXTURE_FILTER = {
  25148. NearestFilter: NearestFilter,
  25149. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25150. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25151. LinearFilter: LinearFilter,
  25152. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25153. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25154. };
  25155. class ImageBitmapLoader extends Loader {
  25156. constructor( manager ) {
  25157. super( manager );
  25158. this.isImageBitmapLoader = true;
  25159. if ( typeof createImageBitmap === 'undefined' ) {
  25160. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25161. }
  25162. if ( typeof fetch === 'undefined' ) {
  25163. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25164. }
  25165. this.options = { premultiplyAlpha: 'none' };
  25166. }
  25167. setOptions( options ) {
  25168. this.options = options;
  25169. return this;
  25170. }
  25171. load( url, onLoad, onProgress, onError ) {
  25172. if ( url === undefined ) url = '';
  25173. if ( this.path !== undefined ) url = this.path + url;
  25174. url = this.manager.resolveURL( url );
  25175. const scope = this;
  25176. const cached = Cache.get( url );
  25177. if ( cached !== undefined ) {
  25178. scope.manager.itemStart( url );
  25179. // If cached is a promise, wait for it to resolve
  25180. if ( cached.then ) {
  25181. cached.then( imageBitmap => {
  25182. if ( onLoad ) onLoad( imageBitmap );
  25183. scope.manager.itemEnd( url );
  25184. } ).catch( e => {
  25185. if ( onError ) onError( e );
  25186. } );
  25187. return;
  25188. }
  25189. // If cached is not a promise (i.e., it's already an imageBitmap)
  25190. setTimeout( function () {
  25191. if ( onLoad ) onLoad( cached );
  25192. scope.manager.itemEnd( url );
  25193. }, 0 );
  25194. return cached;
  25195. }
  25196. const fetchOptions = {};
  25197. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25198. fetchOptions.headers = this.requestHeader;
  25199. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  25200. return res.blob();
  25201. } ).then( function ( blob ) {
  25202. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25203. } ).then( function ( imageBitmap ) {
  25204. Cache.add( url, imageBitmap );
  25205. if ( onLoad ) onLoad( imageBitmap );
  25206. scope.manager.itemEnd( url );
  25207. return imageBitmap;
  25208. } ).catch( function ( e ) {
  25209. if ( onError ) onError( e );
  25210. Cache.remove( url );
  25211. scope.manager.itemError( url );
  25212. scope.manager.itemEnd( url );
  25213. } );
  25214. Cache.add( url, promise );
  25215. scope.manager.itemStart( url );
  25216. }
  25217. }
  25218. let _context;
  25219. class AudioContext {
  25220. static getContext() {
  25221. if ( _context === undefined ) {
  25222. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25223. }
  25224. return _context;
  25225. }
  25226. static setContext( value ) {
  25227. _context = value;
  25228. }
  25229. }
  25230. class AudioLoader extends Loader {
  25231. constructor( manager ) {
  25232. super( manager );
  25233. }
  25234. load( url, onLoad, onProgress, onError ) {
  25235. const scope = this;
  25236. const loader = new FileLoader( this.manager );
  25237. loader.setResponseType( 'arraybuffer' );
  25238. loader.setPath( this.path );
  25239. loader.setRequestHeader( this.requestHeader );
  25240. loader.setWithCredentials( this.withCredentials );
  25241. loader.load( url, function ( buffer ) {
  25242. try {
  25243. // Create a copy of the buffer. The `decodeAudioData` method
  25244. // detaches the buffer when complete, preventing reuse.
  25245. const bufferCopy = buffer.slice( 0 );
  25246. const context = AudioContext.getContext();
  25247. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25248. onLoad( audioBuffer );
  25249. } ).catch( handleError );
  25250. } catch ( e ) {
  25251. handleError( e );
  25252. }
  25253. }, onProgress, onError );
  25254. function handleError( e ) {
  25255. if ( onError ) {
  25256. onError( e );
  25257. } else {
  25258. console.error( e );
  25259. }
  25260. scope.manager.itemError( url );
  25261. }
  25262. }
  25263. }
  25264. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25265. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25266. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25267. /**
  25268. * A special type of camera that uses two perspective cameras with
  25269. * stereoscopic projection. Can be used for rendering stereo effects
  25270. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  25271. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  25272. */
  25273. class StereoCamera {
  25274. /**
  25275. * Constructs a new stereo camera.
  25276. */
  25277. constructor() {
  25278. /**
  25279. * The type property is used for detecting the object type
  25280. * in context of serialization/deserialization.
  25281. *
  25282. * @type {string}
  25283. * @readonly
  25284. */
  25285. this.type = 'StereoCamera';
  25286. /**
  25287. * The aspect.
  25288. *
  25289. * @type {number}
  25290. * @default 1
  25291. */
  25292. this.aspect = 1;
  25293. /**
  25294. * The eye separation which represents the distance
  25295. * between the left and right camera.
  25296. *
  25297. * @type {number}
  25298. * @default 0.064
  25299. */
  25300. this.eyeSep = 0.064;
  25301. /**
  25302. * The camera representing the left eye. This is added to layer `1` so objects to be
  25303. * rendered by the left camera must also be added to this layer.
  25304. *
  25305. * @type {PerspectiveCamera}
  25306. */
  25307. this.cameraL = new PerspectiveCamera();
  25308. this.cameraL.layers.enable( 1 );
  25309. this.cameraL.matrixAutoUpdate = false;
  25310. /**
  25311. * The camera representing the right eye. This is added to layer `2` so objects to be
  25312. * rendered by the right camera must also be added to this layer.
  25313. *
  25314. * @type {PerspectiveCamera}
  25315. */
  25316. this.cameraR = new PerspectiveCamera();
  25317. this.cameraR.layers.enable( 2 );
  25318. this.cameraR.matrixAutoUpdate = false;
  25319. this._cache = {
  25320. focus: null,
  25321. fov: null,
  25322. aspect: null,
  25323. near: null,
  25324. far: null,
  25325. zoom: null,
  25326. eyeSep: null
  25327. };
  25328. }
  25329. /**
  25330. * Updates the stereo camera based on the given perspective camera.
  25331. *
  25332. * @param {PerspectiveCamera} camera - The perspective camera.
  25333. */
  25334. update( camera ) {
  25335. const cache = this._cache;
  25336. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25337. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25338. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25339. if ( needsUpdate ) {
  25340. cache.focus = camera.focus;
  25341. cache.fov = camera.fov;
  25342. cache.aspect = camera.aspect * this.aspect;
  25343. cache.near = camera.near;
  25344. cache.far = camera.far;
  25345. cache.zoom = camera.zoom;
  25346. cache.eyeSep = this.eyeSep;
  25347. // Off-axis stereoscopic effect based on
  25348. // http://paulbourke.net/stereographics/stereorender/
  25349. _projectionMatrix.copy( camera.projectionMatrix );
  25350. const eyeSepHalf = cache.eyeSep / 2;
  25351. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25352. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25353. let xmin, xmax;
  25354. // translate xOffset
  25355. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25356. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25357. // for left eye
  25358. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25359. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25360. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25361. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25362. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25363. // for right eye
  25364. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25365. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25366. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25367. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25368. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25369. }
  25370. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25371. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25372. }
  25373. }
  25374. /**
  25375. * This type of camera can be used in order to efficiently render a scene with a
  25376. * predefined set of cameras. This is an important performance aspect for
  25377. * rendering VR scenes.
  25378. *
  25379. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  25380. * to define for each sub camera the `viewport` property which determines the
  25381. * part of the viewport that is rendered with this camera.
  25382. *
  25383. * @augments PerspectiveCamera
  25384. */
  25385. class ArrayCamera extends PerspectiveCamera {
  25386. /**
  25387. * Constructs a new array camera.
  25388. *
  25389. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  25390. */
  25391. constructor( array = [] ) {
  25392. super();
  25393. /**
  25394. * This flag can be used for type testing.
  25395. *
  25396. * @type {boolean}
  25397. * @readonly
  25398. * @default true
  25399. */
  25400. this.isArrayCamera = true;
  25401. /**
  25402. * An array of perspective sub cameras.
  25403. *
  25404. * @type {Array<PerspectiveCamera>}
  25405. */
  25406. this.cameras = array;
  25407. this.index = 0;
  25408. }
  25409. }
  25410. class Clock {
  25411. constructor( autoStart = true ) {
  25412. this.autoStart = autoStart;
  25413. this.startTime = 0;
  25414. this.oldTime = 0;
  25415. this.elapsedTime = 0;
  25416. this.running = false;
  25417. }
  25418. start() {
  25419. this.startTime = now();
  25420. this.oldTime = this.startTime;
  25421. this.elapsedTime = 0;
  25422. this.running = true;
  25423. }
  25424. stop() {
  25425. this.getElapsedTime();
  25426. this.running = false;
  25427. this.autoStart = false;
  25428. }
  25429. getElapsedTime() {
  25430. this.getDelta();
  25431. return this.elapsedTime;
  25432. }
  25433. getDelta() {
  25434. let diff = 0;
  25435. if ( this.autoStart && ! this.running ) {
  25436. this.start();
  25437. return 0;
  25438. }
  25439. if ( this.running ) {
  25440. const newTime = now();
  25441. diff = ( newTime - this.oldTime ) / 1000;
  25442. this.oldTime = newTime;
  25443. this.elapsedTime += diff;
  25444. }
  25445. return diff;
  25446. }
  25447. }
  25448. function now() {
  25449. return performance.now();
  25450. }
  25451. const _position$1 = /*@__PURE__*/ new Vector3();
  25452. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25453. const _scale$1 = /*@__PURE__*/ new Vector3();
  25454. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25455. class AudioListener extends Object3D {
  25456. constructor() {
  25457. super();
  25458. this.type = 'AudioListener';
  25459. this.context = AudioContext.getContext();
  25460. this.gain = this.context.createGain();
  25461. this.gain.connect( this.context.destination );
  25462. this.filter = null;
  25463. this.timeDelta = 0;
  25464. // private
  25465. this._clock = new Clock();
  25466. }
  25467. getInput() {
  25468. return this.gain;
  25469. }
  25470. removeFilter() {
  25471. if ( this.filter !== null ) {
  25472. this.gain.disconnect( this.filter );
  25473. this.filter.disconnect( this.context.destination );
  25474. this.gain.connect( this.context.destination );
  25475. this.filter = null;
  25476. }
  25477. return this;
  25478. }
  25479. getFilter() {
  25480. return this.filter;
  25481. }
  25482. setFilter( value ) {
  25483. if ( this.filter !== null ) {
  25484. this.gain.disconnect( this.filter );
  25485. this.filter.disconnect( this.context.destination );
  25486. } else {
  25487. this.gain.disconnect( this.context.destination );
  25488. }
  25489. this.filter = value;
  25490. this.gain.connect( this.filter );
  25491. this.filter.connect( this.context.destination );
  25492. return this;
  25493. }
  25494. getMasterVolume() {
  25495. return this.gain.gain.value;
  25496. }
  25497. setMasterVolume( value ) {
  25498. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25499. return this;
  25500. }
  25501. updateMatrixWorld( force ) {
  25502. super.updateMatrixWorld( force );
  25503. const listener = this.context.listener;
  25504. const up = this.up;
  25505. this.timeDelta = this._clock.getDelta();
  25506. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25507. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  25508. if ( listener.positionX ) {
  25509. // code path for Chrome (see #14393)
  25510. const endTime = this.context.currentTime + this.timeDelta;
  25511. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25512. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25513. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25514. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25515. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25516. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25517. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25518. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25519. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25520. } else {
  25521. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25522. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25523. }
  25524. }
  25525. }
  25526. class Audio extends Object3D {
  25527. constructor( listener ) {
  25528. super();
  25529. this.type = 'Audio';
  25530. this.listener = listener;
  25531. this.context = listener.context;
  25532. this.gain = this.context.createGain();
  25533. this.gain.connect( listener.getInput() );
  25534. this.autoplay = false;
  25535. this.buffer = null;
  25536. this.detune = 0;
  25537. this.loop = false;
  25538. this.loopStart = 0;
  25539. this.loopEnd = 0;
  25540. this.offset = 0;
  25541. this.duration = undefined;
  25542. this.playbackRate = 1;
  25543. this.isPlaying = false;
  25544. this.hasPlaybackControl = true;
  25545. this.source = null;
  25546. this.sourceType = 'empty';
  25547. this._startedAt = 0;
  25548. this._progress = 0;
  25549. this._connected = false;
  25550. this.filters = [];
  25551. }
  25552. getOutput() {
  25553. return this.gain;
  25554. }
  25555. setNodeSource( audioNode ) {
  25556. this.hasPlaybackControl = false;
  25557. this.sourceType = 'audioNode';
  25558. this.source = audioNode;
  25559. this.connect();
  25560. return this;
  25561. }
  25562. setMediaElementSource( mediaElement ) {
  25563. this.hasPlaybackControl = false;
  25564. this.sourceType = 'mediaNode';
  25565. this.source = this.context.createMediaElementSource( mediaElement );
  25566. this.connect();
  25567. return this;
  25568. }
  25569. setMediaStreamSource( mediaStream ) {
  25570. this.hasPlaybackControl = false;
  25571. this.sourceType = 'mediaStreamNode';
  25572. this.source = this.context.createMediaStreamSource( mediaStream );
  25573. this.connect();
  25574. return this;
  25575. }
  25576. setBuffer( audioBuffer ) {
  25577. this.buffer = audioBuffer;
  25578. this.sourceType = 'buffer';
  25579. if ( this.autoplay ) this.play();
  25580. return this;
  25581. }
  25582. play( delay = 0 ) {
  25583. if ( this.isPlaying === true ) {
  25584. console.warn( 'THREE.Audio: Audio is already playing.' );
  25585. return;
  25586. }
  25587. if ( this.hasPlaybackControl === false ) {
  25588. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25589. return;
  25590. }
  25591. this._startedAt = this.context.currentTime + delay;
  25592. const source = this.context.createBufferSource();
  25593. source.buffer = this.buffer;
  25594. source.loop = this.loop;
  25595. source.loopStart = this.loopStart;
  25596. source.loopEnd = this.loopEnd;
  25597. source.onended = this.onEnded.bind( this );
  25598. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25599. this.isPlaying = true;
  25600. this.source = source;
  25601. this.setDetune( this.detune );
  25602. this.setPlaybackRate( this.playbackRate );
  25603. return this.connect();
  25604. }
  25605. pause() {
  25606. if ( this.hasPlaybackControl === false ) {
  25607. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25608. return;
  25609. }
  25610. if ( this.isPlaying === true ) {
  25611. // update current progress
  25612. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25613. if ( this.loop === true ) {
  25614. // ensure _progress does not exceed duration with looped audios
  25615. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25616. }
  25617. this.source.stop();
  25618. this.source.onended = null;
  25619. this.isPlaying = false;
  25620. }
  25621. return this;
  25622. }
  25623. stop( delay = 0 ) {
  25624. if ( this.hasPlaybackControl === false ) {
  25625. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25626. return;
  25627. }
  25628. this._progress = 0;
  25629. if ( this.source !== null ) {
  25630. this.source.stop( this.context.currentTime + delay );
  25631. this.source.onended = null;
  25632. }
  25633. this.isPlaying = false;
  25634. return this;
  25635. }
  25636. connect() {
  25637. if ( this.filters.length > 0 ) {
  25638. this.source.connect( this.filters[ 0 ] );
  25639. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25640. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25641. }
  25642. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25643. } else {
  25644. this.source.connect( this.getOutput() );
  25645. }
  25646. this._connected = true;
  25647. return this;
  25648. }
  25649. disconnect() {
  25650. if ( this._connected === false ) {
  25651. return;
  25652. }
  25653. if ( this.filters.length > 0 ) {
  25654. this.source.disconnect( this.filters[ 0 ] );
  25655. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25656. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25657. }
  25658. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25659. } else {
  25660. this.source.disconnect( this.getOutput() );
  25661. }
  25662. this._connected = false;
  25663. return this;
  25664. }
  25665. getFilters() {
  25666. return this.filters;
  25667. }
  25668. setFilters( value ) {
  25669. if ( ! value ) value = [];
  25670. if ( this._connected === true ) {
  25671. this.disconnect();
  25672. this.filters = value.slice();
  25673. this.connect();
  25674. } else {
  25675. this.filters = value.slice();
  25676. }
  25677. return this;
  25678. }
  25679. setDetune( value ) {
  25680. this.detune = value;
  25681. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  25682. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25683. }
  25684. return this;
  25685. }
  25686. getDetune() {
  25687. return this.detune;
  25688. }
  25689. getFilter() {
  25690. return this.getFilters()[ 0 ];
  25691. }
  25692. setFilter( filter ) {
  25693. return this.setFilters( filter ? [ filter ] : [] );
  25694. }
  25695. setPlaybackRate( value ) {
  25696. if ( this.hasPlaybackControl === false ) {
  25697. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25698. return;
  25699. }
  25700. this.playbackRate = value;
  25701. if ( this.isPlaying === true ) {
  25702. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25703. }
  25704. return this;
  25705. }
  25706. getPlaybackRate() {
  25707. return this.playbackRate;
  25708. }
  25709. onEnded() {
  25710. this.isPlaying = false;
  25711. this._progress = 0;
  25712. }
  25713. getLoop() {
  25714. if ( this.hasPlaybackControl === false ) {
  25715. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25716. return false;
  25717. }
  25718. return this.loop;
  25719. }
  25720. setLoop( value ) {
  25721. if ( this.hasPlaybackControl === false ) {
  25722. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25723. return;
  25724. }
  25725. this.loop = value;
  25726. if ( this.isPlaying === true ) {
  25727. this.source.loop = this.loop;
  25728. }
  25729. return this;
  25730. }
  25731. setLoopStart( value ) {
  25732. this.loopStart = value;
  25733. return this;
  25734. }
  25735. setLoopEnd( value ) {
  25736. this.loopEnd = value;
  25737. return this;
  25738. }
  25739. getVolume() {
  25740. return this.gain.gain.value;
  25741. }
  25742. setVolume( value ) {
  25743. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25744. return this;
  25745. }
  25746. copy( source, recursive ) {
  25747. super.copy( source, recursive );
  25748. if ( source.sourceType !== 'buffer' ) {
  25749. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  25750. return this;
  25751. }
  25752. this.autoplay = source.autoplay;
  25753. this.buffer = source.buffer;
  25754. this.detune = source.detune;
  25755. this.loop = source.loop;
  25756. this.loopStart = source.loopStart;
  25757. this.loopEnd = source.loopEnd;
  25758. this.offset = source.offset;
  25759. this.duration = source.duration;
  25760. this.playbackRate = source.playbackRate;
  25761. this.hasPlaybackControl = source.hasPlaybackControl;
  25762. this.sourceType = source.sourceType;
  25763. this.filters = source.filters.slice();
  25764. return this;
  25765. }
  25766. clone( recursive ) {
  25767. return new this.constructor( this.listener ).copy( this, recursive );
  25768. }
  25769. }
  25770. const _position = /*@__PURE__*/ new Vector3();
  25771. const _quaternion = /*@__PURE__*/ new Quaternion();
  25772. const _scale = /*@__PURE__*/ new Vector3();
  25773. const _orientation = /*@__PURE__*/ new Vector3();
  25774. class PositionalAudio extends Audio {
  25775. constructor( listener ) {
  25776. super( listener );
  25777. this.panner = this.context.createPanner();
  25778. this.panner.panningModel = 'HRTF';
  25779. this.panner.connect( this.gain );
  25780. }
  25781. connect() {
  25782. super.connect();
  25783. this.panner.connect( this.gain );
  25784. }
  25785. disconnect() {
  25786. super.disconnect();
  25787. this.panner.disconnect( this.gain );
  25788. }
  25789. getOutput() {
  25790. return this.panner;
  25791. }
  25792. getRefDistance() {
  25793. return this.panner.refDistance;
  25794. }
  25795. setRefDistance( value ) {
  25796. this.panner.refDistance = value;
  25797. return this;
  25798. }
  25799. getRolloffFactor() {
  25800. return this.panner.rolloffFactor;
  25801. }
  25802. setRolloffFactor( value ) {
  25803. this.panner.rolloffFactor = value;
  25804. return this;
  25805. }
  25806. getDistanceModel() {
  25807. return this.panner.distanceModel;
  25808. }
  25809. setDistanceModel( value ) {
  25810. this.panner.distanceModel = value;
  25811. return this;
  25812. }
  25813. getMaxDistance() {
  25814. return this.panner.maxDistance;
  25815. }
  25816. setMaxDistance( value ) {
  25817. this.panner.maxDistance = value;
  25818. return this;
  25819. }
  25820. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25821. this.panner.coneInnerAngle = coneInnerAngle;
  25822. this.panner.coneOuterAngle = coneOuterAngle;
  25823. this.panner.coneOuterGain = coneOuterGain;
  25824. return this;
  25825. }
  25826. updateMatrixWorld( force ) {
  25827. super.updateMatrixWorld( force );
  25828. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25829. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25830. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25831. const panner = this.panner;
  25832. if ( panner.positionX ) {
  25833. // code path for Chrome and Firefox (see #14393)
  25834. const endTime = this.context.currentTime + this.listener.timeDelta;
  25835. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25836. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25837. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25838. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25839. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25840. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25841. } else {
  25842. panner.setPosition( _position.x, _position.y, _position.z );
  25843. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25844. }
  25845. }
  25846. }
  25847. class AudioAnalyser {
  25848. constructor( audio, fftSize = 2048 ) {
  25849. this.analyser = audio.context.createAnalyser();
  25850. this.analyser.fftSize = fftSize;
  25851. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25852. audio.getOutput().connect( this.analyser );
  25853. }
  25854. getFrequencyData() {
  25855. this.analyser.getByteFrequencyData( this.data );
  25856. return this.data;
  25857. }
  25858. getAverageFrequency() {
  25859. let value = 0;
  25860. const data = this.getFrequencyData();
  25861. for ( let i = 0; i < data.length; i ++ ) {
  25862. value += data[ i ];
  25863. }
  25864. return value / data.length;
  25865. }
  25866. }
  25867. class PropertyMixer {
  25868. constructor( binding, typeName, valueSize ) {
  25869. this.binding = binding;
  25870. this.valueSize = valueSize;
  25871. let mixFunction,
  25872. mixFunctionAdditive,
  25873. setIdentity;
  25874. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25875. //
  25876. // interpolators can use .buffer as their .result
  25877. // the data then goes to 'incoming'
  25878. //
  25879. // 'accu0' and 'accu1' are used frame-interleaved for
  25880. // the cumulative result and are compared to detect
  25881. // changes
  25882. //
  25883. // 'orig' stores the original state of the property
  25884. //
  25885. // 'add' is used for additive cumulative results
  25886. //
  25887. // 'work' is optional and is only present for quaternion types. It is used
  25888. // to store intermediate quaternion multiplication results
  25889. switch ( typeName ) {
  25890. case 'quaternion':
  25891. mixFunction = this._slerp;
  25892. mixFunctionAdditive = this._slerpAdditive;
  25893. setIdentity = this._setAdditiveIdentityQuaternion;
  25894. this.buffer = new Float64Array( valueSize * 6 );
  25895. this._workIndex = 5;
  25896. break;
  25897. case 'string':
  25898. case 'bool':
  25899. mixFunction = this._select;
  25900. // Use the regular mix function and for additive on these types,
  25901. // additive is not relevant for non-numeric types
  25902. mixFunctionAdditive = this._select;
  25903. setIdentity = this._setAdditiveIdentityOther;
  25904. this.buffer = new Array( valueSize * 5 );
  25905. break;
  25906. default:
  25907. mixFunction = this._lerp;
  25908. mixFunctionAdditive = this._lerpAdditive;
  25909. setIdentity = this._setAdditiveIdentityNumeric;
  25910. this.buffer = new Float64Array( valueSize * 5 );
  25911. }
  25912. this._mixBufferRegion = mixFunction;
  25913. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25914. this._setIdentity = setIdentity;
  25915. this._origIndex = 3;
  25916. this._addIndex = 4;
  25917. this.cumulativeWeight = 0;
  25918. this.cumulativeWeightAdditive = 0;
  25919. this.useCount = 0;
  25920. this.referenceCount = 0;
  25921. }
  25922. // accumulate data in the 'incoming' region into 'accu<i>'
  25923. accumulate( accuIndex, weight ) {
  25924. // note: happily accumulating nothing when weight = 0, the caller knows
  25925. // the weight and shouldn't have made the call in the first place
  25926. const buffer = this.buffer,
  25927. stride = this.valueSize,
  25928. offset = accuIndex * stride + stride;
  25929. let currentWeight = this.cumulativeWeight;
  25930. if ( currentWeight === 0 ) {
  25931. // accuN := incoming * weight
  25932. for ( let i = 0; i !== stride; ++ i ) {
  25933. buffer[ offset + i ] = buffer[ i ];
  25934. }
  25935. currentWeight = weight;
  25936. } else {
  25937. // accuN := accuN + incoming * weight
  25938. currentWeight += weight;
  25939. const mix = weight / currentWeight;
  25940. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25941. }
  25942. this.cumulativeWeight = currentWeight;
  25943. }
  25944. // accumulate data in the 'incoming' region into 'add'
  25945. accumulateAdditive( weight ) {
  25946. const buffer = this.buffer,
  25947. stride = this.valueSize,
  25948. offset = stride * this._addIndex;
  25949. if ( this.cumulativeWeightAdditive === 0 ) {
  25950. // add = identity
  25951. this._setIdentity();
  25952. }
  25953. // add := add + incoming * weight
  25954. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25955. this.cumulativeWeightAdditive += weight;
  25956. }
  25957. // apply the state of 'accu<i>' to the binding when accus differ
  25958. apply( accuIndex ) {
  25959. const stride = this.valueSize,
  25960. buffer = this.buffer,
  25961. offset = accuIndex * stride + stride,
  25962. weight = this.cumulativeWeight,
  25963. weightAdditive = this.cumulativeWeightAdditive,
  25964. binding = this.binding;
  25965. this.cumulativeWeight = 0;
  25966. this.cumulativeWeightAdditive = 0;
  25967. if ( weight < 1 ) {
  25968. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25969. const originalValueOffset = stride * this._origIndex;
  25970. this._mixBufferRegion(
  25971. buffer, offset, originalValueOffset, 1 - weight, stride );
  25972. }
  25973. if ( weightAdditive > 0 ) {
  25974. // accuN := accuN + additive accuN
  25975. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25976. }
  25977. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25978. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25979. // value has changed -> update scene graph
  25980. binding.setValue( buffer, offset );
  25981. break;
  25982. }
  25983. }
  25984. }
  25985. // remember the state of the bound property and copy it to both accus
  25986. saveOriginalState() {
  25987. const binding = this.binding;
  25988. const buffer = this.buffer,
  25989. stride = this.valueSize,
  25990. originalValueOffset = stride * this._origIndex;
  25991. binding.getValue( buffer, originalValueOffset );
  25992. // accu[0..1] := orig -- initially detect changes against the original
  25993. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25994. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25995. }
  25996. // Add to identity for additive
  25997. this._setIdentity();
  25998. this.cumulativeWeight = 0;
  25999. this.cumulativeWeightAdditive = 0;
  26000. }
  26001. // apply the state previously taken via 'saveOriginalState' to the binding
  26002. restoreOriginalState() {
  26003. const originalValueOffset = this.valueSize * 3;
  26004. this.binding.setValue( this.buffer, originalValueOffset );
  26005. }
  26006. _setAdditiveIdentityNumeric() {
  26007. const startIndex = this._addIndex * this.valueSize;
  26008. const endIndex = startIndex + this.valueSize;
  26009. for ( let i = startIndex; i < endIndex; i ++ ) {
  26010. this.buffer[ i ] = 0;
  26011. }
  26012. }
  26013. _setAdditiveIdentityQuaternion() {
  26014. this._setAdditiveIdentityNumeric();
  26015. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26016. }
  26017. _setAdditiveIdentityOther() {
  26018. const startIndex = this._origIndex * this.valueSize;
  26019. const targetIndex = this._addIndex * this.valueSize;
  26020. for ( let i = 0; i < this.valueSize; i ++ ) {
  26021. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26022. }
  26023. }
  26024. // mix functions
  26025. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26026. if ( t >= 0.5 ) {
  26027. for ( let i = 0; i !== stride; ++ i ) {
  26028. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26029. }
  26030. }
  26031. }
  26032. _slerp( buffer, dstOffset, srcOffset, t ) {
  26033. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26034. }
  26035. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26036. const workOffset = this._workIndex * stride;
  26037. // Store result in intermediate buffer offset
  26038. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26039. // Slerp to the intermediate result
  26040. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26041. }
  26042. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26043. const s = 1 - t;
  26044. for ( let i = 0; i !== stride; ++ i ) {
  26045. const j = dstOffset + i;
  26046. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26047. }
  26048. }
  26049. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26050. for ( let i = 0; i !== stride; ++ i ) {
  26051. const j = dstOffset + i;
  26052. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26053. }
  26054. }
  26055. }
  26056. // Characters [].:/ are reserved for track binding syntax.
  26057. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26058. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26059. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26060. // only latin characters, and the unicode \p{L} is not yet supported. So
  26061. // instead, we exclude reserved characters and match everything else.
  26062. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26063. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26064. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26065. // be matched to parse the rest of the track name.
  26066. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26067. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26068. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26069. // Object on target node, and accessor. May not contain reserved
  26070. // characters. Accessor may contain any character except closing bracket.
  26071. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26072. // Property and accessor. May not contain reserved characters. Accessor may
  26073. // contain any non-bracket characters.
  26074. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26075. const _trackRe = new RegExp( ''
  26076. + '^'
  26077. + _directoryRe
  26078. + _nodeRe
  26079. + _objectRe
  26080. + _propertyRe
  26081. + '$'
  26082. );
  26083. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26084. class Composite {
  26085. constructor( targetGroup, path, optionalParsedPath ) {
  26086. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26087. this._targetGroup = targetGroup;
  26088. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26089. }
  26090. getValue( array, offset ) {
  26091. this.bind(); // bind all binding
  26092. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26093. binding = this._bindings[ firstValidIndex ];
  26094. // and only call .getValue on the first
  26095. if ( binding !== undefined ) binding.getValue( array, offset );
  26096. }
  26097. setValue( array, offset ) {
  26098. const bindings = this._bindings;
  26099. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26100. bindings[ i ].setValue( array, offset );
  26101. }
  26102. }
  26103. bind() {
  26104. const bindings = this._bindings;
  26105. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26106. bindings[ i ].bind();
  26107. }
  26108. }
  26109. unbind() {
  26110. const bindings = this._bindings;
  26111. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26112. bindings[ i ].unbind();
  26113. }
  26114. }
  26115. }
  26116. // Note: This class uses a State pattern on a per-method basis:
  26117. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26118. // prototype version of these methods with one that represents
  26119. // the bound state. When the property is not found, the methods
  26120. // become no-ops.
  26121. class PropertyBinding {
  26122. constructor( rootNode, path, parsedPath ) {
  26123. this.path = path;
  26124. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26125. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  26126. this.rootNode = rootNode;
  26127. // initial state of these methods that calls 'bind'
  26128. this.getValue = this._getValue_unbound;
  26129. this.setValue = this._setValue_unbound;
  26130. }
  26131. static create( root, path, parsedPath ) {
  26132. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26133. return new PropertyBinding( root, path, parsedPath );
  26134. } else {
  26135. return new PropertyBinding.Composite( root, path, parsedPath );
  26136. }
  26137. }
  26138. /**
  26139. * Replaces spaces with underscores and removes unsupported characters from
  26140. * node names, to ensure compatibility with parseTrackName().
  26141. *
  26142. * @param {string} name Node name to be sanitized.
  26143. * @return {string}
  26144. */
  26145. static sanitizeNodeName( name ) {
  26146. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26147. }
  26148. static parseTrackName( trackName ) {
  26149. const matches = _trackRe.exec( trackName );
  26150. if ( matches === null ) {
  26151. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26152. }
  26153. const results = {
  26154. // directoryName: matches[ 1 ], // (tschw) currently unused
  26155. nodeName: matches[ 2 ],
  26156. objectName: matches[ 3 ],
  26157. objectIndex: matches[ 4 ],
  26158. propertyName: matches[ 5 ], // required
  26159. propertyIndex: matches[ 6 ]
  26160. };
  26161. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26162. if ( lastDot !== undefined && lastDot !== -1 ) {
  26163. const objectName = results.nodeName.substring( lastDot + 1 );
  26164. // Object names must be checked against an allowlist. Otherwise, there
  26165. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26166. // 'bar' could be the objectName, or part of a nodeName (which can
  26167. // include '.' characters).
  26168. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  26169. results.nodeName = results.nodeName.substring( 0, lastDot );
  26170. results.objectName = objectName;
  26171. }
  26172. }
  26173. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26174. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26175. }
  26176. return results;
  26177. }
  26178. static findNode( root, nodeName ) {
  26179. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  26180. return root;
  26181. }
  26182. // search into skeleton bones.
  26183. if ( root.skeleton ) {
  26184. const bone = root.skeleton.getBoneByName( nodeName );
  26185. if ( bone !== undefined ) {
  26186. return bone;
  26187. }
  26188. }
  26189. // search into node subtree.
  26190. if ( root.children ) {
  26191. const searchNodeSubtree = function ( children ) {
  26192. for ( let i = 0; i < children.length; i ++ ) {
  26193. const childNode = children[ i ];
  26194. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26195. return childNode;
  26196. }
  26197. const result = searchNodeSubtree( childNode.children );
  26198. if ( result ) return result;
  26199. }
  26200. return null;
  26201. };
  26202. const subTreeNode = searchNodeSubtree( root.children );
  26203. if ( subTreeNode ) {
  26204. return subTreeNode;
  26205. }
  26206. }
  26207. return null;
  26208. }
  26209. // these are used to "bind" a nonexistent property
  26210. _getValue_unavailable() {}
  26211. _setValue_unavailable() {}
  26212. // Getters
  26213. _getValue_direct( buffer, offset ) {
  26214. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26215. }
  26216. _getValue_array( buffer, offset ) {
  26217. const source = this.resolvedProperty;
  26218. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26219. buffer[ offset ++ ] = source[ i ];
  26220. }
  26221. }
  26222. _getValue_arrayElement( buffer, offset ) {
  26223. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26224. }
  26225. _getValue_toArray( buffer, offset ) {
  26226. this.resolvedProperty.toArray( buffer, offset );
  26227. }
  26228. // Direct
  26229. _setValue_direct( buffer, offset ) {
  26230. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26231. }
  26232. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26233. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26234. this.targetObject.needsUpdate = true;
  26235. }
  26236. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26237. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26238. this.targetObject.matrixWorldNeedsUpdate = true;
  26239. }
  26240. // EntireArray
  26241. _setValue_array( buffer, offset ) {
  26242. const dest = this.resolvedProperty;
  26243. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26244. dest[ i ] = buffer[ offset ++ ];
  26245. }
  26246. }
  26247. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26248. const dest = this.resolvedProperty;
  26249. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26250. dest[ i ] = buffer[ offset ++ ];
  26251. }
  26252. this.targetObject.needsUpdate = true;
  26253. }
  26254. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26255. const dest = this.resolvedProperty;
  26256. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26257. dest[ i ] = buffer[ offset ++ ];
  26258. }
  26259. this.targetObject.matrixWorldNeedsUpdate = true;
  26260. }
  26261. // ArrayElement
  26262. _setValue_arrayElement( buffer, offset ) {
  26263. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26264. }
  26265. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26266. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26267. this.targetObject.needsUpdate = true;
  26268. }
  26269. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26270. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26271. this.targetObject.matrixWorldNeedsUpdate = true;
  26272. }
  26273. // HasToFromArray
  26274. _setValue_fromArray( buffer, offset ) {
  26275. this.resolvedProperty.fromArray( buffer, offset );
  26276. }
  26277. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26278. this.resolvedProperty.fromArray( buffer, offset );
  26279. this.targetObject.needsUpdate = true;
  26280. }
  26281. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26282. this.resolvedProperty.fromArray( buffer, offset );
  26283. this.targetObject.matrixWorldNeedsUpdate = true;
  26284. }
  26285. _getValue_unbound( targetArray, offset ) {
  26286. this.bind();
  26287. this.getValue( targetArray, offset );
  26288. }
  26289. _setValue_unbound( sourceArray, offset ) {
  26290. this.bind();
  26291. this.setValue( sourceArray, offset );
  26292. }
  26293. // create getter / setter pair for a property in the scene graph
  26294. bind() {
  26295. let targetObject = this.node;
  26296. const parsedPath = this.parsedPath;
  26297. const objectName = parsedPath.objectName;
  26298. const propertyName = parsedPath.propertyName;
  26299. let propertyIndex = parsedPath.propertyIndex;
  26300. if ( ! targetObject ) {
  26301. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  26302. this.node = targetObject;
  26303. }
  26304. // set fail state so we can just 'return' on error
  26305. this.getValue = this._getValue_unavailable;
  26306. this.setValue = this._setValue_unavailable;
  26307. // ensure there is a value node
  26308. if ( ! targetObject ) {
  26309. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  26310. return;
  26311. }
  26312. if ( objectName ) {
  26313. let objectIndex = parsedPath.objectIndex;
  26314. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26315. switch ( objectName ) {
  26316. case 'materials':
  26317. if ( ! targetObject.material ) {
  26318. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26319. return;
  26320. }
  26321. if ( ! targetObject.material.materials ) {
  26322. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26323. return;
  26324. }
  26325. targetObject = targetObject.material.materials;
  26326. break;
  26327. case 'bones':
  26328. if ( ! targetObject.skeleton ) {
  26329. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26330. return;
  26331. }
  26332. // potential future optimization: skip this if propertyIndex is already an integer
  26333. // and convert the integer string to a true integer.
  26334. targetObject = targetObject.skeleton.bones;
  26335. // support resolving morphTarget names into indices.
  26336. for ( let i = 0; i < targetObject.length; i ++ ) {
  26337. if ( targetObject[ i ].name === objectIndex ) {
  26338. objectIndex = i;
  26339. break;
  26340. }
  26341. }
  26342. break;
  26343. case 'map':
  26344. if ( 'map' in targetObject ) {
  26345. targetObject = targetObject.map;
  26346. break;
  26347. }
  26348. if ( ! targetObject.material ) {
  26349. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26350. return;
  26351. }
  26352. if ( ! targetObject.material.map ) {
  26353. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26354. return;
  26355. }
  26356. targetObject = targetObject.material.map;
  26357. break;
  26358. default:
  26359. if ( targetObject[ objectName ] === undefined ) {
  26360. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26361. return;
  26362. }
  26363. targetObject = targetObject[ objectName ];
  26364. }
  26365. if ( objectIndex !== undefined ) {
  26366. if ( targetObject[ objectIndex ] === undefined ) {
  26367. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26368. return;
  26369. }
  26370. targetObject = targetObject[ objectIndex ];
  26371. }
  26372. }
  26373. // resolve property
  26374. const nodeProperty = targetObject[ propertyName ];
  26375. if ( nodeProperty === undefined ) {
  26376. const nodeName = parsedPath.nodeName;
  26377. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26378. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26379. return;
  26380. }
  26381. // determine versioning scheme
  26382. let versioning = this.Versioning.None;
  26383. this.targetObject = targetObject;
  26384. if ( targetObject.isMaterial === true ) {
  26385. versioning = this.Versioning.NeedsUpdate;
  26386. } else if ( targetObject.isObject3D === true ) {
  26387. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26388. }
  26389. // determine how the property gets bound
  26390. let bindingType = this.BindingType.Direct;
  26391. if ( propertyIndex !== undefined ) {
  26392. // access a sub element of the property array (only primitives are supported right now)
  26393. if ( propertyName === 'morphTargetInfluences' ) {
  26394. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26395. // support resolving morphTarget names into indices.
  26396. if ( ! targetObject.geometry ) {
  26397. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26398. return;
  26399. }
  26400. if ( ! targetObject.geometry.morphAttributes ) {
  26401. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26402. return;
  26403. }
  26404. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26405. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26406. }
  26407. }
  26408. bindingType = this.BindingType.ArrayElement;
  26409. this.resolvedProperty = nodeProperty;
  26410. this.propertyIndex = propertyIndex;
  26411. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26412. // must use copy for Object3D.Euler/Quaternion
  26413. bindingType = this.BindingType.HasFromToArray;
  26414. this.resolvedProperty = nodeProperty;
  26415. } else if ( Array.isArray( nodeProperty ) ) {
  26416. bindingType = this.BindingType.EntireArray;
  26417. this.resolvedProperty = nodeProperty;
  26418. } else {
  26419. this.propertyName = propertyName;
  26420. }
  26421. // select getter / setter
  26422. this.getValue = this.GetterByBindingType[ bindingType ];
  26423. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26424. }
  26425. unbind() {
  26426. this.node = null;
  26427. // back to the prototype version of getValue / setValue
  26428. // note: avoiding to mutate the shape of 'this' via 'delete'
  26429. this.getValue = this._getValue_unbound;
  26430. this.setValue = this._setValue_unbound;
  26431. }
  26432. }
  26433. PropertyBinding.Composite = Composite;
  26434. PropertyBinding.prototype.BindingType = {
  26435. Direct: 0,
  26436. EntireArray: 1,
  26437. ArrayElement: 2,
  26438. HasFromToArray: 3
  26439. };
  26440. PropertyBinding.prototype.Versioning = {
  26441. None: 0,
  26442. NeedsUpdate: 1,
  26443. MatrixWorldNeedsUpdate: 2
  26444. };
  26445. PropertyBinding.prototype.GetterByBindingType = [
  26446. PropertyBinding.prototype._getValue_direct,
  26447. PropertyBinding.prototype._getValue_array,
  26448. PropertyBinding.prototype._getValue_arrayElement,
  26449. PropertyBinding.prototype._getValue_toArray,
  26450. ];
  26451. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26452. [
  26453. // Direct
  26454. PropertyBinding.prototype._setValue_direct,
  26455. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26456. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26457. ], [
  26458. // EntireArray
  26459. PropertyBinding.prototype._setValue_array,
  26460. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26461. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26462. ], [
  26463. // ArrayElement
  26464. PropertyBinding.prototype._setValue_arrayElement,
  26465. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26466. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26467. ], [
  26468. // HasToFromArray
  26469. PropertyBinding.prototype._setValue_fromArray,
  26470. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26471. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26472. ]
  26473. ];
  26474. /**
  26475. *
  26476. * A group of objects that receives a shared animation state.
  26477. *
  26478. * Usage:
  26479. *
  26480. * - Add objects you would otherwise pass as 'root' to the
  26481. * constructor or the .clipAction method of AnimationMixer.
  26482. *
  26483. * - Instead pass this object as 'root'.
  26484. *
  26485. * - You can also add and remove objects later when the mixer
  26486. * is running.
  26487. *
  26488. * Note:
  26489. *
  26490. * Objects of this class appear as one object to the mixer,
  26491. * so cache control of the individual objects must be done
  26492. * on the group.
  26493. *
  26494. * Limitation:
  26495. *
  26496. * - The animated properties must be compatible among the
  26497. * all objects in the group.
  26498. *
  26499. * - A single property can either be controlled through a
  26500. * target group or directly, but not both.
  26501. */
  26502. class AnimationObjectGroup {
  26503. constructor() {
  26504. this.isAnimationObjectGroup = true;
  26505. this.uuid = generateUUID();
  26506. // cached objects followed by the active ones
  26507. this._objects = Array.prototype.slice.call( arguments );
  26508. this.nCachedObjects_ = 0; // threshold
  26509. // note: read by PropertyBinding.Composite
  26510. const indices = {};
  26511. this._indicesByUUID = indices; // for bookkeeping
  26512. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26513. indices[ arguments[ i ].uuid ] = i;
  26514. }
  26515. this._paths = []; // inside: string
  26516. this._parsedPaths = []; // inside: { we don't care, here }
  26517. this._bindings = []; // inside: Array< PropertyBinding >
  26518. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26519. const scope = this;
  26520. this.stats = {
  26521. objects: {
  26522. get total() {
  26523. return scope._objects.length;
  26524. },
  26525. get inUse() {
  26526. return this.total - scope.nCachedObjects_;
  26527. }
  26528. },
  26529. get bindingsPerObject() {
  26530. return scope._bindings.length;
  26531. }
  26532. };
  26533. }
  26534. add() {
  26535. const objects = this._objects,
  26536. indicesByUUID = this._indicesByUUID,
  26537. paths = this._paths,
  26538. parsedPaths = this._parsedPaths,
  26539. bindings = this._bindings,
  26540. nBindings = bindings.length;
  26541. let knownObject = undefined,
  26542. nObjects = objects.length,
  26543. nCachedObjects = this.nCachedObjects_;
  26544. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26545. const object = arguments[ i ],
  26546. uuid = object.uuid;
  26547. let index = indicesByUUID[ uuid ];
  26548. if ( index === undefined ) {
  26549. // unknown object -> add it to the ACTIVE region
  26550. index = nObjects ++;
  26551. indicesByUUID[ uuid ] = index;
  26552. objects.push( object );
  26553. // accounting is done, now do the same for all bindings
  26554. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26555. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26556. }
  26557. } else if ( index < nCachedObjects ) {
  26558. knownObject = objects[ index ];
  26559. // move existing object to the ACTIVE region
  26560. const firstActiveIndex = -- nCachedObjects,
  26561. lastCachedObject = objects[ firstActiveIndex ];
  26562. indicesByUUID[ lastCachedObject.uuid ] = index;
  26563. objects[ index ] = lastCachedObject;
  26564. indicesByUUID[ uuid ] = firstActiveIndex;
  26565. objects[ firstActiveIndex ] = object;
  26566. // accounting is done, now do the same for all bindings
  26567. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26568. const bindingsForPath = bindings[ j ],
  26569. lastCached = bindingsForPath[ firstActiveIndex ];
  26570. let binding = bindingsForPath[ index ];
  26571. bindingsForPath[ index ] = lastCached;
  26572. if ( binding === undefined ) {
  26573. // since we do not bother to create new bindings
  26574. // for objects that are cached, the binding may
  26575. // or may not exist
  26576. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26577. }
  26578. bindingsForPath[ firstActiveIndex ] = binding;
  26579. }
  26580. } else if ( objects[ index ] !== knownObject ) {
  26581. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26582. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26583. } // else the object is already where we want it to be
  26584. } // for arguments
  26585. this.nCachedObjects_ = nCachedObjects;
  26586. }
  26587. remove() {
  26588. const objects = this._objects,
  26589. indicesByUUID = this._indicesByUUID,
  26590. bindings = this._bindings,
  26591. nBindings = bindings.length;
  26592. let nCachedObjects = this.nCachedObjects_;
  26593. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26594. const object = arguments[ i ],
  26595. uuid = object.uuid,
  26596. index = indicesByUUID[ uuid ];
  26597. if ( index !== undefined && index >= nCachedObjects ) {
  26598. // move existing object into the CACHED region
  26599. const lastCachedIndex = nCachedObjects ++,
  26600. firstActiveObject = objects[ lastCachedIndex ];
  26601. indicesByUUID[ firstActiveObject.uuid ] = index;
  26602. objects[ index ] = firstActiveObject;
  26603. indicesByUUID[ uuid ] = lastCachedIndex;
  26604. objects[ lastCachedIndex ] = object;
  26605. // accounting is done, now do the same for all bindings
  26606. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26607. const bindingsForPath = bindings[ j ],
  26608. firstActive = bindingsForPath[ lastCachedIndex ],
  26609. binding = bindingsForPath[ index ];
  26610. bindingsForPath[ index ] = firstActive;
  26611. bindingsForPath[ lastCachedIndex ] = binding;
  26612. }
  26613. }
  26614. } // for arguments
  26615. this.nCachedObjects_ = nCachedObjects;
  26616. }
  26617. // remove & forget
  26618. uncache() {
  26619. const objects = this._objects,
  26620. indicesByUUID = this._indicesByUUID,
  26621. bindings = this._bindings,
  26622. nBindings = bindings.length;
  26623. let nCachedObjects = this.nCachedObjects_,
  26624. nObjects = objects.length;
  26625. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26626. const object = arguments[ i ],
  26627. uuid = object.uuid,
  26628. index = indicesByUUID[ uuid ];
  26629. if ( index !== undefined ) {
  26630. delete indicesByUUID[ uuid ];
  26631. if ( index < nCachedObjects ) {
  26632. // object is cached, shrink the CACHED region
  26633. const firstActiveIndex = -- nCachedObjects,
  26634. lastCachedObject = objects[ firstActiveIndex ],
  26635. lastIndex = -- nObjects,
  26636. lastObject = objects[ lastIndex ];
  26637. // last cached object takes this object's place
  26638. indicesByUUID[ lastCachedObject.uuid ] = index;
  26639. objects[ index ] = lastCachedObject;
  26640. // last object goes to the activated slot and pop
  26641. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26642. objects[ firstActiveIndex ] = lastObject;
  26643. objects.pop();
  26644. // accounting is done, now do the same for all bindings
  26645. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26646. const bindingsForPath = bindings[ j ],
  26647. lastCached = bindingsForPath[ firstActiveIndex ],
  26648. last = bindingsForPath[ lastIndex ];
  26649. bindingsForPath[ index ] = lastCached;
  26650. bindingsForPath[ firstActiveIndex ] = last;
  26651. bindingsForPath.pop();
  26652. }
  26653. } else {
  26654. // object is active, just swap with the last and pop
  26655. const lastIndex = -- nObjects,
  26656. lastObject = objects[ lastIndex ];
  26657. if ( lastIndex > 0 ) {
  26658. indicesByUUID[ lastObject.uuid ] = index;
  26659. }
  26660. objects[ index ] = lastObject;
  26661. objects.pop();
  26662. // accounting is done, now do the same for all bindings
  26663. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26664. const bindingsForPath = bindings[ j ];
  26665. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26666. bindingsForPath.pop();
  26667. }
  26668. } // cached or active
  26669. } // if object is known
  26670. } // for arguments
  26671. this.nCachedObjects_ = nCachedObjects;
  26672. }
  26673. // Internal interface used by befriended PropertyBinding.Composite:
  26674. subscribe_( path, parsedPath ) {
  26675. // returns an array of bindings for the given path that is changed
  26676. // according to the contained objects in the group
  26677. const indicesByPath = this._bindingsIndicesByPath;
  26678. let index = indicesByPath[ path ];
  26679. const bindings = this._bindings;
  26680. if ( index !== undefined ) return bindings[ index ];
  26681. const paths = this._paths,
  26682. parsedPaths = this._parsedPaths,
  26683. objects = this._objects,
  26684. nObjects = objects.length,
  26685. nCachedObjects = this.nCachedObjects_,
  26686. bindingsForPath = new Array( nObjects );
  26687. index = bindings.length;
  26688. indicesByPath[ path ] = index;
  26689. paths.push( path );
  26690. parsedPaths.push( parsedPath );
  26691. bindings.push( bindingsForPath );
  26692. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26693. const object = objects[ i ];
  26694. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26695. }
  26696. return bindingsForPath;
  26697. }
  26698. unsubscribe_( path ) {
  26699. // tells the group to forget about a property path and no longer
  26700. // update the array previously obtained with 'subscribe_'
  26701. const indicesByPath = this._bindingsIndicesByPath,
  26702. index = indicesByPath[ path ];
  26703. if ( index !== undefined ) {
  26704. const paths = this._paths,
  26705. parsedPaths = this._parsedPaths,
  26706. bindings = this._bindings,
  26707. lastBindingsIndex = bindings.length - 1,
  26708. lastBindings = bindings[ lastBindingsIndex ],
  26709. lastBindingsPath = path[ lastBindingsIndex ];
  26710. indicesByPath[ lastBindingsPath ] = index;
  26711. bindings[ index ] = lastBindings;
  26712. bindings.pop();
  26713. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26714. parsedPaths.pop();
  26715. paths[ index ] = paths[ lastBindingsIndex ];
  26716. paths.pop();
  26717. }
  26718. }
  26719. }
  26720. class AnimationAction {
  26721. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26722. this._mixer = mixer;
  26723. this._clip = clip;
  26724. this._localRoot = localRoot;
  26725. this.blendMode = blendMode;
  26726. const tracks = clip.tracks,
  26727. nTracks = tracks.length,
  26728. interpolants = new Array( nTracks );
  26729. const interpolantSettings = {
  26730. endingStart: ZeroCurvatureEnding,
  26731. endingEnd: ZeroCurvatureEnding
  26732. };
  26733. for ( let i = 0; i !== nTracks; ++ i ) {
  26734. const interpolant = tracks[ i ].createInterpolant( null );
  26735. interpolants[ i ] = interpolant;
  26736. interpolant.settings = interpolantSettings;
  26737. }
  26738. this._interpolantSettings = interpolantSettings;
  26739. this._interpolants = interpolants; // bound by the mixer
  26740. // inside: PropertyMixer (managed by the mixer)
  26741. this._propertyBindings = new Array( nTracks );
  26742. this._cacheIndex = null; // for the memory manager
  26743. this._byClipCacheIndex = null; // for the memory manager
  26744. this._timeScaleInterpolant = null;
  26745. this._weightInterpolant = null;
  26746. this.loop = LoopRepeat;
  26747. this._loopCount = -1;
  26748. // global mixer time when the action is to be started
  26749. // it's set back to 'null' upon start of the action
  26750. this._startTime = null;
  26751. // scaled local time of the action
  26752. // gets clamped or wrapped to 0..clip.duration according to loop
  26753. this.time = 0;
  26754. this.timeScale = 1;
  26755. this._effectiveTimeScale = 1;
  26756. this.weight = 1;
  26757. this._effectiveWeight = 1;
  26758. this.repetitions = Infinity; // no. of repetitions when looping
  26759. this.paused = false; // true -> zero effective time scale
  26760. this.enabled = true; // false -> zero effective weight
  26761. this.clampWhenFinished = false;// keep feeding the last frame?
  26762. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26763. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26764. }
  26765. // State & Scheduling
  26766. play() {
  26767. this._mixer._activateAction( this );
  26768. return this;
  26769. }
  26770. stop() {
  26771. this._mixer._deactivateAction( this );
  26772. return this.reset();
  26773. }
  26774. reset() {
  26775. this.paused = false;
  26776. this.enabled = true;
  26777. this.time = 0; // restart clip
  26778. this._loopCount = -1;// forget previous loops
  26779. this._startTime = null;// forget scheduling
  26780. return this.stopFading().stopWarping();
  26781. }
  26782. isRunning() {
  26783. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26784. this._startTime === null && this._mixer._isActiveAction( this );
  26785. }
  26786. // return true when play has been called
  26787. isScheduled() {
  26788. return this._mixer._isActiveAction( this );
  26789. }
  26790. startAt( time ) {
  26791. this._startTime = time;
  26792. return this;
  26793. }
  26794. setLoop( mode, repetitions ) {
  26795. this.loop = mode;
  26796. this.repetitions = repetitions;
  26797. return this;
  26798. }
  26799. // Weight
  26800. // set the weight stopping any scheduled fading
  26801. // although .enabled = false yields an effective weight of zero, this
  26802. // method does *not* change .enabled, because it would be confusing
  26803. setEffectiveWeight( weight ) {
  26804. this.weight = weight;
  26805. // note: same logic as when updated at runtime
  26806. this._effectiveWeight = this.enabled ? weight : 0;
  26807. return this.stopFading();
  26808. }
  26809. // return the weight considering fading and .enabled
  26810. getEffectiveWeight() {
  26811. return this._effectiveWeight;
  26812. }
  26813. fadeIn( duration ) {
  26814. return this._scheduleFading( duration, 0, 1 );
  26815. }
  26816. fadeOut( duration ) {
  26817. return this._scheduleFading( duration, 1, 0 );
  26818. }
  26819. crossFadeFrom( fadeOutAction, duration, warp ) {
  26820. fadeOutAction.fadeOut( duration );
  26821. this.fadeIn( duration );
  26822. if ( warp ) {
  26823. const fadeInDuration = this._clip.duration,
  26824. fadeOutDuration = fadeOutAction._clip.duration,
  26825. startEndRatio = fadeOutDuration / fadeInDuration,
  26826. endStartRatio = fadeInDuration / fadeOutDuration;
  26827. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26828. this.warp( endStartRatio, 1.0, duration );
  26829. }
  26830. return this;
  26831. }
  26832. crossFadeTo( fadeInAction, duration, warp ) {
  26833. return fadeInAction.crossFadeFrom( this, duration, warp );
  26834. }
  26835. stopFading() {
  26836. const weightInterpolant = this._weightInterpolant;
  26837. if ( weightInterpolant !== null ) {
  26838. this._weightInterpolant = null;
  26839. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26840. }
  26841. return this;
  26842. }
  26843. // Time Scale Control
  26844. // set the time scale stopping any scheduled warping
  26845. // although .paused = true yields an effective time scale of zero, this
  26846. // method does *not* change .paused, because it would be confusing
  26847. setEffectiveTimeScale( timeScale ) {
  26848. this.timeScale = timeScale;
  26849. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26850. return this.stopWarping();
  26851. }
  26852. // return the time scale considering warping and .paused
  26853. getEffectiveTimeScale() {
  26854. return this._effectiveTimeScale;
  26855. }
  26856. setDuration( duration ) {
  26857. this.timeScale = this._clip.duration / duration;
  26858. return this.stopWarping();
  26859. }
  26860. syncWith( action ) {
  26861. this.time = action.time;
  26862. this.timeScale = action.timeScale;
  26863. return this.stopWarping();
  26864. }
  26865. halt( duration ) {
  26866. return this.warp( this._effectiveTimeScale, 0, duration );
  26867. }
  26868. warp( startTimeScale, endTimeScale, duration ) {
  26869. const mixer = this._mixer,
  26870. now = mixer.time,
  26871. timeScale = this.timeScale;
  26872. let interpolant = this._timeScaleInterpolant;
  26873. if ( interpolant === null ) {
  26874. interpolant = mixer._lendControlInterpolant();
  26875. this._timeScaleInterpolant = interpolant;
  26876. }
  26877. const times = interpolant.parameterPositions,
  26878. values = interpolant.sampleValues;
  26879. times[ 0 ] = now;
  26880. times[ 1 ] = now + duration;
  26881. values[ 0 ] = startTimeScale / timeScale;
  26882. values[ 1 ] = endTimeScale / timeScale;
  26883. return this;
  26884. }
  26885. stopWarping() {
  26886. const timeScaleInterpolant = this._timeScaleInterpolant;
  26887. if ( timeScaleInterpolant !== null ) {
  26888. this._timeScaleInterpolant = null;
  26889. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26890. }
  26891. return this;
  26892. }
  26893. // Object Accessors
  26894. getMixer() {
  26895. return this._mixer;
  26896. }
  26897. getClip() {
  26898. return this._clip;
  26899. }
  26900. getRoot() {
  26901. return this._localRoot || this._mixer._root;
  26902. }
  26903. // Interna
  26904. _update( time, deltaTime, timeDirection, accuIndex ) {
  26905. // called by the mixer
  26906. if ( ! this.enabled ) {
  26907. // call ._updateWeight() to update ._effectiveWeight
  26908. this._updateWeight( time );
  26909. return;
  26910. }
  26911. const startTime = this._startTime;
  26912. if ( startTime !== null ) {
  26913. // check for scheduled start of action
  26914. const timeRunning = ( time - startTime ) * timeDirection;
  26915. if ( timeRunning < 0 || timeDirection === 0 ) {
  26916. deltaTime = 0;
  26917. } else {
  26918. this._startTime = null; // unschedule
  26919. deltaTime = timeDirection * timeRunning;
  26920. }
  26921. }
  26922. // apply time scale and advance time
  26923. deltaTime *= this._updateTimeScale( time );
  26924. const clipTime = this._updateTime( deltaTime );
  26925. // note: _updateTime may disable the action resulting in
  26926. // an effective weight of 0
  26927. const weight = this._updateWeight( time );
  26928. if ( weight > 0 ) {
  26929. const interpolants = this._interpolants;
  26930. const propertyMixers = this._propertyBindings;
  26931. switch ( this.blendMode ) {
  26932. case AdditiveAnimationBlendMode:
  26933. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26934. interpolants[ j ].evaluate( clipTime );
  26935. propertyMixers[ j ].accumulateAdditive( weight );
  26936. }
  26937. break;
  26938. case NormalAnimationBlendMode:
  26939. default:
  26940. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26941. interpolants[ j ].evaluate( clipTime );
  26942. propertyMixers[ j ].accumulate( accuIndex, weight );
  26943. }
  26944. }
  26945. }
  26946. }
  26947. _updateWeight( time ) {
  26948. let weight = 0;
  26949. if ( this.enabled ) {
  26950. weight = this.weight;
  26951. const interpolant = this._weightInterpolant;
  26952. if ( interpolant !== null ) {
  26953. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26954. weight *= interpolantValue;
  26955. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26956. this.stopFading();
  26957. if ( interpolantValue === 0 ) {
  26958. // faded out, disable
  26959. this.enabled = false;
  26960. }
  26961. }
  26962. }
  26963. }
  26964. this._effectiveWeight = weight;
  26965. return weight;
  26966. }
  26967. _updateTimeScale( time ) {
  26968. let timeScale = 0;
  26969. if ( ! this.paused ) {
  26970. timeScale = this.timeScale;
  26971. const interpolant = this._timeScaleInterpolant;
  26972. if ( interpolant !== null ) {
  26973. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26974. timeScale *= interpolantValue;
  26975. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26976. this.stopWarping();
  26977. if ( timeScale === 0 ) {
  26978. // motion has halted, pause
  26979. this.paused = true;
  26980. } else {
  26981. // warp done - apply final time scale
  26982. this.timeScale = timeScale;
  26983. }
  26984. }
  26985. }
  26986. }
  26987. this._effectiveTimeScale = timeScale;
  26988. return timeScale;
  26989. }
  26990. _updateTime( deltaTime ) {
  26991. const duration = this._clip.duration;
  26992. const loop = this.loop;
  26993. let time = this.time + deltaTime;
  26994. let loopCount = this._loopCount;
  26995. const pingPong = ( loop === LoopPingPong );
  26996. if ( deltaTime === 0 ) {
  26997. if ( loopCount === -1 ) return time;
  26998. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26999. }
  27000. if ( loop === LoopOnce ) {
  27001. if ( loopCount === -1 ) {
  27002. // just started
  27003. this._loopCount = 0;
  27004. this._setEndings( true, true, false );
  27005. }
  27006. handle_stop: {
  27007. if ( time >= duration ) {
  27008. time = duration;
  27009. } else if ( time < 0 ) {
  27010. time = 0;
  27011. } else {
  27012. this.time = time;
  27013. break handle_stop;
  27014. }
  27015. if ( this.clampWhenFinished ) this.paused = true;
  27016. else this.enabled = false;
  27017. this.time = time;
  27018. this._mixer.dispatchEvent( {
  27019. type: 'finished', action: this,
  27020. direction: deltaTime < 0 ? -1 : 1
  27021. } );
  27022. }
  27023. } else { // repetitive Repeat or PingPong
  27024. if ( loopCount === -1 ) {
  27025. // just started
  27026. if ( deltaTime >= 0 ) {
  27027. loopCount = 0;
  27028. this._setEndings( true, this.repetitions === 0, pingPong );
  27029. } else {
  27030. // when looping in reverse direction, the initial
  27031. // transition through zero counts as a repetition,
  27032. // so leave loopCount at -1
  27033. this._setEndings( this.repetitions === 0, true, pingPong );
  27034. }
  27035. }
  27036. if ( time >= duration || time < 0 ) {
  27037. // wrap around
  27038. const loopDelta = Math.floor( time / duration ); // signed
  27039. time -= duration * loopDelta;
  27040. loopCount += Math.abs( loopDelta );
  27041. const pending = this.repetitions - loopCount;
  27042. if ( pending <= 0 ) {
  27043. // have to stop (switch state, clamp time, fire event)
  27044. if ( this.clampWhenFinished ) this.paused = true;
  27045. else this.enabled = false;
  27046. time = deltaTime > 0 ? duration : 0;
  27047. this.time = time;
  27048. this._mixer.dispatchEvent( {
  27049. type: 'finished', action: this,
  27050. direction: deltaTime > 0 ? 1 : -1
  27051. } );
  27052. } else {
  27053. // keep running
  27054. if ( pending === 1 ) {
  27055. // entering the last round
  27056. const atStart = deltaTime < 0;
  27057. this._setEndings( atStart, ! atStart, pingPong );
  27058. } else {
  27059. this._setEndings( false, false, pingPong );
  27060. }
  27061. this._loopCount = loopCount;
  27062. this.time = time;
  27063. this._mixer.dispatchEvent( {
  27064. type: 'loop', action: this, loopDelta: loopDelta
  27065. } );
  27066. }
  27067. } else {
  27068. this.time = time;
  27069. }
  27070. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27071. // invert time for the "pong round"
  27072. return duration - time;
  27073. }
  27074. }
  27075. return time;
  27076. }
  27077. _setEndings( atStart, atEnd, pingPong ) {
  27078. const settings = this._interpolantSettings;
  27079. if ( pingPong ) {
  27080. settings.endingStart = ZeroSlopeEnding;
  27081. settings.endingEnd = ZeroSlopeEnding;
  27082. } else {
  27083. // assuming for LoopOnce atStart == atEnd == true
  27084. if ( atStart ) {
  27085. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27086. } else {
  27087. settings.endingStart = WrapAroundEnding;
  27088. }
  27089. if ( atEnd ) {
  27090. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27091. } else {
  27092. settings.endingEnd = WrapAroundEnding;
  27093. }
  27094. }
  27095. }
  27096. _scheduleFading( duration, weightNow, weightThen ) {
  27097. const mixer = this._mixer, now = mixer.time;
  27098. let interpolant = this._weightInterpolant;
  27099. if ( interpolant === null ) {
  27100. interpolant = mixer._lendControlInterpolant();
  27101. this._weightInterpolant = interpolant;
  27102. }
  27103. const times = interpolant.parameterPositions,
  27104. values = interpolant.sampleValues;
  27105. times[ 0 ] = now;
  27106. values[ 0 ] = weightNow;
  27107. times[ 1 ] = now + duration;
  27108. values[ 1 ] = weightThen;
  27109. return this;
  27110. }
  27111. }
  27112. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27113. class AnimationMixer extends EventDispatcher {
  27114. constructor( root ) {
  27115. super();
  27116. this._root = root;
  27117. this._initMemoryManager();
  27118. this._accuIndex = 0;
  27119. this.time = 0;
  27120. this.timeScale = 1.0;
  27121. }
  27122. _bindAction( action, prototypeAction ) {
  27123. const root = action._localRoot || this._root,
  27124. tracks = action._clip.tracks,
  27125. nTracks = tracks.length,
  27126. bindings = action._propertyBindings,
  27127. interpolants = action._interpolants,
  27128. rootUuid = root.uuid,
  27129. bindingsByRoot = this._bindingsByRootAndName;
  27130. let bindingsByName = bindingsByRoot[ rootUuid ];
  27131. if ( bindingsByName === undefined ) {
  27132. bindingsByName = {};
  27133. bindingsByRoot[ rootUuid ] = bindingsByName;
  27134. }
  27135. for ( let i = 0; i !== nTracks; ++ i ) {
  27136. const track = tracks[ i ],
  27137. trackName = track.name;
  27138. let binding = bindingsByName[ trackName ];
  27139. if ( binding !== undefined ) {
  27140. ++ binding.referenceCount;
  27141. bindings[ i ] = binding;
  27142. } else {
  27143. binding = bindings[ i ];
  27144. if ( binding !== undefined ) {
  27145. // existing binding, make sure the cache knows
  27146. if ( binding._cacheIndex === null ) {
  27147. ++ binding.referenceCount;
  27148. this._addInactiveBinding( binding, rootUuid, trackName );
  27149. }
  27150. continue;
  27151. }
  27152. const path = prototypeAction && prototypeAction.
  27153. _propertyBindings[ i ].binding.parsedPath;
  27154. binding = new PropertyMixer(
  27155. PropertyBinding.create( root, trackName, path ),
  27156. track.ValueTypeName, track.getValueSize() );
  27157. ++ binding.referenceCount;
  27158. this._addInactiveBinding( binding, rootUuid, trackName );
  27159. bindings[ i ] = binding;
  27160. }
  27161. interpolants[ i ].resultBuffer = binding.buffer;
  27162. }
  27163. }
  27164. _activateAction( action ) {
  27165. if ( ! this._isActiveAction( action ) ) {
  27166. if ( action._cacheIndex === null ) {
  27167. // this action has been forgotten by the cache, but the user
  27168. // appears to be still using it -> rebind
  27169. const rootUuid = ( action._localRoot || this._root ).uuid,
  27170. clipUuid = action._clip.uuid,
  27171. actionsForClip = this._actionsByClip[ clipUuid ];
  27172. this._bindAction( action,
  27173. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27174. this._addInactiveAction( action, clipUuid, rootUuid );
  27175. }
  27176. const bindings = action._propertyBindings;
  27177. // increment reference counts / sort out state
  27178. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27179. const binding = bindings[ i ];
  27180. if ( binding.useCount ++ === 0 ) {
  27181. this._lendBinding( binding );
  27182. binding.saveOriginalState();
  27183. }
  27184. }
  27185. this._lendAction( action );
  27186. }
  27187. }
  27188. _deactivateAction( action ) {
  27189. if ( this._isActiveAction( action ) ) {
  27190. const bindings = action._propertyBindings;
  27191. // decrement reference counts / sort out state
  27192. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27193. const binding = bindings[ i ];
  27194. if ( -- binding.useCount === 0 ) {
  27195. binding.restoreOriginalState();
  27196. this._takeBackBinding( binding );
  27197. }
  27198. }
  27199. this._takeBackAction( action );
  27200. }
  27201. }
  27202. // Memory manager
  27203. _initMemoryManager() {
  27204. this._actions = []; // 'nActiveActions' followed by inactive ones
  27205. this._nActiveActions = 0;
  27206. this._actionsByClip = {};
  27207. // inside:
  27208. // {
  27209. // knownActions: Array< AnimationAction > - used as prototypes
  27210. // actionByRoot: AnimationAction - lookup
  27211. // }
  27212. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27213. this._nActiveBindings = 0;
  27214. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27215. this._controlInterpolants = []; // same game as above
  27216. this._nActiveControlInterpolants = 0;
  27217. const scope = this;
  27218. this.stats = {
  27219. actions: {
  27220. get total() {
  27221. return scope._actions.length;
  27222. },
  27223. get inUse() {
  27224. return scope._nActiveActions;
  27225. }
  27226. },
  27227. bindings: {
  27228. get total() {
  27229. return scope._bindings.length;
  27230. },
  27231. get inUse() {
  27232. return scope._nActiveBindings;
  27233. }
  27234. },
  27235. controlInterpolants: {
  27236. get total() {
  27237. return scope._controlInterpolants.length;
  27238. },
  27239. get inUse() {
  27240. return scope._nActiveControlInterpolants;
  27241. }
  27242. }
  27243. };
  27244. }
  27245. // Memory management for AnimationAction objects
  27246. _isActiveAction( action ) {
  27247. const index = action._cacheIndex;
  27248. return index !== null && index < this._nActiveActions;
  27249. }
  27250. _addInactiveAction( action, clipUuid, rootUuid ) {
  27251. const actions = this._actions,
  27252. actionsByClip = this._actionsByClip;
  27253. let actionsForClip = actionsByClip[ clipUuid ];
  27254. if ( actionsForClip === undefined ) {
  27255. actionsForClip = {
  27256. knownActions: [ action ],
  27257. actionByRoot: {}
  27258. };
  27259. action._byClipCacheIndex = 0;
  27260. actionsByClip[ clipUuid ] = actionsForClip;
  27261. } else {
  27262. const knownActions = actionsForClip.knownActions;
  27263. action._byClipCacheIndex = knownActions.length;
  27264. knownActions.push( action );
  27265. }
  27266. action._cacheIndex = actions.length;
  27267. actions.push( action );
  27268. actionsForClip.actionByRoot[ rootUuid ] = action;
  27269. }
  27270. _removeInactiveAction( action ) {
  27271. const actions = this._actions,
  27272. lastInactiveAction = actions[ actions.length - 1 ],
  27273. cacheIndex = action._cacheIndex;
  27274. lastInactiveAction._cacheIndex = cacheIndex;
  27275. actions[ cacheIndex ] = lastInactiveAction;
  27276. actions.pop();
  27277. action._cacheIndex = null;
  27278. const clipUuid = action._clip.uuid,
  27279. actionsByClip = this._actionsByClip,
  27280. actionsForClip = actionsByClip[ clipUuid ],
  27281. knownActionsForClip = actionsForClip.knownActions,
  27282. lastKnownAction =
  27283. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27284. byClipCacheIndex = action._byClipCacheIndex;
  27285. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27286. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27287. knownActionsForClip.pop();
  27288. action._byClipCacheIndex = null;
  27289. const actionByRoot = actionsForClip.actionByRoot,
  27290. rootUuid = ( action._localRoot || this._root ).uuid;
  27291. delete actionByRoot[ rootUuid ];
  27292. if ( knownActionsForClip.length === 0 ) {
  27293. delete actionsByClip[ clipUuid ];
  27294. }
  27295. this._removeInactiveBindingsForAction( action );
  27296. }
  27297. _removeInactiveBindingsForAction( action ) {
  27298. const bindings = action._propertyBindings;
  27299. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27300. const binding = bindings[ i ];
  27301. if ( -- binding.referenceCount === 0 ) {
  27302. this._removeInactiveBinding( binding );
  27303. }
  27304. }
  27305. }
  27306. _lendAction( action ) {
  27307. // [ active actions | inactive actions ]
  27308. // [ active actions >| inactive actions ]
  27309. // s a
  27310. // <-swap->
  27311. // a s
  27312. const actions = this._actions,
  27313. prevIndex = action._cacheIndex,
  27314. lastActiveIndex = this._nActiveActions ++,
  27315. firstInactiveAction = actions[ lastActiveIndex ];
  27316. action._cacheIndex = lastActiveIndex;
  27317. actions[ lastActiveIndex ] = action;
  27318. firstInactiveAction._cacheIndex = prevIndex;
  27319. actions[ prevIndex ] = firstInactiveAction;
  27320. }
  27321. _takeBackAction( action ) {
  27322. // [ active actions | inactive actions ]
  27323. // [ active actions |< inactive actions ]
  27324. // a s
  27325. // <-swap->
  27326. // s a
  27327. const actions = this._actions,
  27328. prevIndex = action._cacheIndex,
  27329. firstInactiveIndex = -- this._nActiveActions,
  27330. lastActiveAction = actions[ firstInactiveIndex ];
  27331. action._cacheIndex = firstInactiveIndex;
  27332. actions[ firstInactiveIndex ] = action;
  27333. lastActiveAction._cacheIndex = prevIndex;
  27334. actions[ prevIndex ] = lastActiveAction;
  27335. }
  27336. // Memory management for PropertyMixer objects
  27337. _addInactiveBinding( binding, rootUuid, trackName ) {
  27338. const bindingsByRoot = this._bindingsByRootAndName,
  27339. bindings = this._bindings;
  27340. let bindingByName = bindingsByRoot[ rootUuid ];
  27341. if ( bindingByName === undefined ) {
  27342. bindingByName = {};
  27343. bindingsByRoot[ rootUuid ] = bindingByName;
  27344. }
  27345. bindingByName[ trackName ] = binding;
  27346. binding._cacheIndex = bindings.length;
  27347. bindings.push( binding );
  27348. }
  27349. _removeInactiveBinding( binding ) {
  27350. const bindings = this._bindings,
  27351. propBinding = binding.binding,
  27352. rootUuid = propBinding.rootNode.uuid,
  27353. trackName = propBinding.path,
  27354. bindingsByRoot = this._bindingsByRootAndName,
  27355. bindingByName = bindingsByRoot[ rootUuid ],
  27356. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27357. cacheIndex = binding._cacheIndex;
  27358. lastInactiveBinding._cacheIndex = cacheIndex;
  27359. bindings[ cacheIndex ] = lastInactiveBinding;
  27360. bindings.pop();
  27361. delete bindingByName[ trackName ];
  27362. if ( Object.keys( bindingByName ).length === 0 ) {
  27363. delete bindingsByRoot[ rootUuid ];
  27364. }
  27365. }
  27366. _lendBinding( binding ) {
  27367. const bindings = this._bindings,
  27368. prevIndex = binding._cacheIndex,
  27369. lastActiveIndex = this._nActiveBindings ++,
  27370. firstInactiveBinding = bindings[ lastActiveIndex ];
  27371. binding._cacheIndex = lastActiveIndex;
  27372. bindings[ lastActiveIndex ] = binding;
  27373. firstInactiveBinding._cacheIndex = prevIndex;
  27374. bindings[ prevIndex ] = firstInactiveBinding;
  27375. }
  27376. _takeBackBinding( binding ) {
  27377. const bindings = this._bindings,
  27378. prevIndex = binding._cacheIndex,
  27379. firstInactiveIndex = -- this._nActiveBindings,
  27380. lastActiveBinding = bindings[ firstInactiveIndex ];
  27381. binding._cacheIndex = firstInactiveIndex;
  27382. bindings[ firstInactiveIndex ] = binding;
  27383. lastActiveBinding._cacheIndex = prevIndex;
  27384. bindings[ prevIndex ] = lastActiveBinding;
  27385. }
  27386. // Memory management of Interpolants for weight and time scale
  27387. _lendControlInterpolant() {
  27388. const interpolants = this._controlInterpolants,
  27389. lastActiveIndex = this._nActiveControlInterpolants ++;
  27390. let interpolant = interpolants[ lastActiveIndex ];
  27391. if ( interpolant === undefined ) {
  27392. interpolant = new LinearInterpolant(
  27393. new Float32Array( 2 ), new Float32Array( 2 ),
  27394. 1, _controlInterpolantsResultBuffer );
  27395. interpolant.__cacheIndex = lastActiveIndex;
  27396. interpolants[ lastActiveIndex ] = interpolant;
  27397. }
  27398. return interpolant;
  27399. }
  27400. _takeBackControlInterpolant( interpolant ) {
  27401. const interpolants = this._controlInterpolants,
  27402. prevIndex = interpolant.__cacheIndex,
  27403. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27404. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27405. interpolant.__cacheIndex = firstInactiveIndex;
  27406. interpolants[ firstInactiveIndex ] = interpolant;
  27407. lastActiveInterpolant.__cacheIndex = prevIndex;
  27408. interpolants[ prevIndex ] = lastActiveInterpolant;
  27409. }
  27410. // return an action for a clip optionally using a custom root target
  27411. // object (this method allocates a lot of dynamic memory in case a
  27412. // previously unknown clip/root combination is specified)
  27413. clipAction( clip, optionalRoot, blendMode ) {
  27414. const root = optionalRoot || this._root,
  27415. rootUuid = root.uuid;
  27416. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27417. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27418. const actionsForClip = this._actionsByClip[ clipUuid ];
  27419. let prototypeAction = null;
  27420. if ( blendMode === undefined ) {
  27421. if ( clipObject !== null ) {
  27422. blendMode = clipObject.blendMode;
  27423. } else {
  27424. blendMode = NormalAnimationBlendMode;
  27425. }
  27426. }
  27427. if ( actionsForClip !== undefined ) {
  27428. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27429. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27430. return existingAction;
  27431. }
  27432. // we know the clip, so we don't have to parse all
  27433. // the bindings again but can just copy
  27434. prototypeAction = actionsForClip.knownActions[ 0 ];
  27435. // also, take the clip from the prototype action
  27436. if ( clipObject === null )
  27437. clipObject = prototypeAction._clip;
  27438. }
  27439. // clip must be known when specified via string
  27440. if ( clipObject === null ) return null;
  27441. // allocate all resources required to run it
  27442. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27443. this._bindAction( newAction, prototypeAction );
  27444. // and make the action known to the memory manager
  27445. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27446. return newAction;
  27447. }
  27448. // get an existing action
  27449. existingAction( clip, optionalRoot ) {
  27450. const root = optionalRoot || this._root,
  27451. rootUuid = root.uuid,
  27452. clipObject = typeof clip === 'string' ?
  27453. AnimationClip.findByName( root, clip ) : clip,
  27454. clipUuid = clipObject ? clipObject.uuid : clip,
  27455. actionsForClip = this._actionsByClip[ clipUuid ];
  27456. if ( actionsForClip !== undefined ) {
  27457. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27458. }
  27459. return null;
  27460. }
  27461. // deactivates all previously scheduled actions
  27462. stopAllAction() {
  27463. const actions = this._actions,
  27464. nActions = this._nActiveActions;
  27465. for ( let i = nActions - 1; i >= 0; -- i ) {
  27466. actions[ i ].stop();
  27467. }
  27468. return this;
  27469. }
  27470. // advance the time and update apply the animation
  27471. update( deltaTime ) {
  27472. deltaTime *= this.timeScale;
  27473. const actions = this._actions,
  27474. nActions = this._nActiveActions,
  27475. time = this.time += deltaTime,
  27476. timeDirection = Math.sign( deltaTime ),
  27477. accuIndex = this._accuIndex ^= 1;
  27478. // run active actions
  27479. for ( let i = 0; i !== nActions; ++ i ) {
  27480. const action = actions[ i ];
  27481. action._update( time, deltaTime, timeDirection, accuIndex );
  27482. }
  27483. // update scene graph
  27484. const bindings = this._bindings,
  27485. nBindings = this._nActiveBindings;
  27486. for ( let i = 0; i !== nBindings; ++ i ) {
  27487. bindings[ i ].apply( accuIndex );
  27488. }
  27489. return this;
  27490. }
  27491. // Allows you to seek to a specific time in an animation.
  27492. setTime( timeInSeconds ) {
  27493. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27494. for ( let i = 0; i < this._actions.length; i ++ ) {
  27495. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27496. }
  27497. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27498. }
  27499. // return this mixer's root target object
  27500. getRoot() {
  27501. return this._root;
  27502. }
  27503. // free all resources specific to a particular clip
  27504. uncacheClip( clip ) {
  27505. const actions = this._actions,
  27506. clipUuid = clip.uuid,
  27507. actionsByClip = this._actionsByClip,
  27508. actionsForClip = actionsByClip[ clipUuid ];
  27509. if ( actionsForClip !== undefined ) {
  27510. // note: just calling _removeInactiveAction would mess up the
  27511. // iteration state and also require updating the state we can
  27512. // just throw away
  27513. const actionsToRemove = actionsForClip.knownActions;
  27514. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27515. const action = actionsToRemove[ i ];
  27516. this._deactivateAction( action );
  27517. const cacheIndex = action._cacheIndex,
  27518. lastInactiveAction = actions[ actions.length - 1 ];
  27519. action._cacheIndex = null;
  27520. action._byClipCacheIndex = null;
  27521. lastInactiveAction._cacheIndex = cacheIndex;
  27522. actions[ cacheIndex ] = lastInactiveAction;
  27523. actions.pop();
  27524. this._removeInactiveBindingsForAction( action );
  27525. }
  27526. delete actionsByClip[ clipUuid ];
  27527. }
  27528. }
  27529. // free all resources specific to a particular root target object
  27530. uncacheRoot( root ) {
  27531. const rootUuid = root.uuid,
  27532. actionsByClip = this._actionsByClip;
  27533. for ( const clipUuid in actionsByClip ) {
  27534. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27535. action = actionByRoot[ rootUuid ];
  27536. if ( action !== undefined ) {
  27537. this._deactivateAction( action );
  27538. this._removeInactiveAction( action );
  27539. }
  27540. }
  27541. const bindingsByRoot = this._bindingsByRootAndName,
  27542. bindingByName = bindingsByRoot[ rootUuid ];
  27543. if ( bindingByName !== undefined ) {
  27544. for ( const trackName in bindingByName ) {
  27545. const binding = bindingByName[ trackName ];
  27546. binding.restoreOriginalState();
  27547. this._removeInactiveBinding( binding );
  27548. }
  27549. }
  27550. }
  27551. // remove a targeted clip from the cache
  27552. uncacheAction( clip, optionalRoot ) {
  27553. const action = this.existingAction( clip, optionalRoot );
  27554. if ( action !== null ) {
  27555. this._deactivateAction( action );
  27556. this._removeInactiveAction( action );
  27557. }
  27558. }
  27559. }
  27560. class RenderTarget3D extends RenderTarget {
  27561. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  27562. super( width, height, options );
  27563. this.isRenderTarget3D = true;
  27564. this.depth = depth;
  27565. this.texture = new Data3DTexture( null, width, height, depth );
  27566. this.texture.isRenderTargetTexture = true;
  27567. }
  27568. }
  27569. class RenderTargetArray extends RenderTarget {
  27570. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  27571. super( width, height, options );
  27572. this.isRenderTargetArray = true;
  27573. this.depth = depth;
  27574. this.texture = new DataArrayTexture( null, width, height, depth );
  27575. this.texture.isRenderTargetTexture = true;
  27576. }
  27577. }
  27578. class Uniform {
  27579. constructor( value ) {
  27580. this.value = value;
  27581. }
  27582. clone() {
  27583. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27584. }
  27585. }
  27586. let _id$1 = 0;
  27587. class UniformsGroup extends EventDispatcher {
  27588. constructor() {
  27589. super();
  27590. this.isUniformsGroup = true;
  27591. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  27592. this.name = '';
  27593. this.usage = StaticDrawUsage;
  27594. this.uniforms = [];
  27595. }
  27596. add( uniform ) {
  27597. this.uniforms.push( uniform );
  27598. return this;
  27599. }
  27600. remove( uniform ) {
  27601. const index = this.uniforms.indexOf( uniform );
  27602. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  27603. return this;
  27604. }
  27605. setName( name ) {
  27606. this.name = name;
  27607. return this;
  27608. }
  27609. setUsage( value ) {
  27610. this.usage = value;
  27611. return this;
  27612. }
  27613. dispose() {
  27614. this.dispatchEvent( { type: 'dispose' } );
  27615. return this;
  27616. }
  27617. copy( source ) {
  27618. this.name = source.name;
  27619. this.usage = source.usage;
  27620. const uniformsSource = source.uniforms;
  27621. this.uniforms.length = 0;
  27622. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  27623. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  27624. for ( let j = 0; j < uniforms.length; j ++ ) {
  27625. this.uniforms.push( uniforms[ j ].clone() );
  27626. }
  27627. }
  27628. return this;
  27629. }
  27630. clone() {
  27631. return new this.constructor().copy( this );
  27632. }
  27633. }
  27634. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27635. constructor( array, stride, meshPerAttribute = 1 ) {
  27636. super( array, stride );
  27637. this.isInstancedInterleavedBuffer = true;
  27638. this.meshPerAttribute = meshPerAttribute;
  27639. }
  27640. copy( source ) {
  27641. super.copy( source );
  27642. this.meshPerAttribute = source.meshPerAttribute;
  27643. return this;
  27644. }
  27645. clone( data ) {
  27646. const ib = super.clone( data );
  27647. ib.meshPerAttribute = this.meshPerAttribute;
  27648. return ib;
  27649. }
  27650. toJSON( data ) {
  27651. const json = super.toJSON( data );
  27652. json.isInstancedInterleavedBuffer = true;
  27653. json.meshPerAttribute = this.meshPerAttribute;
  27654. return json;
  27655. }
  27656. }
  27657. class GLBufferAttribute {
  27658. constructor( buffer, type, itemSize, elementSize, count ) {
  27659. this.isGLBufferAttribute = true;
  27660. this.name = '';
  27661. this.buffer = buffer;
  27662. this.type = type;
  27663. this.itemSize = itemSize;
  27664. this.elementSize = elementSize;
  27665. this.count = count;
  27666. this.version = 0;
  27667. }
  27668. set needsUpdate( value ) {
  27669. if ( value === true ) this.version ++;
  27670. }
  27671. setBuffer( buffer ) {
  27672. this.buffer = buffer;
  27673. return this;
  27674. }
  27675. setType( type, elementSize ) {
  27676. this.type = type;
  27677. this.elementSize = elementSize;
  27678. return this;
  27679. }
  27680. setItemSize( itemSize ) {
  27681. this.itemSize = itemSize;
  27682. return this;
  27683. }
  27684. setCount( count ) {
  27685. this.count = count;
  27686. return this;
  27687. }
  27688. }
  27689. const _matrix = /*@__PURE__*/ new Matrix4();
  27690. class Raycaster {
  27691. constructor( origin, direction, near = 0, far = Infinity ) {
  27692. this.ray = new Ray( origin, direction );
  27693. // direction is assumed to be normalized (for accurate distance calculations)
  27694. this.near = near;
  27695. this.far = far;
  27696. this.camera = null;
  27697. this.layers = new Layers();
  27698. this.params = {
  27699. Mesh: {},
  27700. Line: { threshold: 1 },
  27701. LOD: {},
  27702. Points: { threshold: 1 },
  27703. Sprite: {}
  27704. };
  27705. }
  27706. set( origin, direction ) {
  27707. // direction is assumed to be normalized (for accurate distance calculations)
  27708. this.ray.set( origin, direction );
  27709. }
  27710. setFromCamera( coords, camera ) {
  27711. if ( camera.isPerspectiveCamera ) {
  27712. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27713. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27714. this.camera = camera;
  27715. } else if ( camera.isOrthographicCamera ) {
  27716. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27717. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  27718. this.camera = camera;
  27719. } else {
  27720. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27721. }
  27722. }
  27723. setFromXRController( controller ) {
  27724. _matrix.identity().extractRotation( controller.matrixWorld );
  27725. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  27726. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  27727. return this;
  27728. }
  27729. intersectObject( object, recursive = true, intersects = [] ) {
  27730. intersect( object, this, intersects, recursive );
  27731. intersects.sort( ascSort );
  27732. return intersects;
  27733. }
  27734. intersectObjects( objects, recursive = true, intersects = [] ) {
  27735. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27736. intersect( objects[ i ], this, intersects, recursive );
  27737. }
  27738. intersects.sort( ascSort );
  27739. return intersects;
  27740. }
  27741. }
  27742. function ascSort( a, b ) {
  27743. return a.distance - b.distance;
  27744. }
  27745. function intersect( object, raycaster, intersects, recursive ) {
  27746. let propagate = true;
  27747. if ( object.layers.test( raycaster.layers ) ) {
  27748. const result = object.raycast( raycaster, intersects );
  27749. if ( result === false ) propagate = false;
  27750. }
  27751. if ( propagate === true && recursive === true ) {
  27752. const children = object.children;
  27753. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27754. intersect( children[ i ], raycaster, intersects, true );
  27755. }
  27756. }
  27757. }
  27758. /**
  27759. * This class can be used to represent points in 3D space as
  27760. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  27761. */
  27762. class Spherical {
  27763. /**
  27764. * Constructs a new spherical.
  27765. *
  27766. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  27767. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  27768. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  27769. */
  27770. constructor( radius = 1, phi = 0, theta = 0 ) {
  27771. /**
  27772. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  27773. *
  27774. * @type {number}
  27775. * @default 1
  27776. */
  27777. this.radius = radius;
  27778. /**
  27779. * The polar angle in radians from the y (up) axis.
  27780. *
  27781. * @type {number}
  27782. * @default 0
  27783. */
  27784. this.phi = phi;
  27785. /**
  27786. * The equator/azimuthal angle in radians around the y (up) axis.
  27787. *
  27788. * @type {number}
  27789. * @default 0
  27790. */
  27791. this.theta = theta;
  27792. }
  27793. /**
  27794. * Sets the spherical components by copying the given values.
  27795. *
  27796. * @param {number} radius - The radius.
  27797. * @param {number} phi - The polar angle.
  27798. * @param {number} theta - The azimuthal angle.
  27799. * @return {Spherical} A reference to this spherical.
  27800. */
  27801. set( radius, phi, theta ) {
  27802. this.radius = radius;
  27803. this.phi = phi;
  27804. this.theta = theta;
  27805. return this;
  27806. }
  27807. /**
  27808. * Copies the values of the given spherical to this instance.
  27809. *
  27810. * @param {Spherical} other - The spherical to copy.
  27811. * @return {Spherical} A reference to this spherical.
  27812. */
  27813. copy( other ) {
  27814. this.radius = other.radius;
  27815. this.phi = other.phi;
  27816. this.theta = other.theta;
  27817. return this;
  27818. }
  27819. /**
  27820. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  27821. * `0.000001`.
  27822. *
  27823. * @return {Spherical} A reference to this spherical.
  27824. */
  27825. makeSafe() {
  27826. const EPS = 0.000001;
  27827. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  27828. return this;
  27829. }
  27830. /**
  27831. * Sets the spherical components from the given vector which is assumed to hold
  27832. * Cartesian coordinates.
  27833. *
  27834. * @param {Vector3} v - The vector to set.
  27835. * @return {Spherical} A reference to this spherical.
  27836. */
  27837. setFromVector3( v ) {
  27838. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27839. }
  27840. /**
  27841. * Sets the spherical components from the given Cartesian coordinates.
  27842. *
  27843. * @param {number} x - The x value.
  27844. * @param {number} y - The x value.
  27845. * @param {number} z - The x value.
  27846. * @return {Spherical} A reference to this spherical.
  27847. */
  27848. setFromCartesianCoords( x, y, z ) {
  27849. this.radius = Math.sqrt( x * x + y * y + z * z );
  27850. if ( this.radius === 0 ) {
  27851. this.theta = 0;
  27852. this.phi = 0;
  27853. } else {
  27854. this.theta = Math.atan2( x, z );
  27855. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  27856. }
  27857. return this;
  27858. }
  27859. /**
  27860. * Returns a new spherical with copied values from this instance.
  27861. *
  27862. * @return {Spherical} A clone of this instance.
  27863. */
  27864. clone() {
  27865. return new this.constructor().copy( this );
  27866. }
  27867. }
  27868. /**
  27869. * This class can be used to represent points in 3D space as
  27870. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  27871. */
  27872. class Cylindrical {
  27873. /**
  27874. * Constructs a new cylindrical.
  27875. *
  27876. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  27877. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  27878. * @param {number} [y=0] - The height above the x-z plane.
  27879. */
  27880. constructor( radius = 1, theta = 0, y = 0 ) {
  27881. /**
  27882. * The distance from the origin to a point in the x-z plane.
  27883. *
  27884. * @type {number}
  27885. * @default 1
  27886. */
  27887. this.radius = radius;
  27888. /**
  27889. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  27890. *
  27891. * @type {number}
  27892. * @default 0
  27893. */
  27894. this.theta = theta;
  27895. /**
  27896. * The height above the x-z plane.
  27897. *
  27898. * @type {number}
  27899. * @default 0
  27900. */
  27901. this.y = y;
  27902. }
  27903. /**
  27904. * Sets the cylindrical components by copying the given values.
  27905. *
  27906. * @param {number} radius - The radius.
  27907. * @param {number} theta - The theta angle.
  27908. * @param {number} y - The height value.
  27909. * @return {Cylindrical} A reference to this cylindrical.
  27910. */
  27911. set( radius, theta, y ) {
  27912. this.radius = radius;
  27913. this.theta = theta;
  27914. this.y = y;
  27915. return this;
  27916. }
  27917. /**
  27918. * Copies the values of the given cylindrical to this instance.
  27919. *
  27920. * @param {Cylindrical} other - The cylindrical to copy.
  27921. * @return {Cylindrical} A reference to this cylindrical.
  27922. */
  27923. copy( other ) {
  27924. this.radius = other.radius;
  27925. this.theta = other.theta;
  27926. this.y = other.y;
  27927. return this;
  27928. }
  27929. /**
  27930. * Sets the cylindrical components from the given vector which is assumed to hold
  27931. * Cartesian coordinates.
  27932. *
  27933. * @param {Vector3} v - The vector to set.
  27934. * @return {Cylindrical} A reference to this cylindrical.
  27935. */
  27936. setFromVector3( v ) {
  27937. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27938. }
  27939. /**
  27940. * Sets the cylindrical components from the given Cartesian coordinates.
  27941. *
  27942. * @param {number} x - The x value.
  27943. * @param {number} y - The x value.
  27944. * @param {number} z - The x value.
  27945. * @return {Cylindrical} A reference to this cylindrical.
  27946. */
  27947. setFromCartesianCoords( x, y, z ) {
  27948. this.radius = Math.sqrt( x * x + z * z );
  27949. this.theta = Math.atan2( x, z );
  27950. this.y = y;
  27951. return this;
  27952. }
  27953. /**
  27954. * Returns a new cylindrical with copied values from this instance.
  27955. *
  27956. * @return {Cylindrical} A clone of this instance.
  27957. */
  27958. clone() {
  27959. return new this.constructor().copy( this );
  27960. }
  27961. }
  27962. /**
  27963. * Represents a 2x2 matrix.
  27964. *
  27965. * A Note on Row-Major and Column-Major Ordering:
  27966. *
  27967. * The constructor and {@link Matrix2#set} method take arguments in
  27968. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  27969. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  27970. * This means that calling:
  27971. * ```js
  27972. * const m = new THREE.Matrix2();
  27973. * m.set( 11, 12,
  27974. * 21, 22 );
  27975. * ```
  27976. * will result in the elements array containing:
  27977. * ```js
  27978. * m.elements = [ 11, 21,
  27979. * 12, 22 ];
  27980. * ```
  27981. * and internally all calculations are performed using column-major ordering.
  27982. * However, as the actual ordering makes no difference mathematically and
  27983. * most people are used to thinking about matrices in row-major order, the
  27984. * three.js documentation shows matrices in row-major order. Just bear in
  27985. * mind that if you are reading the source code, you'll have to take the
  27986. * transpose of any matrices outlined here to make sense of the calculations.
  27987. */
  27988. class Matrix2 {
  27989. /**
  27990. * Constructs a new 2x2 matrix. The arguments are supposed to be
  27991. * in row-major order. If no arguments are provided, the constructor
  27992. * initializes the matrix as an identity matrix.
  27993. *
  27994. * @param {number} [n11] - 1-1 matrix element.
  27995. * @param {number} [n12] - 1-2 matrix element.
  27996. * @param {number} [n21] - 2-1 matrix element.
  27997. * @param {number} [n22] - 2-2 matrix element.
  27998. */
  27999. constructor( n11, n12, n21, n22 ) {
  28000. /**
  28001. * This flag can be used for type testing.
  28002. *
  28003. * @type {boolean}
  28004. * @readonly
  28005. * @default true
  28006. */
  28007. Matrix2.prototype.isMatrix2 = true;
  28008. /**
  28009. * A column-major list of matrix values.
  28010. *
  28011. * @type {Array<number>}
  28012. */
  28013. this.elements = [
  28014. 1, 0,
  28015. 0, 1,
  28016. ];
  28017. if ( n11 !== undefined ) {
  28018. this.set( n11, n12, n21, n22 );
  28019. }
  28020. }
  28021. /**
  28022. * Sets this matrix to the 2x2 identity matrix.
  28023. *
  28024. * @return {Matrix2} A reference to this matrix.
  28025. */
  28026. identity() {
  28027. this.set(
  28028. 1, 0,
  28029. 0, 1,
  28030. );
  28031. return this;
  28032. }
  28033. /**
  28034. * Sets the elements of the matrix from the given array.
  28035. *
  28036. * @param {Array<number>} array - The matrix elements in column-major order.
  28037. * @param {number} [offset=0] - Index of the first element in the array.
  28038. * @return {Matrix2} A reference to this matrix.
  28039. */
  28040. fromArray( array, offset = 0 ) {
  28041. for ( let i = 0; i < 4; i ++ ) {
  28042. this.elements[ i ] = array[ i + offset ];
  28043. }
  28044. return this;
  28045. }
  28046. /**
  28047. * Sets the elements of the matrix.The arguments are supposed to be
  28048. * in row-major order.
  28049. *
  28050. * @param {number} n11 - 1-1 matrix element.
  28051. * @param {number} n12 - 1-2 matrix element.
  28052. * @param {number} n21 - 2-1 matrix element.
  28053. * @param {number} n22 - 2-2 matrix element.
  28054. * @return {Matrix2} A reference to this matrix.
  28055. */
  28056. set( n11, n12, n21, n22 ) {
  28057. const te = this.elements;
  28058. te[ 0 ] = n11; te[ 2 ] = n12;
  28059. te[ 1 ] = n21; te[ 3 ] = n22;
  28060. return this;
  28061. }
  28062. }
  28063. const _vector$4 = /*@__PURE__*/ new Vector2();
  28064. /**
  28065. * Represents an axis-aligned bounding box (AABB) in 2D space.
  28066. */
  28067. class Box2 {
  28068. /**
  28069. * Constructs a new bounding box.
  28070. *
  28071. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  28072. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  28073. */
  28074. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28075. /**
  28076. * This flag can be used for type testing.
  28077. *
  28078. * @type {boolean}
  28079. * @readonly
  28080. * @default true
  28081. */
  28082. this.isBox2 = true;
  28083. /**
  28084. * The lower boundary of the box.
  28085. *
  28086. * @type {Vector2}
  28087. */
  28088. this.min = min;
  28089. /**
  28090. * The upper boundary of the box.
  28091. *
  28092. * @type {Vector2}
  28093. */
  28094. this.max = max;
  28095. }
  28096. /**
  28097. * Sets the lower and upper boundaries of this box.
  28098. * Please note that this method only copies the values from the given objects.
  28099. *
  28100. * @param {Vector2} min - The lower boundary of the box.
  28101. * @param {Vector2} max - The upper boundary of the box.
  28102. * @return {Box2} A reference to this bounding box.
  28103. */
  28104. set( min, max ) {
  28105. this.min.copy( min );
  28106. this.max.copy( max );
  28107. return this;
  28108. }
  28109. /**
  28110. * Sets the upper and lower bounds of this box so it encloses the position data
  28111. * in the given array.
  28112. *
  28113. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  28114. * @return {Box2} A reference to this bounding box.
  28115. */
  28116. setFromPoints( points ) {
  28117. this.makeEmpty();
  28118. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28119. this.expandByPoint( points[ i ] );
  28120. }
  28121. return this;
  28122. }
  28123. /**
  28124. * Centers this box on the given center vector and sets this box's width, height and
  28125. * depth to the given size values.
  28126. *
  28127. * @param {Vector2} center - The center of the box.
  28128. * @param {Vector2} size - The x and y dimensions of the box.
  28129. * @return {Box2} A reference to this bounding box.
  28130. */
  28131. setFromCenterAndSize( center, size ) {
  28132. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28133. this.min.copy( center ).sub( halfSize );
  28134. this.max.copy( center ).add( halfSize );
  28135. return this;
  28136. }
  28137. /**
  28138. * Returns a new box with copied values from this instance.
  28139. *
  28140. * @return {Box2} A clone of this instance.
  28141. */
  28142. clone() {
  28143. return new this.constructor().copy( this );
  28144. }
  28145. /**
  28146. * Copies the values of the given box to this instance.
  28147. *
  28148. * @param {Box2} box - The box to copy.
  28149. * @return {Box2} A reference to this bounding box.
  28150. */
  28151. copy( box ) {
  28152. this.min.copy( box.min );
  28153. this.max.copy( box.max );
  28154. return this;
  28155. }
  28156. /**
  28157. * Makes this box empty which means in encloses a zero space in 2D.
  28158. *
  28159. * @return {Box2} A reference to this bounding box.
  28160. */
  28161. makeEmpty() {
  28162. this.min.x = this.min.y = + Infinity;
  28163. this.max.x = this.max.y = - Infinity;
  28164. return this;
  28165. }
  28166. /**
  28167. * Returns true if this box includes zero points within its bounds.
  28168. * Note that a box with equal lower and upper bounds still includes one
  28169. * point, the one both bounds share.
  28170. *
  28171. * @return {boolean} Whether this box is empty or not.
  28172. */
  28173. isEmpty() {
  28174. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28175. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28176. }
  28177. /**
  28178. * Returns the center point of this box.
  28179. *
  28180. * @param {Vector2} target - The target vector that is used to store the method's result.
  28181. * @return {Vector2} The center point.
  28182. */
  28183. getCenter( target ) {
  28184. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28185. }
  28186. /**
  28187. * Returns the dimensions of this box.
  28188. *
  28189. * @param {Vector2} target - The target vector that is used to store the method's result.
  28190. * @return {Vector2} The size.
  28191. */
  28192. getSize( target ) {
  28193. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28194. }
  28195. /**
  28196. * Expands the boundaries of this box to include the given point.
  28197. *
  28198. * @param {Vector2} point - The point that should be included by the bounding box.
  28199. * @return {Box2} A reference to this bounding box.
  28200. */
  28201. expandByPoint( point ) {
  28202. this.min.min( point );
  28203. this.max.max( point );
  28204. return this;
  28205. }
  28206. /**
  28207. * Expands this box equilaterally by the given vector. The width of this
  28208. * box will be expanded by the x component of the vector in both
  28209. * directions. The height of this box will be expanded by the y component of
  28210. * the vector in both directions.
  28211. *
  28212. * @param {Vector2} vector - The vector that should expand the bounding box.
  28213. * @return {Box2} A reference to this bounding box.
  28214. */
  28215. expandByVector( vector ) {
  28216. this.min.sub( vector );
  28217. this.max.add( vector );
  28218. return this;
  28219. }
  28220. /**
  28221. * Expands each dimension of the box by the given scalar. If negative, the
  28222. * dimensions of the box will be contracted.
  28223. *
  28224. * @param {number} scalar - The scalar value that should expand the bounding box.
  28225. * @return {Box2} A reference to this bounding box.
  28226. */
  28227. expandByScalar( scalar ) {
  28228. this.min.addScalar( - scalar );
  28229. this.max.addScalar( scalar );
  28230. return this;
  28231. }
  28232. /**
  28233. * Returns `true` if the given point lies within or on the boundaries of this box.
  28234. *
  28235. * @param {Vector2} point - The point to test.
  28236. * @return {boolean} Whether the bounding box contains the given point or not.
  28237. */
  28238. containsPoint( point ) {
  28239. return point.x >= this.min.x && point.x <= this.max.x &&
  28240. point.y >= this.min.y && point.y <= this.max.y;
  28241. }
  28242. /**
  28243. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  28244. * If this box and the given one are identical, this function also returns `true`.
  28245. *
  28246. * @param {Box2} box - The bounding box to test.
  28247. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  28248. */
  28249. containsBox( box ) {
  28250. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28251. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28252. }
  28253. /**
  28254. * Returns a point as a proportion of this box's width and height.
  28255. *
  28256. * @param {Vector2} point - A point in 2D space.
  28257. * @param {Vector2} target - The target vector that is used to store the method's result.
  28258. * @return {Vector2} A point as a proportion of this box's width and height.
  28259. */
  28260. getParameter( point, target ) {
  28261. // This can potentially have a divide by zero if the box
  28262. // has a size dimension of 0.
  28263. return target.set(
  28264. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28265. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28266. );
  28267. }
  28268. /**
  28269. * Returns `true` if the given bounding box intersects with this bounding box.
  28270. *
  28271. * @param {Box2} box - The bounding box to test.
  28272. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  28273. */
  28274. intersectsBox( box ) {
  28275. // using 4 splitting planes to rule out intersections
  28276. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  28277. box.max.y >= this.min.y && box.min.y <= this.max.y;
  28278. }
  28279. /**
  28280. * Clamps the given point within the bounds of this box.
  28281. *
  28282. * @param {Vector2} point - The point to clamp.
  28283. * @param {Vector2} target - The target vector that is used to store the method's result.
  28284. * @return {Vector2} The clamped point.
  28285. */
  28286. clampPoint( point, target ) {
  28287. return target.copy( point ).clamp( this.min, this.max );
  28288. }
  28289. /**
  28290. * Returns the euclidean distance from any edge of this box to the specified point. If
  28291. * the given point lies inside of this box, the distance will be `0`.
  28292. *
  28293. * @param {Vector2} point - The point to compute the distance to.
  28294. * @return {number} The euclidean distance.
  28295. */
  28296. distanceToPoint( point ) {
  28297. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28298. }
  28299. /**
  28300. * Computes the intersection of this bounding box and the given one, setting the upper
  28301. * bound of this box to the lesser of the two boxes' upper bounds and the
  28302. * lower bound of this box to the greater of the two boxes' lower bounds. If
  28303. * there's no overlap, makes this box empty.
  28304. *
  28305. * @param {Box2} box - The bounding box to intersect with.
  28306. * @return {Box2} A reference to this bounding box.
  28307. */
  28308. intersect( box ) {
  28309. this.min.max( box.min );
  28310. this.max.min( box.max );
  28311. if ( this.isEmpty() ) this.makeEmpty();
  28312. return this;
  28313. }
  28314. /**
  28315. * Computes the union of this box and another and the given one, setting the upper
  28316. * bound of this box to the greater of the two boxes' upper bounds and the
  28317. * lower bound of this box to the lesser of the two boxes' lower bounds.
  28318. *
  28319. * @param {Box2} box - The bounding box that will be unioned with this instance.
  28320. * @return {Box2} A reference to this bounding box.
  28321. */
  28322. union( box ) {
  28323. this.min.min( box.min );
  28324. this.max.max( box.max );
  28325. return this;
  28326. }
  28327. /**
  28328. * Adds the given offset to both the upper and lower bounds of this bounding box,
  28329. * effectively moving it in 2D space.
  28330. *
  28331. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  28332. * @return {Box2} A reference to this bounding box.
  28333. */
  28334. translate( offset ) {
  28335. this.min.add( offset );
  28336. this.max.add( offset );
  28337. return this;
  28338. }
  28339. /**
  28340. * Returns `true` if this bounding box is equal with the given one.
  28341. *
  28342. * @param {Box2} box - The box to test for equality.
  28343. * @return {boolean} Whether this bounding box is equal with the given one.
  28344. */
  28345. equals( box ) {
  28346. return box.min.equals( this.min ) && box.max.equals( this.max );
  28347. }
  28348. }
  28349. const _startP = /*@__PURE__*/ new Vector3();
  28350. const _startEnd = /*@__PURE__*/ new Vector3();
  28351. /**
  28352. * An analytical line segment in 3D space represented by a start and end point.
  28353. */
  28354. class Line3 {
  28355. /**
  28356. * Constructs a new line segment.
  28357. *
  28358. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  28359. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  28360. */
  28361. constructor( start = new Vector3(), end = new Vector3() ) {
  28362. /**
  28363. * Start of the line segment.
  28364. *
  28365. * @type {Vector3}
  28366. */
  28367. this.start = start;
  28368. /**
  28369. * End of the line segment.
  28370. *
  28371. * @type {Vector3}
  28372. */
  28373. this.end = end;
  28374. }
  28375. /**
  28376. * Sets the start and end values by copying the given vectors.
  28377. *
  28378. * @param {Vector3} start - The start point.
  28379. * @param {Vector3} end - The end point.
  28380. * @return {Line3} A reference to this line segment.
  28381. */
  28382. set( start, end ) {
  28383. this.start.copy( start );
  28384. this.end.copy( end );
  28385. return this;
  28386. }
  28387. /**
  28388. * Copies the values of the given line segment to this instance.
  28389. *
  28390. * @param {Line3} line - The line segment to copy.
  28391. * @return {Line3} A reference to this line segment.
  28392. */
  28393. copy( line ) {
  28394. this.start.copy( line.start );
  28395. this.end.copy( line.end );
  28396. return this;
  28397. }
  28398. /**
  28399. * Returns the center of the line segment.
  28400. *
  28401. * @param {Vector3} target - The target vector that is used to store the method's result.
  28402. * @return {Vector3} The center point.
  28403. */
  28404. getCenter( target ) {
  28405. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28406. }
  28407. /**
  28408. * Returns the delta vector of the line segment's start and end point.
  28409. *
  28410. * @param {Vector3} target - The target vector that is used to store the method's result.
  28411. * @return {Vector3} The delta vector.
  28412. */
  28413. delta( target ) {
  28414. return target.subVectors( this.end, this.start );
  28415. }
  28416. /**
  28417. * Returns the squared Euclidean distance between the line' start and end point.
  28418. *
  28419. * @return {Vector3} The squared Euclidean distance.
  28420. */
  28421. distanceSq() {
  28422. return this.start.distanceToSquared( this.end );
  28423. }
  28424. /**
  28425. * Returns the Euclidean distance between the line' start and end point.
  28426. *
  28427. * @return {Vector3} The Euclidean distance.
  28428. */
  28429. distance() {
  28430. return this.start.distanceTo( this.end );
  28431. }
  28432. /**
  28433. * Returns a vector at a certain position along the line segment.
  28434. *
  28435. * @param {Vector3} t - A value between `[0,1]` to represent a position along the line segment.
  28436. * @param {Vector3} target - The target vector that is used to store the method's result.
  28437. * @return {Vector3} The delta vector.
  28438. */
  28439. at( t, target ) {
  28440. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28441. }
  28442. /**
  28443. * Returns a point parameter based on the closest point as projected on the line segment.
  28444. *
  28445. * @param {Vector3} point - The point for which to return a point parameter.
  28446. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  28447. * @return {number} The point parameter.
  28448. */
  28449. closestPointToPointParameter( point, clampToLine ) {
  28450. _startP.subVectors( point, this.start );
  28451. _startEnd.subVectors( this.end, this.start );
  28452. const startEnd2 = _startEnd.dot( _startEnd );
  28453. const startEnd_startP = _startEnd.dot( _startP );
  28454. let t = startEnd_startP / startEnd2;
  28455. if ( clampToLine ) {
  28456. t = clamp( t, 0, 1 );
  28457. }
  28458. return t;
  28459. }
  28460. /**
  28461. * Returns the closets point on the line for a given point.
  28462. *
  28463. * @param {Vector3} point - The point to compute the closest point on the line for.
  28464. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  28465. * @param {Vector3} target - The target vector that is used to store the method's result.
  28466. * @return {Vector3} The closest point on the line.
  28467. */
  28468. closestPointToPoint( point, clampToLine, target ) {
  28469. const t = this.closestPointToPointParameter( point, clampToLine );
  28470. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28471. }
  28472. /**
  28473. * Applies a 4x4 transformation matrix to this line segment.
  28474. *
  28475. * @param {Matrix4} matrix - The transformation matrix.
  28476. * @return {Line3} A reference to this line segment.
  28477. */
  28478. applyMatrix4( matrix ) {
  28479. this.start.applyMatrix4( matrix );
  28480. this.end.applyMatrix4( matrix );
  28481. return this;
  28482. }
  28483. /**
  28484. * Returns `true` if this line segment is equal with the given one.
  28485. *
  28486. * @param {Line3} line - The line segment to test for equality.
  28487. * @return {boolean} Whether this line segment is equal with the given one.
  28488. */
  28489. equals( line ) {
  28490. return line.start.equals( this.start ) && line.end.equals( this.end );
  28491. }
  28492. /**
  28493. * Returns a new line segment with copied values from this instance.
  28494. *
  28495. * @return {Line3} A clone of this instance.
  28496. */
  28497. clone() {
  28498. return new this.constructor().copy( this );
  28499. }
  28500. }
  28501. const _vector$3 = /*@__PURE__*/ new Vector3();
  28502. /**
  28503. * This displays a cone shaped helper object for a {@link SpotLight}.
  28504. *
  28505. * ```js
  28506. * const spotLight = new THREE.SpotLight( 0xffffff );
  28507. * spotLight.position.set( 10, 10, 10 );
  28508. * scene.add( spotLight );
  28509. *
  28510. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  28511. * scene.add( spotLightHelper );
  28512. * ```
  28513. *
  28514. * @augments Object3D
  28515. */
  28516. class SpotLightHelper extends Object3D {
  28517. /**
  28518. * Constructs a new spot light helper.
  28519. *
  28520. * @param {HemisphereLight} light - The light to be visualized.
  28521. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  28522. * the color of the light.
  28523. */
  28524. constructor( light, color ) {
  28525. super();
  28526. /**
  28527. * The light being visualized.
  28528. *
  28529. * @type {SpotLight}
  28530. */
  28531. this.light = light;
  28532. this.matrixAutoUpdate = false;
  28533. /**
  28534. * The color parameter passed in the constructor.
  28535. * If not set, the helper will take the color of the light.
  28536. *
  28537. * @type {number|Color|string}
  28538. */
  28539. this.color = color;
  28540. this.type = 'SpotLightHelper';
  28541. const geometry = new BufferGeometry();
  28542. const positions = [
  28543. 0, 0, 0, 0, 0, 1,
  28544. 0, 0, 0, 1, 0, 1,
  28545. 0, 0, 0, -1, 0, 1,
  28546. 0, 0, 0, 0, 1, 1,
  28547. 0, 0, 0, 0, -1, 1
  28548. ];
  28549. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28550. const p1 = ( i / l ) * Math.PI * 2;
  28551. const p2 = ( j / l ) * Math.PI * 2;
  28552. positions.push(
  28553. Math.cos( p1 ), Math.sin( p1 ), 1,
  28554. Math.cos( p2 ), Math.sin( p2 ), 1
  28555. );
  28556. }
  28557. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28558. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28559. this.cone = new LineSegments( geometry, material );
  28560. this.add( this.cone );
  28561. this.update();
  28562. }
  28563. /**
  28564. * Frees the GPU-related resources allocated by this instance. Call this
  28565. * method whenever this instance is no longer used in your app.
  28566. */
  28567. dispose() {
  28568. this.cone.geometry.dispose();
  28569. this.cone.material.dispose();
  28570. }
  28571. /**
  28572. * Updates the helper to match the position and direction of the
  28573. * light being visualized.
  28574. */
  28575. update() {
  28576. this.light.updateWorldMatrix( true, false );
  28577. this.light.target.updateWorldMatrix( true, false );
  28578. // update the local matrix based on the parent and light target transforms
  28579. if ( this.parent ) {
  28580. this.parent.updateWorldMatrix( true );
  28581. this.matrix
  28582. .copy( this.parent.matrixWorld )
  28583. .invert()
  28584. .multiply( this.light.matrixWorld );
  28585. } else {
  28586. this.matrix.copy( this.light.matrixWorld );
  28587. }
  28588. this.matrixWorld.copy( this.light.matrixWorld );
  28589. const coneLength = this.light.distance ? this.light.distance : 1000;
  28590. const coneWidth = coneLength * Math.tan( this.light.angle );
  28591. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28592. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28593. this.cone.lookAt( _vector$3 );
  28594. if ( this.color !== undefined ) {
  28595. this.cone.material.color.set( this.color );
  28596. } else {
  28597. this.cone.material.color.copy( this.light.color );
  28598. }
  28599. }
  28600. }
  28601. const _vector$2 = /*@__PURE__*/ new Vector3();
  28602. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28603. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28604. /**
  28605. * A helper object to assist with visualizing a {@link Skeleton}.
  28606. *
  28607. * ```js
  28608. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  28609. * scene.add( helper );
  28610. * ```
  28611. *
  28612. * @augments LineSegments
  28613. */
  28614. class SkeletonHelper extends LineSegments {
  28615. /**
  28616. * Constructs a new hemisphere light helper.
  28617. *
  28618. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  28619. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  28620. */
  28621. constructor( object ) {
  28622. const bones = getBoneList( object );
  28623. const geometry = new BufferGeometry();
  28624. const vertices = [];
  28625. const colors = [];
  28626. const color1 = new Color( 0, 0, 1 );
  28627. const color2 = new Color( 0, 1, 0 );
  28628. for ( let i = 0; i < bones.length; i ++ ) {
  28629. const bone = bones[ i ];
  28630. if ( bone.parent && bone.parent.isBone ) {
  28631. vertices.push( 0, 0, 0 );
  28632. vertices.push( 0, 0, 0 );
  28633. colors.push( color1.r, color1.g, color1.b );
  28634. colors.push( color2.r, color2.g, color2.b );
  28635. }
  28636. }
  28637. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28638. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28639. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28640. super( geometry, material );
  28641. /**
  28642. * This flag can be used for type testing.
  28643. *
  28644. * @type {boolean}
  28645. * @readonly
  28646. * @default true
  28647. */
  28648. this.isSkeletonHelper = true;
  28649. this.type = 'SkeletonHelper';
  28650. /**
  28651. * The object being visualized.
  28652. *
  28653. * @type {Object3D}
  28654. */
  28655. this.root = object;
  28656. /**
  28657. * he list of bones that the helper visualizes.
  28658. *
  28659. * @type {Array<Bone>}
  28660. */
  28661. this.bones = bones;
  28662. this.matrix = object.matrixWorld;
  28663. this.matrixAutoUpdate = false;
  28664. }
  28665. updateMatrixWorld( force ) {
  28666. const bones = this.bones;
  28667. const geometry = this.geometry;
  28668. const position = geometry.getAttribute( 'position' );
  28669. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28670. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28671. const bone = bones[ i ];
  28672. if ( bone.parent && bone.parent.isBone ) {
  28673. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28674. _vector$2.setFromMatrixPosition( _boneMatrix );
  28675. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28676. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28677. _vector$2.setFromMatrixPosition( _boneMatrix );
  28678. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28679. j += 2;
  28680. }
  28681. }
  28682. geometry.getAttribute( 'position' ).needsUpdate = true;
  28683. super.updateMatrixWorld( force );
  28684. }
  28685. /**
  28686. * Frees the GPU-related resources allocated by this instance. Call this
  28687. * method whenever this instance is no longer used in your app.
  28688. */
  28689. dispose() {
  28690. this.geometry.dispose();
  28691. this.material.dispose();
  28692. }
  28693. }
  28694. function getBoneList( object ) {
  28695. const boneList = [];
  28696. if ( object.isBone === true ) {
  28697. boneList.push( object );
  28698. }
  28699. for ( let i = 0; i < object.children.length; i ++ ) {
  28700. boneList.push( ...getBoneList( object.children[ i ] ) );
  28701. }
  28702. return boneList;
  28703. }
  28704. /**
  28705. * This displays a helper object consisting of a spherical mesh for
  28706. * visualizing an instance of {@link PointLight}.
  28707. *
  28708. * ```js
  28709. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  28710. * pointLight.position.set( 10, 10, 10 );
  28711. * scene.add( pointLight );
  28712. *
  28713. * const sphereSize = 1;
  28714. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  28715. * scene.add( pointLightHelper );
  28716. * ```
  28717. *
  28718. * @augments Mesh
  28719. */
  28720. class PointLightHelper extends Mesh {
  28721. /**
  28722. * Constructs a new point light helper.
  28723. *
  28724. * @param {PointLight} light - The light to be visualized.
  28725. * @param {number} [sphereSize=1] - The size of the sphere helper.
  28726. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  28727. * the color of the light.
  28728. */
  28729. constructor( light, sphereSize, color ) {
  28730. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28731. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28732. super( geometry, material );
  28733. /**
  28734. * The light being visualized.
  28735. *
  28736. * @type {HemisphereLight}
  28737. */
  28738. this.light = light;
  28739. /**
  28740. * The color parameter passed in the constructor.
  28741. * If not set, the helper will take the color of the light.
  28742. *
  28743. * @type {number|Color|string}
  28744. */
  28745. this.color = color;
  28746. this.type = 'PointLightHelper';
  28747. this.matrix = this.light.matrixWorld;
  28748. this.matrixAutoUpdate = false;
  28749. this.update();
  28750. /*
  28751. // TODO: delete this comment?
  28752. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28753. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28754. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28755. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28756. const d = light.distance;
  28757. if ( d === 0.0 ) {
  28758. this.lightDistance.visible = false;
  28759. } else {
  28760. this.lightDistance.scale.set( d, d, d );
  28761. }
  28762. this.add( this.lightDistance );
  28763. */
  28764. }
  28765. /**
  28766. * Frees the GPU-related resources allocated by this instance. Call this
  28767. * method whenever this instance is no longer used in your app.
  28768. */
  28769. dispose() {
  28770. this.geometry.dispose();
  28771. this.material.dispose();
  28772. }
  28773. /**
  28774. * Updates the helper to match the position of the
  28775. * light being visualized.
  28776. */
  28777. update() {
  28778. this.light.updateWorldMatrix( true, false );
  28779. if ( this.color !== undefined ) {
  28780. this.material.color.set( this.color );
  28781. } else {
  28782. this.material.color.copy( this.light.color );
  28783. }
  28784. /*
  28785. const d = this.light.distance;
  28786. if ( d === 0.0 ) {
  28787. this.lightDistance.visible = false;
  28788. } else {
  28789. this.lightDistance.visible = true;
  28790. this.lightDistance.scale.set( d, d, d );
  28791. }
  28792. */
  28793. }
  28794. }
  28795. const _vector$1 = /*@__PURE__*/ new Vector3();
  28796. const _color1 = /*@__PURE__*/ new Color();
  28797. const _color2 = /*@__PURE__*/ new Color();
  28798. /**
  28799. * Creates a visual aid consisting of a spherical mesh for a
  28800. * given {@link HemisphereLight}.
  28801. *
  28802. * ```js
  28803. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  28804. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  28805. * scene.add( helper );
  28806. * ```
  28807. *
  28808. * @augments Object3D
  28809. */
  28810. class HemisphereLightHelper extends Object3D {
  28811. /**
  28812. * Constructs a new hemisphere light helper.
  28813. *
  28814. * @param {HemisphereLight} light - The light to be visualized.
  28815. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  28816. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  28817. * the color of the light.
  28818. */
  28819. constructor( light, size, color ) {
  28820. super();
  28821. /**
  28822. * The light being visualized.
  28823. *
  28824. * @type {HemisphereLight}
  28825. */
  28826. this.light = light;
  28827. this.matrix = light.matrixWorld;
  28828. this.matrixAutoUpdate = false;
  28829. /**
  28830. * The color parameter passed in the constructor.
  28831. * If not set, the helper will take the color of the light.
  28832. *
  28833. * @type {number|Color|string}
  28834. */
  28835. this.color = color;
  28836. this.type = 'HemisphereLightHelper';
  28837. const geometry = new OctahedronGeometry( size );
  28838. geometry.rotateY( Math.PI * 0.5 );
  28839. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28840. if ( this.color === undefined ) this.material.vertexColors = true;
  28841. const position = geometry.getAttribute( 'position' );
  28842. const colors = new Float32Array( position.count * 3 );
  28843. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28844. this.add( new Mesh( geometry, this.material ) );
  28845. this.update();
  28846. }
  28847. /**
  28848. * Frees the GPU-related resources allocated by this instance. Call this
  28849. * method whenever this instance is no longer used in your app.
  28850. */
  28851. dispose() {
  28852. this.children[ 0 ].geometry.dispose();
  28853. this.children[ 0 ].material.dispose();
  28854. }
  28855. /**
  28856. * Updates the helper to match the position and direction of the
  28857. * light being visualized.
  28858. */
  28859. update() {
  28860. const mesh = this.children[ 0 ];
  28861. if ( this.color !== undefined ) {
  28862. this.material.color.set( this.color );
  28863. } else {
  28864. const colors = mesh.geometry.getAttribute( 'color' );
  28865. _color1.copy( this.light.color );
  28866. _color2.copy( this.light.groundColor );
  28867. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28868. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28869. colors.setXYZ( i, color.r, color.g, color.b );
  28870. }
  28871. colors.needsUpdate = true;
  28872. }
  28873. this.light.updateWorldMatrix( true, false );
  28874. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28875. }
  28876. }
  28877. /**
  28878. * The helper is an object to define grids. Grids are two-dimensional
  28879. * arrays of lines.
  28880. *
  28881. * ```js
  28882. * const size = 10;
  28883. * const divisions = 10;
  28884. *
  28885. * const gridHelper = new THREE.GridHelper( size, divisions );
  28886. * scene.add( gridHelper );
  28887. * ```
  28888. *
  28889. * @augments LineSegments
  28890. */
  28891. class GridHelper extends LineSegments {
  28892. /**
  28893. * Constructs a new grid helper.
  28894. *
  28895. * @param {number} [size=10] - The size of the grid.
  28896. * @param {number} [divisions=10] - The number of divisions across the grid.
  28897. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  28898. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  28899. */
  28900. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28901. color1 = new Color( color1 );
  28902. color2 = new Color( color2 );
  28903. const center = divisions / 2;
  28904. const step = size / divisions;
  28905. const halfSize = size / 2;
  28906. const vertices = [], colors = [];
  28907. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28908. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28909. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28910. const color = i === center ? color1 : color2;
  28911. color.toArray( colors, j ); j += 3;
  28912. color.toArray( colors, j ); j += 3;
  28913. color.toArray( colors, j ); j += 3;
  28914. color.toArray( colors, j ); j += 3;
  28915. }
  28916. const geometry = new BufferGeometry();
  28917. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28918. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28919. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28920. super( geometry, material );
  28921. this.type = 'GridHelper';
  28922. }
  28923. /**
  28924. * Frees the GPU-related resources allocated by this instance. Call this
  28925. * method whenever this instance is no longer used in your app.
  28926. */
  28927. dispose() {
  28928. this.geometry.dispose();
  28929. this.material.dispose();
  28930. }
  28931. }
  28932. /**
  28933. * This helper is an object to define polar grids. Grids are
  28934. * two-dimensional arrays of lines.
  28935. *
  28936. * ```js
  28937. * const radius = 10;
  28938. * const sectors = 16;
  28939. * const rings = 8;
  28940. * const divisions = 64;
  28941. *
  28942. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  28943. * scene.add( helper );
  28944. * ```
  28945. *
  28946. * @augments LineSegments
  28947. */
  28948. class PolarGridHelper extends LineSegments {
  28949. /**
  28950. * Constructs a new polar grid helper.
  28951. *
  28952. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  28953. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  28954. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  28955. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  28956. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  28957. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  28958. */
  28959. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28960. color1 = new Color( color1 );
  28961. color2 = new Color( color2 );
  28962. const vertices = [];
  28963. const colors = [];
  28964. // create the sectors
  28965. if ( sectors > 1 ) {
  28966. for ( let i = 0; i < sectors; i ++ ) {
  28967. const v = ( i / sectors ) * ( Math.PI * 2 );
  28968. const x = Math.sin( v ) * radius;
  28969. const z = Math.cos( v ) * radius;
  28970. vertices.push( 0, 0, 0 );
  28971. vertices.push( x, 0, z );
  28972. const color = ( i & 1 ) ? color1 : color2;
  28973. colors.push( color.r, color.g, color.b );
  28974. colors.push( color.r, color.g, color.b );
  28975. }
  28976. }
  28977. // create the rings
  28978. for ( let i = 0; i < rings; i ++ ) {
  28979. const color = ( i & 1 ) ? color1 : color2;
  28980. const r = radius - ( radius / rings * i );
  28981. for ( let j = 0; j < divisions; j ++ ) {
  28982. // first vertex
  28983. let v = ( j / divisions ) * ( Math.PI * 2 );
  28984. let x = Math.sin( v ) * r;
  28985. let z = Math.cos( v ) * r;
  28986. vertices.push( x, 0, z );
  28987. colors.push( color.r, color.g, color.b );
  28988. // second vertex
  28989. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28990. x = Math.sin( v ) * r;
  28991. z = Math.cos( v ) * r;
  28992. vertices.push( x, 0, z );
  28993. colors.push( color.r, color.g, color.b );
  28994. }
  28995. }
  28996. const geometry = new BufferGeometry();
  28997. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28998. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28999. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29000. super( geometry, material );
  29001. this.type = 'PolarGridHelper';
  29002. }
  29003. /**
  29004. * Frees the GPU-related resources allocated by this instance. Call this
  29005. * method whenever this instance is no longer used in your app.
  29006. */
  29007. dispose() {
  29008. this.geometry.dispose();
  29009. this.material.dispose();
  29010. }
  29011. }
  29012. const _v1 = /*@__PURE__*/ new Vector3();
  29013. const _v2 = /*@__PURE__*/ new Vector3();
  29014. const _v3 = /*@__PURE__*/ new Vector3();
  29015. /**
  29016. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  29017. * effect on the scene. This consists of plane and a line representing the
  29018. * light's position and direction.
  29019. *
  29020. * ```js
  29021. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  29022. * scene.add( light );
  29023. *
  29024. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  29025. * scene.add( helper );
  29026. * ```
  29027. *
  29028. * @augments Object3D
  29029. */
  29030. class DirectionalLightHelper extends Object3D {
  29031. /**
  29032. * Constructs a new directional light helper.
  29033. *
  29034. * @param {DirectionalLight} light - The light to be visualized.
  29035. * @param {number} [size=1] - The dimensions of the plane.
  29036. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  29037. * the color of the light.
  29038. */
  29039. constructor( light, size, color ) {
  29040. super();
  29041. /**
  29042. * The light being visualized.
  29043. *
  29044. * @type {DirectionalLight}
  29045. */
  29046. this.light = light;
  29047. this.matrix = light.matrixWorld;
  29048. this.matrixAutoUpdate = false;
  29049. /**
  29050. * The color parameter passed in the constructor.
  29051. * If not set, the helper will take the color of the light.
  29052. *
  29053. * @type {number|Color|string}
  29054. */
  29055. this.color = color;
  29056. this.type = 'DirectionalLightHelper';
  29057. if ( size === undefined ) size = 1;
  29058. let geometry = new BufferGeometry();
  29059. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29060. - size, size, 0,
  29061. size, size, 0,
  29062. size, - size, 0,
  29063. - size, - size, 0,
  29064. - size, size, 0
  29065. ], 3 ) );
  29066. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29067. /**
  29068. * Contains the line showing the location of the directional light.
  29069. *
  29070. * @type {Line}
  29071. */
  29072. this.lightPlane = new Line( geometry, material );
  29073. this.add( this.lightPlane );
  29074. geometry = new BufferGeometry();
  29075. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29076. /**
  29077. * Represents the target line of the directional light.
  29078. *
  29079. * @type {Line}
  29080. */
  29081. this.targetLine = new Line( geometry, material );
  29082. this.add( this.targetLine );
  29083. this.update();
  29084. }
  29085. /**
  29086. * Frees the GPU-related resources allocated by this instance. Call this
  29087. * method whenever this instance is no longer used in your app.
  29088. */
  29089. dispose() {
  29090. this.lightPlane.geometry.dispose();
  29091. this.lightPlane.material.dispose();
  29092. this.targetLine.geometry.dispose();
  29093. this.targetLine.material.dispose();
  29094. }
  29095. /**
  29096. * Updates the helper to match the position and direction of the
  29097. * light being visualized.
  29098. */
  29099. update() {
  29100. this.light.updateWorldMatrix( true, false );
  29101. this.light.target.updateWorldMatrix( true, false );
  29102. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29103. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29104. _v3.subVectors( _v2, _v1 );
  29105. this.lightPlane.lookAt( _v2 );
  29106. if ( this.color !== undefined ) {
  29107. this.lightPlane.material.color.set( this.color );
  29108. this.targetLine.material.color.set( this.color );
  29109. } else {
  29110. this.lightPlane.material.color.copy( this.light.color );
  29111. this.targetLine.material.color.copy( this.light.color );
  29112. }
  29113. this.targetLine.lookAt( _v2 );
  29114. this.targetLine.scale.z = _v3.length();
  29115. }
  29116. }
  29117. const _vector = /*@__PURE__*/ new Vector3();
  29118. const _camera = /*@__PURE__*/ new Camera();
  29119. /**
  29120. * This helps with visualizing what a camera contains in its frustum. It
  29121. * visualizes the frustum of a camera using a line segments.
  29122. *
  29123. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  29124. *
  29125. * `CameraHelper` must be a child of the scene.
  29126. *
  29127. * ```js
  29128. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  29129. * const helper = new THREE.CameraHelper( camera );
  29130. * scene.add( helper );
  29131. * ```
  29132. *
  29133. * @augments LineSegments
  29134. */
  29135. class CameraHelper extends LineSegments {
  29136. /**
  29137. * Constructs a new arror helper.
  29138. *
  29139. * @param {Camera} camera - The camera to visualize.
  29140. */
  29141. constructor( camera ) {
  29142. const geometry = new BufferGeometry();
  29143. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29144. const vertices = [];
  29145. const colors = [];
  29146. const pointMap = {};
  29147. // near
  29148. addLine( 'n1', 'n2' );
  29149. addLine( 'n2', 'n4' );
  29150. addLine( 'n4', 'n3' );
  29151. addLine( 'n3', 'n1' );
  29152. // far
  29153. addLine( 'f1', 'f2' );
  29154. addLine( 'f2', 'f4' );
  29155. addLine( 'f4', 'f3' );
  29156. addLine( 'f3', 'f1' );
  29157. // sides
  29158. addLine( 'n1', 'f1' );
  29159. addLine( 'n2', 'f2' );
  29160. addLine( 'n3', 'f3' );
  29161. addLine( 'n4', 'f4' );
  29162. // cone
  29163. addLine( 'p', 'n1' );
  29164. addLine( 'p', 'n2' );
  29165. addLine( 'p', 'n3' );
  29166. addLine( 'p', 'n4' );
  29167. // up
  29168. addLine( 'u1', 'u2' );
  29169. addLine( 'u2', 'u3' );
  29170. addLine( 'u3', 'u1' );
  29171. // target
  29172. addLine( 'c', 't' );
  29173. addLine( 'p', 'c' );
  29174. // cross
  29175. addLine( 'cn1', 'cn2' );
  29176. addLine( 'cn3', 'cn4' );
  29177. addLine( 'cf1', 'cf2' );
  29178. addLine( 'cf3', 'cf4' );
  29179. function addLine( a, b ) {
  29180. addPoint( a );
  29181. addPoint( b );
  29182. }
  29183. function addPoint( id ) {
  29184. vertices.push( 0, 0, 0 );
  29185. colors.push( 0, 0, 0 );
  29186. if ( pointMap[ id ] === undefined ) {
  29187. pointMap[ id ] = [];
  29188. }
  29189. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29190. }
  29191. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29192. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29193. super( geometry, material );
  29194. this.type = 'CameraHelper';
  29195. /**
  29196. * The camera being visualized.
  29197. *
  29198. * @type {Camera}
  29199. */
  29200. this.camera = camera;
  29201. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29202. this.matrix = camera.matrixWorld;
  29203. this.matrixAutoUpdate = false;
  29204. /**
  29205. * This contains the points used to visualize the camera.
  29206. *
  29207. * @type {Object<string,Array<number>>}
  29208. */
  29209. this.pointMap = pointMap;
  29210. this.update();
  29211. // colors
  29212. const colorFrustum = new Color( 0xffaa00 );
  29213. const colorCone = new Color( 0xff0000 );
  29214. const colorUp = new Color( 0x00aaff );
  29215. const colorTarget = new Color( 0xffffff );
  29216. const colorCross = new Color( 0x333333 );
  29217. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29218. }
  29219. /**
  29220. * Defines the colors of the helper.
  29221. *
  29222. * @param {Color} frustum - The frustum line color.
  29223. * @param {Color} cone - The cone line color.
  29224. * @param {Color} up - The up line color.
  29225. * @param {Color} target - The target line color.
  29226. * @param {Color} cross - The cross line color.
  29227. */
  29228. setColors( frustum, cone, up, target, cross ) {
  29229. const geometry = this.geometry;
  29230. const colorAttribute = geometry.getAttribute( 'color' );
  29231. // near
  29232. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29233. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29234. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29235. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29236. // far
  29237. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29238. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29239. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29240. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29241. // sides
  29242. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29243. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29244. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29245. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29246. // cone
  29247. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29248. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29249. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29250. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29251. // up
  29252. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29253. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29254. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29255. // target
  29256. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29257. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29258. // cross
  29259. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29260. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29261. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29262. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29263. colorAttribute.needsUpdate = true;
  29264. }
  29265. /**
  29266. * Updates the helper based on the projection matrix of the camera.
  29267. */
  29268. update() {
  29269. const geometry = this.geometry;
  29270. const pointMap = this.pointMap;
  29271. const w = 1, h = 1;
  29272. // we need just camera projection matrix inverse
  29273. // world matrix must be identity
  29274. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29275. // Adjust z values based on coordinate system
  29276. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  29277. // center / target
  29278. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  29279. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29280. // near
  29281. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  29282. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  29283. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  29284. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  29285. // far
  29286. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  29287. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  29288. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  29289. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29290. // up
  29291. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  29292. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  29293. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  29294. // cross
  29295. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  29296. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29297. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  29298. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29299. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  29300. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  29301. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  29302. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  29303. geometry.getAttribute( 'position' ).needsUpdate = true;
  29304. }
  29305. /**
  29306. * Frees the GPU-related resources allocated by this instance. Call this
  29307. * method whenever this instance is no longer used in your app.
  29308. */
  29309. dispose() {
  29310. this.geometry.dispose();
  29311. this.material.dispose();
  29312. }
  29313. }
  29314. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29315. _vector.set( x, y, z ).unproject( camera );
  29316. const points = pointMap[ point ];
  29317. if ( points !== undefined ) {
  29318. const position = geometry.getAttribute( 'position' );
  29319. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29320. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29321. }
  29322. }
  29323. }
  29324. const _box = /*@__PURE__*/ new Box3();
  29325. /**
  29326. * Helper object to graphically show the world-axis-aligned bounding box
  29327. * around an object. The actual bounding box is handled with {@link Box3},
  29328. * this is just a visual helper for debugging. It can be automatically
  29329. * resized with {@link BoxHelper#update} when the object it's created from
  29330. * is transformed. Note that the object must have a geometry for this to work,
  29331. * so it won't work with sprites.
  29332. *
  29333. * ```js
  29334. * const sphere = new THREE.SphereGeometry();
  29335. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  29336. * const box = new THREE.BoxHelper( object, 0xffff00 );
  29337. * scene.add( box );
  29338. * ```
  29339. *
  29340. * @augments LineSegments
  29341. */
  29342. class BoxHelper extends LineSegments {
  29343. /**
  29344. * Constructs a new box helper.
  29345. *
  29346. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  29347. * @param {number|Color|string} [color=0xffff00] - The box's color.
  29348. */
  29349. constructor( object, color = 0xffff00 ) {
  29350. 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 ] );
  29351. const positions = new Float32Array( 8 * 3 );
  29352. const geometry = new BufferGeometry();
  29353. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29354. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29355. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29356. /**
  29357. * The 3D object being visualized.
  29358. *
  29359. * @type {Object3D}
  29360. */
  29361. this.object = object;
  29362. this.type = 'BoxHelper';
  29363. this.matrixAutoUpdate = false;
  29364. this.update();
  29365. }
  29366. /**
  29367. * Updates the helper's geometry to match the dimensions of the object,
  29368. * including any children.
  29369. */
  29370. update() {
  29371. if ( this.object !== undefined ) {
  29372. _box.setFromObject( this.object );
  29373. }
  29374. if ( _box.isEmpty() ) return;
  29375. const min = _box.min;
  29376. const max = _box.max;
  29377. /*
  29378. 5____4
  29379. 1/___0/|
  29380. | 6__|_7
  29381. 2/___3/
  29382. 0: max.x, max.y, max.z
  29383. 1: min.x, max.y, max.z
  29384. 2: min.x, min.y, max.z
  29385. 3: max.x, min.y, max.z
  29386. 4: max.x, max.y, min.z
  29387. 5: min.x, max.y, min.z
  29388. 6: min.x, min.y, min.z
  29389. 7: max.x, min.y, min.z
  29390. */
  29391. const position = this.geometry.attributes.position;
  29392. const array = position.array;
  29393. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29394. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29395. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29396. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29397. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29398. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29399. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29400. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29401. position.needsUpdate = true;
  29402. this.geometry.computeBoundingSphere();
  29403. }
  29404. /**
  29405. * Updates the wireframe box for the passed object.
  29406. *
  29407. * @param {Object3D} object - The 3D object to create the helper for.
  29408. * @return {BoxHelper} A reference to this instance.
  29409. */
  29410. setFromObject( object ) {
  29411. this.object = object;
  29412. this.update();
  29413. return this;
  29414. }
  29415. copy( source, recursive ) {
  29416. super.copy( source, recursive );
  29417. this.object = source.object;
  29418. return this;
  29419. }
  29420. /**
  29421. * Frees the GPU-related resources allocated by this instance. Call this
  29422. * method whenever this instance is no longer used in your app.
  29423. */
  29424. dispose() {
  29425. this.geometry.dispose();
  29426. this.material.dispose();
  29427. }
  29428. }
  29429. /**
  29430. * A helper object to visualize an instance of {@link Box3}.
  29431. *
  29432. * ```js
  29433. * const box = new THREE.Box3();
  29434. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  29435. *
  29436. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  29437. * scene.add( helper )
  29438. * ```
  29439. *
  29440. * @augments LineSegments
  29441. */
  29442. class Box3Helper extends LineSegments {
  29443. /**
  29444. * Constructs a new box3 helper.
  29445. *
  29446. * @param {Box3} box - The box to visualize.
  29447. * @param {number|Color|string} [color=0xffff00] - The box's color.
  29448. */
  29449. constructor( box, color = 0xffff00 ) {
  29450. 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 ] );
  29451. 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 ];
  29452. const geometry = new BufferGeometry();
  29453. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29454. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29455. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29456. /**
  29457. * The box being visualized.
  29458. *
  29459. * @type {Box3}
  29460. */
  29461. this.box = box;
  29462. this.type = 'Box3Helper';
  29463. this.geometry.computeBoundingSphere();
  29464. }
  29465. updateMatrixWorld( force ) {
  29466. const box = this.box;
  29467. if ( box.isEmpty() ) return;
  29468. box.getCenter( this.position );
  29469. box.getSize( this.scale );
  29470. this.scale.multiplyScalar( 0.5 );
  29471. super.updateMatrixWorld( force );
  29472. }
  29473. /**
  29474. * Frees the GPU-related resources allocated by this instance. Call this
  29475. * method whenever this instance is no longer used in your app.
  29476. */
  29477. dispose() {
  29478. this.geometry.dispose();
  29479. this.material.dispose();
  29480. }
  29481. }
  29482. /**
  29483. * A helper object to visualize an instance of {@link Plane}.
  29484. *
  29485. * ```js
  29486. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  29487. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  29488. * scene.add( helper );
  29489. * ```
  29490. *
  29491. * @augments Line
  29492. */
  29493. class PlaneHelper extends Line {
  29494. /**
  29495. * Constructs a new plane helper.
  29496. *
  29497. * @param {Plane} plane - The plane to be visualized.
  29498. * @param {number} [size=1] - The side length of plane helper.
  29499. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  29500. */
  29501. constructor( plane, size = 1, hex = 0xffff00 ) {
  29502. const color = hex;
  29503. 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 ];
  29504. const geometry = new BufferGeometry();
  29505. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29506. geometry.computeBoundingSphere();
  29507. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29508. this.type = 'PlaneHelper';
  29509. /**
  29510. * The plane being visualized.
  29511. *
  29512. * @type {Plane}
  29513. */
  29514. this.plane = plane;
  29515. /**
  29516. * The side length of plane helper.
  29517. *
  29518. * @type {number}
  29519. * @default 1
  29520. */
  29521. this.size = size;
  29522. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  29523. const geometry2 = new BufferGeometry();
  29524. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29525. geometry2.computeBoundingSphere();
  29526. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29527. }
  29528. updateMatrixWorld( force ) {
  29529. this.position.set( 0, 0, 0 );
  29530. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29531. this.lookAt( this.plane.normal );
  29532. this.translateZ( - this.plane.constant );
  29533. super.updateMatrixWorld( force );
  29534. }
  29535. /**
  29536. * Updates the helper to match the position and direction of the
  29537. * light being visualized.
  29538. */
  29539. dispose() {
  29540. this.geometry.dispose();
  29541. this.material.dispose();
  29542. this.children[ 0 ].geometry.dispose();
  29543. this.children[ 0 ].material.dispose();
  29544. }
  29545. }
  29546. const _axis = /*@__PURE__*/ new Vector3();
  29547. let _lineGeometry, _coneGeometry;
  29548. /**
  29549. * An 3D arrow object for visualizing directions.
  29550. *
  29551. * ```js
  29552. * const dir = new THREE.Vector3( 1, 2, 0 );
  29553. *
  29554. * //normalize the direction vector (convert to vector of length 1)
  29555. * dir.normalize();
  29556. *
  29557. * const origin = new THREE.Vector3( 0, 0, 0 );
  29558. * const length = 1;
  29559. * const hex = 0xffff00;
  29560. *
  29561. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  29562. * scene.add( arrowHelper );
  29563. * ```
  29564. *
  29565. * @augments Object3D
  29566. */
  29567. class ArrowHelper extends Object3D {
  29568. /**
  29569. * Constructs a new arror helper.
  29570. *
  29571. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  29572. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  29573. * @param {number} [length=1] - Length of the arrow in world units.
  29574. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  29575. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  29576. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  29577. */
  29578. 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 ) {
  29579. super();
  29580. this.type = 'ArrowHelper';
  29581. if ( _lineGeometry === undefined ) {
  29582. _lineGeometry = new BufferGeometry();
  29583. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29584. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29585. _coneGeometry.translate( 0, -0.5, 0 );
  29586. }
  29587. this.position.copy( origin );
  29588. /**
  29589. * The line part of the arrow helper.
  29590. *
  29591. * @type {Line}
  29592. */
  29593. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29594. this.line.matrixAutoUpdate = false;
  29595. this.add( this.line );
  29596. /**
  29597. * The cone part of the arrow helper.
  29598. *
  29599. * @type {Mesh}
  29600. */
  29601. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29602. this.cone.matrixAutoUpdate = false;
  29603. this.add( this.cone );
  29604. this.setDirection( dir );
  29605. this.setLength( length, headLength, headWidth );
  29606. }
  29607. /**
  29608. * Sets the direction of the helper.
  29609. *
  29610. * @param {Vector3} dir - The normalized direction vector.
  29611. */
  29612. setDirection( dir ) {
  29613. // dir is assumed to be normalized
  29614. if ( dir.y > 0.99999 ) {
  29615. this.quaternion.set( 0, 0, 0, 1 );
  29616. } else if ( dir.y < -0.99999 ) {
  29617. this.quaternion.set( 1, 0, 0, 0 );
  29618. } else {
  29619. _axis.set( dir.z, 0, - dir.x ).normalize();
  29620. const radians = Math.acos( dir.y );
  29621. this.quaternion.setFromAxisAngle( _axis, radians );
  29622. }
  29623. }
  29624. /**
  29625. * Sets the length of the helper.
  29626. *
  29627. * @param {number} length - Length of the arrow in world units.
  29628. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  29629. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  29630. */
  29631. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29632. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29633. this.line.updateMatrix();
  29634. this.cone.scale.set( headWidth, headLength, headWidth );
  29635. this.cone.position.y = length;
  29636. this.cone.updateMatrix();
  29637. }
  29638. /**
  29639. * Sets the color of the helper.
  29640. *
  29641. * @param {number|Color|string} color - The color to set.
  29642. */
  29643. setColor( color ) {
  29644. this.line.material.color.set( color );
  29645. this.cone.material.color.set( color );
  29646. }
  29647. copy( source ) {
  29648. super.copy( source, false );
  29649. this.line.copy( source.line );
  29650. this.cone.copy( source.cone );
  29651. return this;
  29652. }
  29653. /**
  29654. * Frees the GPU-related resources allocated by this instance. Call this
  29655. * method whenever this instance is no longer used in your app.
  29656. */
  29657. dispose() {
  29658. this.line.geometry.dispose();
  29659. this.line.material.dispose();
  29660. this.cone.geometry.dispose();
  29661. this.cone.material.dispose();
  29662. }
  29663. }
  29664. /**
  29665. * An axis object to visualize the 3 axes in a simple way.
  29666. * The X axis is red. The Y axis is green. The Z axis is blue.
  29667. *
  29668. * ```js
  29669. * const axesHelper = new THREE.AxesHelper( 5 );
  29670. * scene.add( axesHelper );
  29671. * ```
  29672. *
  29673. * @augments LineSegments
  29674. */
  29675. class AxesHelper extends LineSegments {
  29676. /**
  29677. * Constructs a new axes helper.
  29678. *
  29679. * @param {number} [size=1] - Size of the lines representing the axes.
  29680. */
  29681. constructor( size = 1 ) {
  29682. const vertices = [
  29683. 0, 0, 0, size, 0, 0,
  29684. 0, 0, 0, 0, size, 0,
  29685. 0, 0, 0, 0, 0, size
  29686. ];
  29687. const colors = [
  29688. 1, 0, 0, 1, 0.6, 0,
  29689. 0, 1, 0, 0.6, 1, 0,
  29690. 0, 0, 1, 0, 0.6, 1
  29691. ];
  29692. const geometry = new BufferGeometry();
  29693. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29694. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29695. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29696. super( geometry, material );
  29697. this.type = 'AxesHelper';
  29698. }
  29699. /**
  29700. * Defines the colors of the axes helper.
  29701. *
  29702. * @param {number|Color|string} xAxisColor - The color for the x axis.
  29703. * @param {number|Color|string} yAxisColor - The color for the y axis.
  29704. * @param {number|Color|string} zAxisColor - The color for the z axis.
  29705. * @return {AxesHelper} A reference to this axes helper.
  29706. */
  29707. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29708. const color = new Color();
  29709. const array = this.geometry.attributes.color.array;
  29710. color.set( xAxisColor );
  29711. color.toArray( array, 0 );
  29712. color.toArray( array, 3 );
  29713. color.set( yAxisColor );
  29714. color.toArray( array, 6 );
  29715. color.toArray( array, 9 );
  29716. color.set( zAxisColor );
  29717. color.toArray( array, 12 );
  29718. color.toArray( array, 15 );
  29719. this.geometry.attributes.color.needsUpdate = true;
  29720. return this;
  29721. }
  29722. /**
  29723. * Frees the GPU-related resources allocated by this instance. Call this
  29724. * method whenever this instance is no longer used in your app.
  29725. */
  29726. dispose() {
  29727. this.geometry.dispose();
  29728. this.material.dispose();
  29729. }
  29730. }
  29731. /**
  29732. * This class is used to convert a series of paths to an array of
  29733. * shapes. It is specifically used in context of fonts and SVG.
  29734. */
  29735. class ShapePath {
  29736. /**
  29737. * Constructs a new shape path.
  29738. */
  29739. constructor() {
  29740. this.type = 'ShapePath';
  29741. /**
  29742. * The color of the shape.
  29743. *
  29744. * @type {Color}
  29745. */
  29746. this.color = new Color();
  29747. /**
  29748. * The paths that have been generated for this shape.
  29749. *
  29750. * @type {Array<Path>}
  29751. * @default null
  29752. */
  29753. this.subPaths = [];
  29754. /**
  29755. * The current path that is being generated.
  29756. *
  29757. * @type {?Path}
  29758. * @default null
  29759. */
  29760. this.currentPath = null;
  29761. }
  29762. /**
  29763. * Creates a new path and moves it current point to the given one.
  29764. *
  29765. * @param {number} x - The x coordinate.
  29766. * @param {number} y - The y coordinate.
  29767. * @return {ShapePath} A reference to this shape path.
  29768. */
  29769. moveTo( x, y ) {
  29770. this.currentPath = new Path();
  29771. this.subPaths.push( this.currentPath );
  29772. this.currentPath.moveTo( x, y );
  29773. return this;
  29774. }
  29775. /**
  29776. * Adds an instance of {@link LineCurve} to the path by connecting
  29777. * the current point with the given one.
  29778. *
  29779. * @param {number} x - The x coordinate of the end point.
  29780. * @param {number} y - The y coordinate of the end point.
  29781. * @return {ShapePath} A reference to this shape path.
  29782. */
  29783. lineTo( x, y ) {
  29784. this.currentPath.lineTo( x, y );
  29785. return this;
  29786. }
  29787. /**
  29788. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  29789. * the current point with the given one.
  29790. *
  29791. * @param {number} aCPx - The x coordinate of the control point.
  29792. * @param {number} aCPy - The y coordinate of the control point.
  29793. * @param {number} aX - The x coordinate of the end point.
  29794. * @param {number} aY - The y coordinate of the end point.
  29795. * @return {ShapePath} A reference to this shape path.
  29796. */
  29797. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29798. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29799. return this;
  29800. }
  29801. /**
  29802. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  29803. * the current point with the given one.
  29804. *
  29805. * @param {number} aCP1x - The x coordinate of the first control point.
  29806. * @param {number} aCP1y - The y coordinate of the first control point.
  29807. * @param {number} aCP2x - The x coordinate of the second control point.
  29808. * @param {number} aCP2y - The y coordinate of the second control point.
  29809. * @param {number} aX - The x coordinate of the end point.
  29810. * @param {number} aY - The y coordinate of the end point.
  29811. * @return {ShapePath} A reference to this shape path.
  29812. */
  29813. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29814. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29815. return this;
  29816. }
  29817. /**
  29818. * Adds an instance of {@link SplineCurve} to the path by connecting
  29819. * the current point with the given list of points.
  29820. *
  29821. * @param {Array<Vector2>} pts - An array of points in 2D space.
  29822. * @return {ShapePath} A reference to this shape path.
  29823. */
  29824. splineThru( pts ) {
  29825. this.currentPath.splineThru( pts );
  29826. return this;
  29827. }
  29828. /**
  29829. * Converts the paths into an array of shapes.
  29830. *
  29831. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  29832. * If this flag is set to `true`, then those are flipped.
  29833. * @return {Array<Shape>} An array of shapes.
  29834. */
  29835. toShapes( isCCW ) {
  29836. function toShapesNoHoles( inSubpaths ) {
  29837. const shapes = [];
  29838. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29839. const tmpPath = inSubpaths[ i ];
  29840. const tmpShape = new Shape();
  29841. tmpShape.curves = tmpPath.curves;
  29842. shapes.push( tmpShape );
  29843. }
  29844. return shapes;
  29845. }
  29846. function isPointInsidePolygon( inPt, inPolygon ) {
  29847. const polyLen = inPolygon.length;
  29848. // inPt on polygon contour => immediate success or
  29849. // toggling of inside/outside at every single! intersection point of an edge
  29850. // with the horizontal line through inPt, left of inPt
  29851. // not counting lowerY endpoints of edges and whole edges on that line
  29852. let inside = false;
  29853. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29854. let edgeLowPt = inPolygon[ p ];
  29855. let edgeHighPt = inPolygon[ q ];
  29856. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29857. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29858. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29859. // not parallel
  29860. if ( edgeDy < 0 ) {
  29861. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29862. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29863. }
  29864. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29865. if ( inPt.y === edgeLowPt.y ) {
  29866. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29867. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29868. } else {
  29869. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29870. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29871. if ( perpEdge < 0 ) continue;
  29872. inside = ! inside; // true intersection left of inPt
  29873. }
  29874. } else {
  29875. // parallel or collinear
  29876. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29877. // edge lies on the same horizontal line as inPt
  29878. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29879. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29880. // continue;
  29881. }
  29882. }
  29883. return inside;
  29884. }
  29885. const isClockWise = ShapeUtils.isClockWise;
  29886. const subPaths = this.subPaths;
  29887. if ( subPaths.length === 0 ) return [];
  29888. let solid, tmpPath, tmpShape;
  29889. const shapes = [];
  29890. if ( subPaths.length === 1 ) {
  29891. tmpPath = subPaths[ 0 ];
  29892. tmpShape = new Shape();
  29893. tmpShape.curves = tmpPath.curves;
  29894. shapes.push( tmpShape );
  29895. return shapes;
  29896. }
  29897. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29898. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29899. // console.log("Holes first", holesFirst);
  29900. const betterShapeHoles = [];
  29901. const newShapes = [];
  29902. let newShapeHoles = [];
  29903. let mainIdx = 0;
  29904. let tmpPoints;
  29905. newShapes[ mainIdx ] = undefined;
  29906. newShapeHoles[ mainIdx ] = [];
  29907. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29908. tmpPath = subPaths[ i ];
  29909. tmpPoints = tmpPath.getPoints();
  29910. solid = isClockWise( tmpPoints );
  29911. solid = isCCW ? ! solid : solid;
  29912. if ( solid ) {
  29913. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29914. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29915. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29916. if ( holesFirst ) mainIdx ++;
  29917. newShapeHoles[ mainIdx ] = [];
  29918. //console.log('cw', i);
  29919. } else {
  29920. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29921. //console.log('ccw', i);
  29922. }
  29923. }
  29924. // only Holes? -> probably all Shapes with wrong orientation
  29925. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29926. if ( newShapes.length > 1 ) {
  29927. let ambiguous = false;
  29928. let toChange = 0;
  29929. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29930. betterShapeHoles[ sIdx ] = [];
  29931. }
  29932. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29933. const sho = newShapeHoles[ sIdx ];
  29934. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29935. const ho = sho[ hIdx ];
  29936. let hole_unassigned = true;
  29937. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29938. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29939. if ( sIdx !== s2Idx ) toChange ++;
  29940. if ( hole_unassigned ) {
  29941. hole_unassigned = false;
  29942. betterShapeHoles[ s2Idx ].push( ho );
  29943. } else {
  29944. ambiguous = true;
  29945. }
  29946. }
  29947. }
  29948. if ( hole_unassigned ) {
  29949. betterShapeHoles[ sIdx ].push( ho );
  29950. }
  29951. }
  29952. }
  29953. if ( toChange > 0 && ambiguous === false ) {
  29954. newShapeHoles = betterShapeHoles;
  29955. }
  29956. }
  29957. let tmpHoles;
  29958. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29959. tmpShape = newShapes[ i ].s;
  29960. shapes.push( tmpShape );
  29961. tmpHoles = newShapeHoles[ i ];
  29962. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29963. tmpShape.holes.push( tmpHoles[ j ].h );
  29964. }
  29965. }
  29966. //console.log("shape", shapes);
  29967. return shapes;
  29968. }
  29969. }
  29970. /**
  29971. * Abstract base class for controls.
  29972. *
  29973. * @abstract
  29974. * @augments EventDispatcher
  29975. */
  29976. class Controls extends EventDispatcher {
  29977. /**
  29978. * Constructs a new controls instance.
  29979. *
  29980. * @param {Object3D} object - The object that is managed by the controls.
  29981. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  29982. */
  29983. constructor( object, domElement = null ) {
  29984. super();
  29985. /**
  29986. * The object that is managed by the controls.
  29987. *
  29988. * @type {Object3D}
  29989. */
  29990. this.object = object;
  29991. /**
  29992. * The HTML element used for event listeners.
  29993. *
  29994. * @type {?HTMLDOMElement}
  29995. * @default null
  29996. */
  29997. this.domElement = domElement;
  29998. /**
  29999. * Whether the controls responds to user input or not.
  30000. *
  30001. * @type {boolean}
  30002. * @default true
  30003. */
  30004. this.enabled = true;
  30005. /**
  30006. * The internal state of the controls.
  30007. *
  30008. * @type {number}
  30009. * @default -1
  30010. */
  30011. this.state = -1;
  30012. /**
  30013. * This object defines the keyboard input of the controls.
  30014. *
  30015. * @type {Object}
  30016. */
  30017. this.keys = {};
  30018. /**
  30019. * This object defines what type of actions are assigned to the available mouse buttons.
  30020. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  30021. *
  30022. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  30023. */
  30024. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  30025. /**
  30026. * This object defines what type of actions are assigned to what kind of touch interaction.
  30027. * It depends on the control implementation what kind of touch interaction and actions are supported.
  30028. *
  30029. * @type {{ONE: ?number, TWO: ?number}}
  30030. */
  30031. this.touches = { ONE: null, TWO: null };
  30032. }
  30033. /**
  30034. * Connects the controls to the DOM. This method has so called "side effects" since
  30035. * it adds the module's event listeners to the DOM.
  30036. */
  30037. connect() {}
  30038. /**
  30039. * Disconnects the controls from the DOM.
  30040. */
  30041. disconnect() {}
  30042. /**
  30043. * Call this method if you no longer want use to the controls. It frees all internal
  30044. * resources and removes all event listeners.
  30045. */
  30046. dispose() {}
  30047. /**
  30048. * Controls should implement this method if they have to update their internal state
  30049. * per simulation step.
  30050. *
  30051. * @param {number} [delta] - The time delta in seconds.
  30052. */
  30053. update( /* delta */ ) {}
  30054. }
  30055. /**
  30056. * Scales the texture as large as possible within its surface without cropping
  30057. * or stretching the texture. The method preserves the original aspect ratio of
  30058. * the texture. Akin to CSS `object-fit: contain`
  30059. *
  30060. * @param {Texture} texture - The texture.
  30061. * @param {number} aspect - The texture's aspect ratio.
  30062. * @return {Texture} The updated texture.
  30063. */
  30064. function contain( texture, aspect ) {
  30065. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  30066. if ( imageAspect > aspect ) {
  30067. texture.repeat.x = 1;
  30068. texture.repeat.y = imageAspect / aspect;
  30069. texture.offset.x = 0;
  30070. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  30071. } else {
  30072. texture.repeat.x = aspect / imageAspect;
  30073. texture.repeat.y = 1;
  30074. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  30075. texture.offset.y = 0;
  30076. }
  30077. return texture;
  30078. }
  30079. /**
  30080. * Scales the texture to the smallest possible size to fill the surface, leaving
  30081. * no empty space. The method preserves the original aspect ratio of the texture.
  30082. * Akin to CSS `object-fit: cover`.
  30083. *
  30084. * @param {Texture} texture - The texture.
  30085. * @param {number} aspect - The texture's aspect ratio.
  30086. * @return {Texture} The updated texture.
  30087. */
  30088. function cover( texture, aspect ) {
  30089. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  30090. if ( imageAspect > aspect ) {
  30091. texture.repeat.x = aspect / imageAspect;
  30092. texture.repeat.y = 1;
  30093. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  30094. texture.offset.y = 0;
  30095. } else {
  30096. texture.repeat.x = 1;
  30097. texture.repeat.y = imageAspect / aspect;
  30098. texture.offset.x = 0;
  30099. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  30100. }
  30101. return texture;
  30102. }
  30103. /**
  30104. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  30105. *
  30106. * @param {Texture} texture - The texture.
  30107. * @return {Texture} The updated texture.
  30108. */
  30109. function fill( texture ) {
  30110. texture.repeat.x = 1;
  30111. texture.repeat.y = 1;
  30112. texture.offset.x = 0;
  30113. texture.offset.y = 0;
  30114. return texture;
  30115. }
  30116. /**
  30117. * Determines how many bytes must be used to represent the texture.
  30118. *
  30119. * @param {number} width - The width of the texture.
  30120. * @param {number} height - The height of the texture.
  30121. * @param {number} format - The texture's format.
  30122. * @param {number} type - The texture's type.
  30123. * @return {number} The byte length.
  30124. */
  30125. function getByteLength( width, height, format, type ) {
  30126. const typeByteLength = getTextureTypeByteLength( type );
  30127. switch ( format ) {
  30128. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  30129. case AlphaFormat:
  30130. return width * height;
  30131. case LuminanceFormat:
  30132. return width * height;
  30133. case LuminanceAlphaFormat:
  30134. return width * height * 2;
  30135. case RedFormat:
  30136. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  30137. case RedIntegerFormat:
  30138. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  30139. case RGFormat:
  30140. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30141. case RGIntegerFormat:
  30142. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30143. case RGBFormat:
  30144. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30145. case RGBAFormat:
  30146. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30147. case RGBAIntegerFormat:
  30148. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30149. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  30150. case RGB_S3TC_DXT1_Format:
  30151. case RGBA_S3TC_DXT1_Format:
  30152. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  30153. case RGBA_S3TC_DXT3_Format:
  30154. case RGBA_S3TC_DXT5_Format:
  30155. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30156. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  30157. case RGB_PVRTC_2BPPV1_Format:
  30158. case RGBA_PVRTC_2BPPV1_Format:
  30159. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  30160. case RGB_PVRTC_4BPPV1_Format:
  30161. case RGBA_PVRTC_4BPPV1_Format:
  30162. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  30163. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  30164. case RGB_ETC1_Format:
  30165. case RGB_ETC2_Format:
  30166. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  30167. case RGBA_ETC2_EAC_Format:
  30168. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30169. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  30170. case RGBA_ASTC_4x4_Format:
  30171. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30172. case RGBA_ASTC_5x4_Format:
  30173. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30174. case RGBA_ASTC_5x5_Format:
  30175. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30176. case RGBA_ASTC_6x5_Format:
  30177. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30178. case RGBA_ASTC_6x6_Format:
  30179. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  30180. case RGBA_ASTC_8x5_Format:
  30181. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30182. case RGBA_ASTC_8x6_Format:
  30183. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  30184. case RGBA_ASTC_8x8_Format:
  30185. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  30186. case RGBA_ASTC_10x5_Format:
  30187. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30188. case RGBA_ASTC_10x6_Format:
  30189. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  30190. case RGBA_ASTC_10x8_Format:
  30191. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  30192. case RGBA_ASTC_10x10_Format:
  30193. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  30194. case RGBA_ASTC_12x10_Format:
  30195. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  30196. case RGBA_ASTC_12x12_Format:
  30197. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  30198. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  30199. case RGBA_BPTC_Format:
  30200. case RGB_BPTC_SIGNED_Format:
  30201. case RGB_BPTC_UNSIGNED_Format:
  30202. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  30203. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  30204. case RED_RGTC1_Format:
  30205. case SIGNED_RED_RGTC1_Format:
  30206. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  30207. case RED_GREEN_RGTC2_Format:
  30208. case SIGNED_RED_GREEN_RGTC2_Format:
  30209. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  30210. }
  30211. throw new Error(
  30212. `Unable to determine texture byte length for ${format} format.`,
  30213. );
  30214. }
  30215. function getTextureTypeByteLength( type ) {
  30216. switch ( type ) {
  30217. case UnsignedByteType:
  30218. case ByteType:
  30219. return { byteLength: 1, components: 1 };
  30220. case UnsignedShortType:
  30221. case ShortType:
  30222. case HalfFloatType:
  30223. return { byteLength: 2, components: 1 };
  30224. case UnsignedShort4444Type:
  30225. case UnsignedShort5551Type:
  30226. return { byteLength: 2, components: 4 };
  30227. case UnsignedIntType:
  30228. case IntType:
  30229. case FloatType:
  30230. return { byteLength: 4, components: 1 };
  30231. case UnsignedInt5999Type:
  30232. return { byteLength: 4, components: 3 };
  30233. }
  30234. throw new Error( `Unknown texture type ${type}.` );
  30235. }
  30236. /**
  30237. * A class containing utility functions for textures.
  30238. *
  30239. * @hideconstructor
  30240. */
  30241. class TextureUtils {
  30242. /**
  30243. * Scales the texture as large as possible within its surface without cropping
  30244. * or stretching the texture. The method preserves the original aspect ratio of
  30245. * the texture. Akin to CSS `object-fit: contain`
  30246. *
  30247. * @param {Texture} texture - The texture.
  30248. * @param {number} aspect - The texture's aspect ratio.
  30249. * @return {Texture} The updated texture.
  30250. */
  30251. static contain( texture, aspect ) {
  30252. return contain( texture, aspect );
  30253. }
  30254. /**
  30255. * Scales the texture to the smallest possible size to fill the surface, leaving
  30256. * no empty space. The method preserves the original aspect ratio of the texture.
  30257. * Akin to CSS `object-fit: cover`.
  30258. *
  30259. * @param {Texture} texture - The texture.
  30260. * @param {number} aspect - The texture's aspect ratio.
  30261. * @return {Texture} The updated texture.
  30262. */
  30263. static cover( texture, aspect ) {
  30264. return cover( texture, aspect );
  30265. }
  30266. /**
  30267. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  30268. *
  30269. * @param {Texture} texture - The texture.
  30270. * @return {Texture} The updated texture.
  30271. */
  30272. static fill( texture ) {
  30273. return fill( texture );
  30274. }
  30275. /**
  30276. * Determines how many bytes must be used to represent the texture.
  30277. *
  30278. * @param {number} width - The width of the texture.
  30279. * @param {number} height - The height of the texture.
  30280. * @param {number} format - The texture's format.
  30281. * @param {number} type - The texture's type.
  30282. * @return {number} The byte length.
  30283. */
  30284. static getByteLength( width, height, format, type ) {
  30285. return getByteLength( width, height, format, type );
  30286. }
  30287. }
  30288. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30289. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30290. revision: REVISION,
  30291. } } ) );
  30292. }
  30293. if ( typeof window !== 'undefined' ) {
  30294. if ( window.__THREE__ ) {
  30295. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30296. } else {
  30297. window.__THREE__ = REVISION;
  30298. }
  30299. }
  30300. function WebGLAnimation() {
  30301. let context = null;
  30302. let isAnimating = false;
  30303. let animationLoop = null;
  30304. let requestId = null;
  30305. function onAnimationFrame( time, frame ) {
  30306. animationLoop( time, frame );
  30307. requestId = context.requestAnimationFrame( onAnimationFrame );
  30308. }
  30309. return {
  30310. start: function () {
  30311. if ( isAnimating === true ) return;
  30312. if ( animationLoop === null ) return;
  30313. requestId = context.requestAnimationFrame( onAnimationFrame );
  30314. isAnimating = true;
  30315. },
  30316. stop: function () {
  30317. context.cancelAnimationFrame( requestId );
  30318. isAnimating = false;
  30319. },
  30320. setAnimationLoop: function ( callback ) {
  30321. animationLoop = callback;
  30322. },
  30323. setContext: function ( value ) {
  30324. context = value;
  30325. }
  30326. };
  30327. }
  30328. function WebGLAttributes( gl ) {
  30329. const buffers = new WeakMap();
  30330. function createBuffer( attribute, bufferType ) {
  30331. const array = attribute.array;
  30332. const usage = attribute.usage;
  30333. const size = array.byteLength;
  30334. const buffer = gl.createBuffer();
  30335. gl.bindBuffer( bufferType, buffer );
  30336. gl.bufferData( bufferType, array, usage );
  30337. attribute.onUploadCallback();
  30338. let type;
  30339. if ( array instanceof Float32Array ) {
  30340. type = gl.FLOAT;
  30341. } else if ( array instanceof Uint16Array ) {
  30342. if ( attribute.isFloat16BufferAttribute ) {
  30343. type = gl.HALF_FLOAT;
  30344. } else {
  30345. type = gl.UNSIGNED_SHORT;
  30346. }
  30347. } else if ( array instanceof Int16Array ) {
  30348. type = gl.SHORT;
  30349. } else if ( array instanceof Uint32Array ) {
  30350. type = gl.UNSIGNED_INT;
  30351. } else if ( array instanceof Int32Array ) {
  30352. type = gl.INT;
  30353. } else if ( array instanceof Int8Array ) {
  30354. type = gl.BYTE;
  30355. } else if ( array instanceof Uint8Array ) {
  30356. type = gl.UNSIGNED_BYTE;
  30357. } else if ( array instanceof Uint8ClampedArray ) {
  30358. type = gl.UNSIGNED_BYTE;
  30359. } else {
  30360. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  30361. }
  30362. return {
  30363. buffer: buffer,
  30364. type: type,
  30365. bytesPerElement: array.BYTES_PER_ELEMENT,
  30366. version: attribute.version,
  30367. size: size
  30368. };
  30369. }
  30370. function updateBuffer( buffer, attribute, bufferType ) {
  30371. const array = attribute.array;
  30372. const updateRanges = attribute.updateRanges;
  30373. gl.bindBuffer( bufferType, buffer );
  30374. if ( updateRanges.length === 0 ) {
  30375. // Not using update ranges
  30376. gl.bufferSubData( bufferType, 0, array );
  30377. } else {
  30378. // Before applying update ranges, we merge any adjacent / overlapping
  30379. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  30380. // to performance improvements for applications which make heavy use of
  30381. // update ranges. Likely due to GPU command overhead.
  30382. //
  30383. // Note that to reduce garbage collection between frames, we merge the
  30384. // update ranges in-place. This is safe because this method will clear the
  30385. // update ranges once updated.
  30386. updateRanges.sort( ( a, b ) => a.start - b.start );
  30387. // To merge the update ranges in-place, we work from left to right in the
  30388. // existing updateRanges array, merging ranges. This may result in a final
  30389. // array which is smaller than the original. This index tracks the last
  30390. // index representing a merged range, any data after this index can be
  30391. // trimmed once the merge algorithm is completed.
  30392. let mergeIndex = 0;
  30393. for ( let i = 1; i < updateRanges.length; i ++ ) {
  30394. const previousRange = updateRanges[ mergeIndex ];
  30395. const range = updateRanges[ i ];
  30396. // We add one here to merge adjacent ranges. This is safe because ranges
  30397. // operate over positive integers.
  30398. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  30399. previousRange.count = Math.max(
  30400. previousRange.count,
  30401. range.start + range.count - previousRange.start
  30402. );
  30403. } else {
  30404. ++ mergeIndex;
  30405. updateRanges[ mergeIndex ] = range;
  30406. }
  30407. }
  30408. // Trim the array to only contain the merged ranges.
  30409. updateRanges.length = mergeIndex + 1;
  30410. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  30411. const range = updateRanges[ i ];
  30412. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  30413. array, range.start, range.count );
  30414. }
  30415. attribute.clearUpdateRanges();
  30416. }
  30417. attribute.onUploadCallback();
  30418. }
  30419. //
  30420. function get( attribute ) {
  30421. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  30422. return buffers.get( attribute );
  30423. }
  30424. function remove( attribute ) {
  30425. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  30426. const data = buffers.get( attribute );
  30427. if ( data ) {
  30428. gl.deleteBuffer( data.buffer );
  30429. buffers.delete( attribute );
  30430. }
  30431. }
  30432. function update( attribute, bufferType ) {
  30433. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  30434. if ( attribute.isGLBufferAttribute ) {
  30435. const cached = buffers.get( attribute );
  30436. if ( ! cached || cached.version < attribute.version ) {
  30437. buffers.set( attribute, {
  30438. buffer: attribute.buffer,
  30439. type: attribute.type,
  30440. bytesPerElement: attribute.elementSize,
  30441. version: attribute.version
  30442. } );
  30443. }
  30444. return;
  30445. }
  30446. const data = buffers.get( attribute );
  30447. if ( data === undefined ) {
  30448. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  30449. } else if ( data.version < attribute.version ) {
  30450. if ( data.size !== attribute.array.byteLength ) {
  30451. 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.' );
  30452. }
  30453. updateBuffer( data.buffer, attribute, bufferType );
  30454. data.version = attribute.version;
  30455. }
  30456. }
  30457. return {
  30458. get: get,
  30459. remove: remove,
  30460. update: update
  30461. };
  30462. }
  30463. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  30464. 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";
  30465. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  30466. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  30467. 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";
  30468. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  30469. 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";
  30470. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  30471. 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";
  30472. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  30473. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  30474. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  30475. 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";
  30476. 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";
  30477. 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";
  30478. 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";
  30479. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  30480. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  30481. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  30482. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  30483. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  30484. 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";
  30485. 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";
  30486. 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";
  30487. 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";
  30488. 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";
  30489. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  30490. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  30491. 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";
  30492. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  30493. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  30494. 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}";
  30495. 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";
  30496. 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";
  30497. 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";
  30498. 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";
  30499. 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";
  30500. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  30501. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  30502. 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";
  30503. 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";
  30504. 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}";
  30505. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  30506. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  30507. 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";
  30508. 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";
  30509. 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";
  30510. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  30511. 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";
  30512. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  30513. 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";
  30514. 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";
  30515. 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}";
  30516. 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";
  30517. 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";
  30518. 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";
  30519. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  30520. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  30521. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  30522. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  30523. 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";
  30524. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  30525. 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";
  30526. 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";
  30527. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  30528. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  30529. 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";
  30530. 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";
  30531. 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";
  30532. 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";
  30533. 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";
  30534. 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;";
  30535. 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";
  30536. 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";
  30537. 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";
  30538. 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";
  30539. 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";
  30540. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  30541. 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";
  30542. 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";
  30543. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  30544. 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 );";
  30545. 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}";
  30546. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  30547. 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;";
  30548. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  30549. 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";
  30550. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  30551. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  30552. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif";
  30553. 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";
  30554. 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";
  30555. 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}";
  30556. 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";
  30557. 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";
  30558. 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";
  30559. 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";
  30560. 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";
  30561. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  30562. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  30563. 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; }";
  30564. 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";
  30565. 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";
  30566. 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";
  30567. 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";
  30568. 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";
  30569. 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";
  30570. 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}";
  30571. 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}";
  30572. 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}";
  30573. 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}";
  30574. 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}";
  30575. 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}";
  30576. 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}";
  30577. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  30578. 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}";
  30579. 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}";
  30580. 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}";
  30581. 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}";
  30582. 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}";
  30583. 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}";
  30584. 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}";
  30585. 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}";
  30586. 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}";
  30587. 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}";
  30588. 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}";
  30589. 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}";
  30590. 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}";
  30591. 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}";
  30592. 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}";
  30593. 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}";
  30594. 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}";
  30595. 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}";
  30596. 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}";
  30597. 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}";
  30598. 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}";
  30599. 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}";
  30600. 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}";
  30601. 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}";
  30602. 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}";
  30603. 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}";
  30604. const ShaderChunk = {
  30605. alphahash_fragment: alphahash_fragment,
  30606. alphahash_pars_fragment: alphahash_pars_fragment,
  30607. alphamap_fragment: alphamap_fragment,
  30608. alphamap_pars_fragment: alphamap_pars_fragment,
  30609. alphatest_fragment: alphatest_fragment,
  30610. alphatest_pars_fragment: alphatest_pars_fragment,
  30611. aomap_fragment: aomap_fragment,
  30612. aomap_pars_fragment: aomap_pars_fragment,
  30613. batching_pars_vertex: batching_pars_vertex,
  30614. batching_vertex: batching_vertex,
  30615. begin_vertex: begin_vertex,
  30616. beginnormal_vertex: beginnormal_vertex,
  30617. bsdfs: bsdfs,
  30618. iridescence_fragment: iridescence_fragment,
  30619. bumpmap_pars_fragment: bumpmap_pars_fragment,
  30620. clipping_planes_fragment: clipping_planes_fragment,
  30621. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  30622. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  30623. clipping_planes_vertex: clipping_planes_vertex,
  30624. color_fragment: color_fragment,
  30625. color_pars_fragment: color_pars_fragment,
  30626. color_pars_vertex: color_pars_vertex,
  30627. color_vertex: color_vertex,
  30628. common: common,
  30629. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  30630. defaultnormal_vertex: defaultnormal_vertex,
  30631. displacementmap_pars_vertex: displacementmap_pars_vertex,
  30632. displacementmap_vertex: displacementmap_vertex,
  30633. emissivemap_fragment: emissivemap_fragment,
  30634. emissivemap_pars_fragment: emissivemap_pars_fragment,
  30635. colorspace_fragment: colorspace_fragment,
  30636. colorspace_pars_fragment: colorspace_pars_fragment,
  30637. envmap_fragment: envmap_fragment,
  30638. envmap_common_pars_fragment: envmap_common_pars_fragment,
  30639. envmap_pars_fragment: envmap_pars_fragment,
  30640. envmap_pars_vertex: envmap_pars_vertex,
  30641. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  30642. envmap_vertex: envmap_vertex,
  30643. fog_vertex: fog_vertex,
  30644. fog_pars_vertex: fog_pars_vertex,
  30645. fog_fragment: fog_fragment,
  30646. fog_pars_fragment: fog_pars_fragment,
  30647. gradientmap_pars_fragment: gradientmap_pars_fragment,
  30648. lightmap_pars_fragment: lightmap_pars_fragment,
  30649. lights_lambert_fragment: lights_lambert_fragment,
  30650. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  30651. lights_pars_begin: lights_pars_begin,
  30652. lights_toon_fragment: lights_toon_fragment,
  30653. lights_toon_pars_fragment: lights_toon_pars_fragment,
  30654. lights_phong_fragment: lights_phong_fragment,
  30655. lights_phong_pars_fragment: lights_phong_pars_fragment,
  30656. lights_physical_fragment: lights_physical_fragment,
  30657. lights_physical_pars_fragment: lights_physical_pars_fragment,
  30658. lights_fragment_begin: lights_fragment_begin,
  30659. lights_fragment_maps: lights_fragment_maps,
  30660. lights_fragment_end: lights_fragment_end,
  30661. logdepthbuf_fragment: logdepthbuf_fragment,
  30662. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  30663. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  30664. logdepthbuf_vertex: logdepthbuf_vertex,
  30665. map_fragment: map_fragment,
  30666. map_pars_fragment: map_pars_fragment,
  30667. map_particle_fragment: map_particle_fragment,
  30668. map_particle_pars_fragment: map_particle_pars_fragment,
  30669. metalnessmap_fragment: metalnessmap_fragment,
  30670. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  30671. morphinstance_vertex: morphinstance_vertex,
  30672. morphcolor_vertex: morphcolor_vertex,
  30673. morphnormal_vertex: morphnormal_vertex,
  30674. morphtarget_pars_vertex: morphtarget_pars_vertex,
  30675. morphtarget_vertex: morphtarget_vertex,
  30676. normal_fragment_begin: normal_fragment_begin,
  30677. normal_fragment_maps: normal_fragment_maps,
  30678. normal_pars_fragment: normal_pars_fragment,
  30679. normal_pars_vertex: normal_pars_vertex,
  30680. normal_vertex: normal_vertex,
  30681. normalmap_pars_fragment: normalmap_pars_fragment,
  30682. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  30683. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  30684. clearcoat_pars_fragment: clearcoat_pars_fragment,
  30685. iridescence_pars_fragment: iridescence_pars_fragment,
  30686. opaque_fragment: opaque_fragment,
  30687. packing: packing,
  30688. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  30689. project_vertex: project_vertex,
  30690. dithering_fragment: dithering_fragment,
  30691. dithering_pars_fragment: dithering_pars_fragment,
  30692. roughnessmap_fragment: roughnessmap_fragment,
  30693. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  30694. shadowmap_pars_fragment: shadowmap_pars_fragment,
  30695. shadowmap_pars_vertex: shadowmap_pars_vertex,
  30696. shadowmap_vertex: shadowmap_vertex,
  30697. shadowmask_pars_fragment: shadowmask_pars_fragment,
  30698. skinbase_vertex: skinbase_vertex,
  30699. skinning_pars_vertex: skinning_pars_vertex,
  30700. skinning_vertex: skinning_vertex,
  30701. skinnormal_vertex: skinnormal_vertex,
  30702. specularmap_fragment: specularmap_fragment,
  30703. specularmap_pars_fragment: specularmap_pars_fragment,
  30704. tonemapping_fragment: tonemapping_fragment,
  30705. tonemapping_pars_fragment: tonemapping_pars_fragment,
  30706. transmission_fragment: transmission_fragment,
  30707. transmission_pars_fragment: transmission_pars_fragment,
  30708. uv_pars_fragment: uv_pars_fragment,
  30709. uv_pars_vertex: uv_pars_vertex,
  30710. uv_vertex: uv_vertex,
  30711. worldpos_vertex: worldpos_vertex,
  30712. background_vert: vertex$h,
  30713. background_frag: fragment$h,
  30714. backgroundCube_vert: vertex$g,
  30715. backgroundCube_frag: fragment$g,
  30716. cube_vert: vertex$f,
  30717. cube_frag: fragment$f,
  30718. depth_vert: vertex$e,
  30719. depth_frag: fragment$e,
  30720. distanceRGBA_vert: vertex$d,
  30721. distanceRGBA_frag: fragment$d,
  30722. equirect_vert: vertex$c,
  30723. equirect_frag: fragment$c,
  30724. linedashed_vert: vertex$b,
  30725. linedashed_frag: fragment$b,
  30726. meshbasic_vert: vertex$a,
  30727. meshbasic_frag: fragment$a,
  30728. meshlambert_vert: vertex$9,
  30729. meshlambert_frag: fragment$9,
  30730. meshmatcap_vert: vertex$8,
  30731. meshmatcap_frag: fragment$8,
  30732. meshnormal_vert: vertex$7,
  30733. meshnormal_frag: fragment$7,
  30734. meshphong_vert: vertex$6,
  30735. meshphong_frag: fragment$6,
  30736. meshphysical_vert: vertex$5,
  30737. meshphysical_frag: fragment$5,
  30738. meshtoon_vert: vertex$4,
  30739. meshtoon_frag: fragment$4,
  30740. points_vert: vertex$3,
  30741. points_frag: fragment$3,
  30742. shadow_vert: vertex$2,
  30743. shadow_frag: fragment$2,
  30744. sprite_vert: vertex$1,
  30745. sprite_frag: fragment$1
  30746. };
  30747. /**
  30748. * Uniforms library for shared webgl shaders
  30749. */
  30750. const UniformsLib = {
  30751. common: {
  30752. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  30753. opacity: { value: 1.0 },
  30754. map: { value: null },
  30755. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30756. alphaMap: { value: null },
  30757. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30758. alphaTest: { value: 0 }
  30759. },
  30760. specularmap: {
  30761. specularMap: { value: null },
  30762. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  30763. },
  30764. envmap: {
  30765. envMap: { value: null },
  30766. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  30767. flipEnvMap: { value: -1 },
  30768. reflectivity: { value: 1.0 }, // basic, lambert, phong
  30769. ior: { value: 1.5 }, // physical
  30770. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  30771. },
  30772. aomap: {
  30773. aoMap: { value: null },
  30774. aoMapIntensity: { value: 1 },
  30775. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  30776. },
  30777. lightmap: {
  30778. lightMap: { value: null },
  30779. lightMapIntensity: { value: 1 },
  30780. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  30781. },
  30782. bumpmap: {
  30783. bumpMap: { value: null },
  30784. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30785. bumpScale: { value: 1 }
  30786. },
  30787. normalmap: {
  30788. normalMap: { value: null },
  30789. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30790. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  30791. },
  30792. displacementmap: {
  30793. displacementMap: { value: null },
  30794. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30795. displacementScale: { value: 1 },
  30796. displacementBias: { value: 0 }
  30797. },
  30798. emissivemap: {
  30799. emissiveMap: { value: null },
  30800. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  30801. },
  30802. metalnessmap: {
  30803. metalnessMap: { value: null },
  30804. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  30805. },
  30806. roughnessmap: {
  30807. roughnessMap: { value: null },
  30808. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  30809. },
  30810. gradientmap: {
  30811. gradientMap: { value: null }
  30812. },
  30813. fog: {
  30814. fogDensity: { value: 0.00025 },
  30815. fogNear: { value: 1 },
  30816. fogFar: { value: 2000 },
  30817. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  30818. },
  30819. lights: {
  30820. ambientLightColor: { value: [] },
  30821. lightProbe: { value: [] },
  30822. directionalLights: { value: [], properties: {
  30823. direction: {},
  30824. color: {}
  30825. } },
  30826. directionalLightShadows: { value: [], properties: {
  30827. shadowIntensity: 1,
  30828. shadowBias: {},
  30829. shadowNormalBias: {},
  30830. shadowRadius: {},
  30831. shadowMapSize: {}
  30832. } },
  30833. directionalShadowMap: { value: [] },
  30834. directionalShadowMatrix: { value: [] },
  30835. spotLights: { value: [], properties: {
  30836. color: {},
  30837. position: {},
  30838. direction: {},
  30839. distance: {},
  30840. coneCos: {},
  30841. penumbraCos: {},
  30842. decay: {}
  30843. } },
  30844. spotLightShadows: { value: [], properties: {
  30845. shadowIntensity: 1,
  30846. shadowBias: {},
  30847. shadowNormalBias: {},
  30848. shadowRadius: {},
  30849. shadowMapSize: {}
  30850. } },
  30851. spotLightMap: { value: [] },
  30852. spotShadowMap: { value: [] },
  30853. spotLightMatrix: { value: [] },
  30854. pointLights: { value: [], properties: {
  30855. color: {},
  30856. position: {},
  30857. decay: {},
  30858. distance: {}
  30859. } },
  30860. pointLightShadows: { value: [], properties: {
  30861. shadowIntensity: 1,
  30862. shadowBias: {},
  30863. shadowNormalBias: {},
  30864. shadowRadius: {},
  30865. shadowMapSize: {},
  30866. shadowCameraNear: {},
  30867. shadowCameraFar: {}
  30868. } },
  30869. pointShadowMap: { value: [] },
  30870. pointShadowMatrix: { value: [] },
  30871. hemisphereLights: { value: [], properties: {
  30872. direction: {},
  30873. skyColor: {},
  30874. groundColor: {}
  30875. } },
  30876. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  30877. rectAreaLights: { value: [], properties: {
  30878. color: {},
  30879. position: {},
  30880. width: {},
  30881. height: {}
  30882. } },
  30883. ltc_1: { value: null },
  30884. ltc_2: { value: null }
  30885. },
  30886. points: {
  30887. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  30888. opacity: { value: 1.0 },
  30889. size: { value: 1.0 },
  30890. scale: { value: 1.0 },
  30891. map: { value: null },
  30892. alphaMap: { value: null },
  30893. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30894. alphaTest: { value: 0 },
  30895. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  30896. },
  30897. sprite: {
  30898. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  30899. opacity: { value: 1.0 },
  30900. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  30901. rotation: { value: 0.0 },
  30902. map: { value: null },
  30903. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30904. alphaMap: { value: null },
  30905. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  30906. alphaTest: { value: 0 }
  30907. }
  30908. };
  30909. const ShaderLib = {
  30910. basic: {
  30911. uniforms: /*@__PURE__*/ mergeUniforms( [
  30912. UniformsLib.common,
  30913. UniformsLib.specularmap,
  30914. UniformsLib.envmap,
  30915. UniformsLib.aomap,
  30916. UniformsLib.lightmap,
  30917. UniformsLib.fog
  30918. ] ),
  30919. vertexShader: ShaderChunk.meshbasic_vert,
  30920. fragmentShader: ShaderChunk.meshbasic_frag
  30921. },
  30922. lambert: {
  30923. uniforms: /*@__PURE__*/ mergeUniforms( [
  30924. UniformsLib.common,
  30925. UniformsLib.specularmap,
  30926. UniformsLib.envmap,
  30927. UniformsLib.aomap,
  30928. UniformsLib.lightmap,
  30929. UniformsLib.emissivemap,
  30930. UniformsLib.bumpmap,
  30931. UniformsLib.normalmap,
  30932. UniformsLib.displacementmap,
  30933. UniformsLib.fog,
  30934. UniformsLib.lights,
  30935. {
  30936. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  30937. }
  30938. ] ),
  30939. vertexShader: ShaderChunk.meshlambert_vert,
  30940. fragmentShader: ShaderChunk.meshlambert_frag
  30941. },
  30942. phong: {
  30943. uniforms: /*@__PURE__*/ mergeUniforms( [
  30944. UniformsLib.common,
  30945. UniformsLib.specularmap,
  30946. UniformsLib.envmap,
  30947. UniformsLib.aomap,
  30948. UniformsLib.lightmap,
  30949. UniformsLib.emissivemap,
  30950. UniformsLib.bumpmap,
  30951. UniformsLib.normalmap,
  30952. UniformsLib.displacementmap,
  30953. UniformsLib.fog,
  30954. UniformsLib.lights,
  30955. {
  30956. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  30957. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  30958. shininess: { value: 30 }
  30959. }
  30960. ] ),
  30961. vertexShader: ShaderChunk.meshphong_vert,
  30962. fragmentShader: ShaderChunk.meshphong_frag
  30963. },
  30964. standard: {
  30965. uniforms: /*@__PURE__*/ mergeUniforms( [
  30966. UniformsLib.common,
  30967. UniformsLib.envmap,
  30968. UniformsLib.aomap,
  30969. UniformsLib.lightmap,
  30970. UniformsLib.emissivemap,
  30971. UniformsLib.bumpmap,
  30972. UniformsLib.normalmap,
  30973. UniformsLib.displacementmap,
  30974. UniformsLib.roughnessmap,
  30975. UniformsLib.metalnessmap,
  30976. UniformsLib.fog,
  30977. UniformsLib.lights,
  30978. {
  30979. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  30980. roughness: { value: 1.0 },
  30981. metalness: { value: 0.0 },
  30982. envMapIntensity: { value: 1 }
  30983. }
  30984. ] ),
  30985. vertexShader: ShaderChunk.meshphysical_vert,
  30986. fragmentShader: ShaderChunk.meshphysical_frag
  30987. },
  30988. toon: {
  30989. uniforms: /*@__PURE__*/ mergeUniforms( [
  30990. UniformsLib.common,
  30991. UniformsLib.aomap,
  30992. UniformsLib.lightmap,
  30993. UniformsLib.emissivemap,
  30994. UniformsLib.bumpmap,
  30995. UniformsLib.normalmap,
  30996. UniformsLib.displacementmap,
  30997. UniformsLib.gradientmap,
  30998. UniformsLib.fog,
  30999. UniformsLib.lights,
  31000. {
  31001. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  31002. }
  31003. ] ),
  31004. vertexShader: ShaderChunk.meshtoon_vert,
  31005. fragmentShader: ShaderChunk.meshtoon_frag
  31006. },
  31007. matcap: {
  31008. uniforms: /*@__PURE__*/ mergeUniforms( [
  31009. UniformsLib.common,
  31010. UniformsLib.bumpmap,
  31011. UniformsLib.normalmap,
  31012. UniformsLib.displacementmap,
  31013. UniformsLib.fog,
  31014. {
  31015. matcap: { value: null }
  31016. }
  31017. ] ),
  31018. vertexShader: ShaderChunk.meshmatcap_vert,
  31019. fragmentShader: ShaderChunk.meshmatcap_frag
  31020. },
  31021. points: {
  31022. uniforms: /*@__PURE__*/ mergeUniforms( [
  31023. UniformsLib.points,
  31024. UniformsLib.fog
  31025. ] ),
  31026. vertexShader: ShaderChunk.points_vert,
  31027. fragmentShader: ShaderChunk.points_frag
  31028. },
  31029. dashed: {
  31030. uniforms: /*@__PURE__*/ mergeUniforms( [
  31031. UniformsLib.common,
  31032. UniformsLib.fog,
  31033. {
  31034. scale: { value: 1 },
  31035. dashSize: { value: 1 },
  31036. totalSize: { value: 2 }
  31037. }
  31038. ] ),
  31039. vertexShader: ShaderChunk.linedashed_vert,
  31040. fragmentShader: ShaderChunk.linedashed_frag
  31041. },
  31042. depth: {
  31043. uniforms: /*@__PURE__*/ mergeUniforms( [
  31044. UniformsLib.common,
  31045. UniformsLib.displacementmap
  31046. ] ),
  31047. vertexShader: ShaderChunk.depth_vert,
  31048. fragmentShader: ShaderChunk.depth_frag
  31049. },
  31050. normal: {
  31051. uniforms: /*@__PURE__*/ mergeUniforms( [
  31052. UniformsLib.common,
  31053. UniformsLib.bumpmap,
  31054. UniformsLib.normalmap,
  31055. UniformsLib.displacementmap,
  31056. {
  31057. opacity: { value: 1.0 }
  31058. }
  31059. ] ),
  31060. vertexShader: ShaderChunk.meshnormal_vert,
  31061. fragmentShader: ShaderChunk.meshnormal_frag
  31062. },
  31063. sprite: {
  31064. uniforms: /*@__PURE__*/ mergeUniforms( [
  31065. UniformsLib.sprite,
  31066. UniformsLib.fog
  31067. ] ),
  31068. vertexShader: ShaderChunk.sprite_vert,
  31069. fragmentShader: ShaderChunk.sprite_frag
  31070. },
  31071. background: {
  31072. uniforms: {
  31073. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  31074. t2D: { value: null },
  31075. backgroundIntensity: { value: 1 }
  31076. },
  31077. vertexShader: ShaderChunk.background_vert,
  31078. fragmentShader: ShaderChunk.background_frag
  31079. },
  31080. backgroundCube: {
  31081. uniforms: {
  31082. envMap: { value: null },
  31083. flipEnvMap: { value: -1 },
  31084. backgroundBlurriness: { value: 0 },
  31085. backgroundIntensity: { value: 1 },
  31086. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  31087. },
  31088. vertexShader: ShaderChunk.backgroundCube_vert,
  31089. fragmentShader: ShaderChunk.backgroundCube_frag
  31090. },
  31091. cube: {
  31092. uniforms: {
  31093. tCube: { value: null },
  31094. tFlip: { value: -1 },
  31095. opacity: { value: 1.0 }
  31096. },
  31097. vertexShader: ShaderChunk.cube_vert,
  31098. fragmentShader: ShaderChunk.cube_frag
  31099. },
  31100. equirect: {
  31101. uniforms: {
  31102. tEquirect: { value: null },
  31103. },
  31104. vertexShader: ShaderChunk.equirect_vert,
  31105. fragmentShader: ShaderChunk.equirect_frag
  31106. },
  31107. distanceRGBA: {
  31108. uniforms: /*@__PURE__*/ mergeUniforms( [
  31109. UniformsLib.common,
  31110. UniformsLib.displacementmap,
  31111. {
  31112. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  31113. nearDistance: { value: 1 },
  31114. farDistance: { value: 1000 }
  31115. }
  31116. ] ),
  31117. vertexShader: ShaderChunk.distanceRGBA_vert,
  31118. fragmentShader: ShaderChunk.distanceRGBA_frag
  31119. },
  31120. shadow: {
  31121. uniforms: /*@__PURE__*/ mergeUniforms( [
  31122. UniformsLib.lights,
  31123. UniformsLib.fog,
  31124. {
  31125. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  31126. opacity: { value: 1.0 }
  31127. },
  31128. ] ),
  31129. vertexShader: ShaderChunk.shadow_vert,
  31130. fragmentShader: ShaderChunk.shadow_frag
  31131. }
  31132. };
  31133. ShaderLib.physical = {
  31134. uniforms: /*@__PURE__*/ mergeUniforms( [
  31135. ShaderLib.standard.uniforms,
  31136. {
  31137. clearcoat: { value: 0 },
  31138. clearcoatMap: { value: null },
  31139. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31140. clearcoatNormalMap: { value: null },
  31141. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31142. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  31143. clearcoatRoughness: { value: 0 },
  31144. clearcoatRoughnessMap: { value: null },
  31145. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31146. dispersion: { value: 0 },
  31147. iridescence: { value: 0 },
  31148. iridescenceMap: { value: null },
  31149. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31150. iridescenceIOR: { value: 1.3 },
  31151. iridescenceThicknessMinimum: { value: 100 },
  31152. iridescenceThicknessMaximum: { value: 400 },
  31153. iridescenceThicknessMap: { value: null },
  31154. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31155. sheen: { value: 0 },
  31156. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  31157. sheenColorMap: { value: null },
  31158. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31159. sheenRoughness: { value: 1 },
  31160. sheenRoughnessMap: { value: null },
  31161. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31162. transmission: { value: 0 },
  31163. transmissionMap: { value: null },
  31164. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31165. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  31166. transmissionSamplerMap: { value: null },
  31167. thickness: { value: 0 },
  31168. thicknessMap: { value: null },
  31169. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31170. attenuationDistance: { value: 0 },
  31171. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  31172. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  31173. specularColorMap: { value: null },
  31174. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31175. specularIntensity: { value: 1 },
  31176. specularIntensityMap: { value: null },
  31177. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31178. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  31179. anisotropyMap: { value: null },
  31180. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  31181. }
  31182. ] ),
  31183. vertexShader: ShaderChunk.meshphysical_vert,
  31184. fragmentShader: ShaderChunk.meshphysical_frag
  31185. };
  31186. const _rgb = { r: 0, b: 0, g: 0 };
  31187. const _e1$1 = /*@__PURE__*/ new Euler();
  31188. const _m1$1 = /*@__PURE__*/ new Matrix4();
  31189. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  31190. const clearColor = new Color( 0x000000 );
  31191. let clearAlpha = alpha === true ? 0 : 1;
  31192. let planeMesh;
  31193. let boxMesh;
  31194. let currentBackground = null;
  31195. let currentBackgroundVersion = 0;
  31196. let currentTonemapping = null;
  31197. function getBackground( scene ) {
  31198. let background = scene.isScene === true ? scene.background : null;
  31199. if ( background && background.isTexture ) {
  31200. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  31201. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  31202. }
  31203. return background;
  31204. }
  31205. function render( scene ) {
  31206. let forceClear = false;
  31207. const background = getBackground( scene );
  31208. if ( background === null ) {
  31209. setClear( clearColor, clearAlpha );
  31210. } else if ( background && background.isColor ) {
  31211. setClear( background, 1 );
  31212. forceClear = true;
  31213. }
  31214. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  31215. if ( environmentBlendMode === 'additive' ) {
  31216. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  31217. } else if ( environmentBlendMode === 'alpha-blend' ) {
  31218. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  31219. }
  31220. if ( renderer.autoClear || forceClear ) {
  31221. // buffers might not be writable which is required to ensure a correct clear
  31222. state.buffers.depth.setTest( true );
  31223. state.buffers.depth.setMask( true );
  31224. state.buffers.color.setMask( true );
  31225. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  31226. }
  31227. }
  31228. function addToRenderList( renderList, scene ) {
  31229. const background = getBackground( scene );
  31230. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  31231. if ( boxMesh === undefined ) {
  31232. boxMesh = new Mesh(
  31233. new BoxGeometry( 1, 1, 1 ),
  31234. new ShaderMaterial( {
  31235. name: 'BackgroundCubeMaterial',
  31236. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  31237. vertexShader: ShaderLib.backgroundCube.vertexShader,
  31238. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  31239. side: BackSide,
  31240. depthTest: false,
  31241. depthWrite: false,
  31242. fog: false
  31243. } )
  31244. );
  31245. boxMesh.geometry.deleteAttribute( 'normal' );
  31246. boxMesh.geometry.deleteAttribute( 'uv' );
  31247. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  31248. this.matrixWorld.copyPosition( camera.matrixWorld );
  31249. };
  31250. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  31251. Object.defineProperty( boxMesh.material, 'envMap', {
  31252. get: function () {
  31253. return this.uniforms.envMap.value;
  31254. }
  31255. } );
  31256. objects.update( boxMesh );
  31257. }
  31258. _e1$1.copy( scene.backgroundRotation );
  31259. // accommodate left-handed frame
  31260. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  31261. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  31262. // environment maps which are not cube render targets or PMREMs follow a different convention
  31263. _e1$1.y *= -1;
  31264. _e1$1.z *= -1;
  31265. }
  31266. boxMesh.material.uniforms.envMap.value = background;
  31267. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  31268. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  31269. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  31270. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  31271. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  31272. if ( currentBackground !== background ||
  31273. currentBackgroundVersion !== background.version ||
  31274. currentTonemapping !== renderer.toneMapping ) {
  31275. boxMesh.material.needsUpdate = true;
  31276. currentBackground = background;
  31277. currentBackgroundVersion = background.version;
  31278. currentTonemapping = renderer.toneMapping;
  31279. }
  31280. boxMesh.layers.enableAll();
  31281. // push to the pre-sorted opaque render list
  31282. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  31283. } else if ( background && background.isTexture ) {
  31284. if ( planeMesh === undefined ) {
  31285. planeMesh = new Mesh(
  31286. new PlaneGeometry( 2, 2 ),
  31287. new ShaderMaterial( {
  31288. name: 'BackgroundMaterial',
  31289. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  31290. vertexShader: ShaderLib.background.vertexShader,
  31291. fragmentShader: ShaderLib.background.fragmentShader,
  31292. side: FrontSide,
  31293. depthTest: false,
  31294. depthWrite: false,
  31295. fog: false
  31296. } )
  31297. );
  31298. planeMesh.geometry.deleteAttribute( 'normal' );
  31299. // add "map" material property so the renderer can evaluate it like for built-in materials
  31300. Object.defineProperty( planeMesh.material, 'map', {
  31301. get: function () {
  31302. return this.uniforms.t2D.value;
  31303. }
  31304. } );
  31305. objects.update( planeMesh );
  31306. }
  31307. planeMesh.material.uniforms.t2D.value = background;
  31308. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  31309. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  31310. if ( background.matrixAutoUpdate === true ) {
  31311. background.updateMatrix();
  31312. }
  31313. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  31314. if ( currentBackground !== background ||
  31315. currentBackgroundVersion !== background.version ||
  31316. currentTonemapping !== renderer.toneMapping ) {
  31317. planeMesh.material.needsUpdate = true;
  31318. currentBackground = background;
  31319. currentBackgroundVersion = background.version;
  31320. currentTonemapping = renderer.toneMapping;
  31321. }
  31322. planeMesh.layers.enableAll();
  31323. // push to the pre-sorted opaque render list
  31324. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  31325. }
  31326. }
  31327. function setClear( color, alpha ) {
  31328. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  31329. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  31330. }
  31331. function dispose() {
  31332. if ( boxMesh !== undefined ) {
  31333. boxMesh.geometry.dispose();
  31334. boxMesh.material.dispose();
  31335. boxMesh = undefined;
  31336. }
  31337. if ( planeMesh !== undefined ) {
  31338. planeMesh.geometry.dispose();
  31339. planeMesh.material.dispose();
  31340. planeMesh = undefined;
  31341. }
  31342. }
  31343. return {
  31344. getClearColor: function () {
  31345. return clearColor;
  31346. },
  31347. setClearColor: function ( color, alpha = 1 ) {
  31348. clearColor.set( color );
  31349. clearAlpha = alpha;
  31350. setClear( clearColor, clearAlpha );
  31351. },
  31352. getClearAlpha: function () {
  31353. return clearAlpha;
  31354. },
  31355. setClearAlpha: function ( alpha ) {
  31356. clearAlpha = alpha;
  31357. setClear( clearColor, clearAlpha );
  31358. },
  31359. render: render,
  31360. addToRenderList: addToRenderList,
  31361. dispose: dispose
  31362. };
  31363. }
  31364. function WebGLBindingStates( gl, attributes ) {
  31365. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  31366. const bindingStates = {};
  31367. const defaultState = createBindingState( null );
  31368. let currentState = defaultState;
  31369. let forceUpdate = false;
  31370. function setup( object, material, program, geometry, index ) {
  31371. let updateBuffers = false;
  31372. const state = getBindingState( geometry, program, material );
  31373. if ( currentState !== state ) {
  31374. currentState = state;
  31375. bindVertexArrayObject( currentState.object );
  31376. }
  31377. updateBuffers = needsUpdate( object, geometry, program, index );
  31378. if ( updateBuffers ) saveCache( object, geometry, program, index );
  31379. if ( index !== null ) {
  31380. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  31381. }
  31382. if ( updateBuffers || forceUpdate ) {
  31383. forceUpdate = false;
  31384. setupVertexAttributes( object, material, program, geometry );
  31385. if ( index !== null ) {
  31386. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  31387. }
  31388. }
  31389. }
  31390. function createVertexArrayObject() {
  31391. return gl.createVertexArray();
  31392. }
  31393. function bindVertexArrayObject( vao ) {
  31394. return gl.bindVertexArray( vao );
  31395. }
  31396. function deleteVertexArrayObject( vao ) {
  31397. return gl.deleteVertexArray( vao );
  31398. }
  31399. function getBindingState( geometry, program, material ) {
  31400. const wireframe = ( material.wireframe === true );
  31401. let programMap = bindingStates[ geometry.id ];
  31402. if ( programMap === undefined ) {
  31403. programMap = {};
  31404. bindingStates[ geometry.id ] = programMap;
  31405. }
  31406. let stateMap = programMap[ program.id ];
  31407. if ( stateMap === undefined ) {
  31408. stateMap = {};
  31409. programMap[ program.id ] = stateMap;
  31410. }
  31411. let state = stateMap[ wireframe ];
  31412. if ( state === undefined ) {
  31413. state = createBindingState( createVertexArrayObject() );
  31414. stateMap[ wireframe ] = state;
  31415. }
  31416. return state;
  31417. }
  31418. function createBindingState( vao ) {
  31419. const newAttributes = [];
  31420. const enabledAttributes = [];
  31421. const attributeDivisors = [];
  31422. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  31423. newAttributes[ i ] = 0;
  31424. enabledAttributes[ i ] = 0;
  31425. attributeDivisors[ i ] = 0;
  31426. }
  31427. return {
  31428. // for backward compatibility on non-VAO support browser
  31429. geometry: null,
  31430. program: null,
  31431. wireframe: false,
  31432. newAttributes: newAttributes,
  31433. enabledAttributes: enabledAttributes,
  31434. attributeDivisors: attributeDivisors,
  31435. object: vao,
  31436. attributes: {},
  31437. index: null
  31438. };
  31439. }
  31440. function needsUpdate( object, geometry, program, index ) {
  31441. const cachedAttributes = currentState.attributes;
  31442. const geometryAttributes = geometry.attributes;
  31443. let attributesNum = 0;
  31444. const programAttributes = program.getAttributes();
  31445. for ( const name in programAttributes ) {
  31446. const programAttribute = programAttributes[ name ];
  31447. if ( programAttribute.location >= 0 ) {
  31448. const cachedAttribute = cachedAttributes[ name ];
  31449. let geometryAttribute = geometryAttributes[ name ];
  31450. if ( geometryAttribute === undefined ) {
  31451. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  31452. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  31453. }
  31454. if ( cachedAttribute === undefined ) return true;
  31455. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  31456. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  31457. attributesNum ++;
  31458. }
  31459. }
  31460. if ( currentState.attributesNum !== attributesNum ) return true;
  31461. if ( currentState.index !== index ) return true;
  31462. return false;
  31463. }
  31464. function saveCache( object, geometry, program, index ) {
  31465. const cache = {};
  31466. const attributes = geometry.attributes;
  31467. let attributesNum = 0;
  31468. const programAttributes = program.getAttributes();
  31469. for ( const name in programAttributes ) {
  31470. const programAttribute = programAttributes[ name ];
  31471. if ( programAttribute.location >= 0 ) {
  31472. let attribute = attributes[ name ];
  31473. if ( attribute === undefined ) {
  31474. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  31475. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  31476. }
  31477. const data = {};
  31478. data.attribute = attribute;
  31479. if ( attribute && attribute.data ) {
  31480. data.data = attribute.data;
  31481. }
  31482. cache[ name ] = data;
  31483. attributesNum ++;
  31484. }
  31485. }
  31486. currentState.attributes = cache;
  31487. currentState.attributesNum = attributesNum;
  31488. currentState.index = index;
  31489. }
  31490. function initAttributes() {
  31491. const newAttributes = currentState.newAttributes;
  31492. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  31493. newAttributes[ i ] = 0;
  31494. }
  31495. }
  31496. function enableAttribute( attribute ) {
  31497. enableAttributeAndDivisor( attribute, 0 );
  31498. }
  31499. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  31500. const newAttributes = currentState.newAttributes;
  31501. const enabledAttributes = currentState.enabledAttributes;
  31502. const attributeDivisors = currentState.attributeDivisors;
  31503. newAttributes[ attribute ] = 1;
  31504. if ( enabledAttributes[ attribute ] === 0 ) {
  31505. gl.enableVertexAttribArray( attribute );
  31506. enabledAttributes[ attribute ] = 1;
  31507. }
  31508. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  31509. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  31510. attributeDivisors[ attribute ] = meshPerAttribute;
  31511. }
  31512. }
  31513. function disableUnusedAttributes() {
  31514. const newAttributes = currentState.newAttributes;
  31515. const enabledAttributes = currentState.enabledAttributes;
  31516. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  31517. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  31518. gl.disableVertexAttribArray( i );
  31519. enabledAttributes[ i ] = 0;
  31520. }
  31521. }
  31522. }
  31523. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  31524. if ( integer === true ) {
  31525. gl.vertexAttribIPointer( index, size, type, stride, offset );
  31526. } else {
  31527. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  31528. }
  31529. }
  31530. function setupVertexAttributes( object, material, program, geometry ) {
  31531. initAttributes();
  31532. const geometryAttributes = geometry.attributes;
  31533. const programAttributes = program.getAttributes();
  31534. const materialDefaultAttributeValues = material.defaultAttributeValues;
  31535. for ( const name in programAttributes ) {
  31536. const programAttribute = programAttributes[ name ];
  31537. if ( programAttribute.location >= 0 ) {
  31538. let geometryAttribute = geometryAttributes[ name ];
  31539. if ( geometryAttribute === undefined ) {
  31540. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  31541. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  31542. }
  31543. if ( geometryAttribute !== undefined ) {
  31544. const normalized = geometryAttribute.normalized;
  31545. const size = geometryAttribute.itemSize;
  31546. const attribute = attributes.get( geometryAttribute );
  31547. // TODO Attribute may not be available on context restore
  31548. if ( attribute === undefined ) continue;
  31549. const buffer = attribute.buffer;
  31550. const type = attribute.type;
  31551. const bytesPerElement = attribute.bytesPerElement;
  31552. // check for integer attributes
  31553. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  31554. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  31555. const data = geometryAttribute.data;
  31556. const stride = data.stride;
  31557. const offset = geometryAttribute.offset;
  31558. if ( data.isInstancedInterleavedBuffer ) {
  31559. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  31560. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  31561. }
  31562. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  31563. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  31564. }
  31565. } else {
  31566. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  31567. enableAttribute( programAttribute.location + i );
  31568. }
  31569. }
  31570. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  31571. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  31572. vertexAttribPointer(
  31573. programAttribute.location + i,
  31574. size / programAttribute.locationSize,
  31575. type,
  31576. normalized,
  31577. stride * bytesPerElement,
  31578. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  31579. integer
  31580. );
  31581. }
  31582. } else {
  31583. if ( geometryAttribute.isInstancedBufferAttribute ) {
  31584. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  31585. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  31586. }
  31587. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  31588. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  31589. }
  31590. } else {
  31591. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  31592. enableAttribute( programAttribute.location + i );
  31593. }
  31594. }
  31595. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  31596. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  31597. vertexAttribPointer(
  31598. programAttribute.location + i,
  31599. size / programAttribute.locationSize,
  31600. type,
  31601. normalized,
  31602. size * bytesPerElement,
  31603. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  31604. integer
  31605. );
  31606. }
  31607. }
  31608. } else if ( materialDefaultAttributeValues !== undefined ) {
  31609. const value = materialDefaultAttributeValues[ name ];
  31610. if ( value !== undefined ) {
  31611. switch ( value.length ) {
  31612. case 2:
  31613. gl.vertexAttrib2fv( programAttribute.location, value );
  31614. break;
  31615. case 3:
  31616. gl.vertexAttrib3fv( programAttribute.location, value );
  31617. break;
  31618. case 4:
  31619. gl.vertexAttrib4fv( programAttribute.location, value );
  31620. break;
  31621. default:
  31622. gl.vertexAttrib1fv( programAttribute.location, value );
  31623. }
  31624. }
  31625. }
  31626. }
  31627. }
  31628. disableUnusedAttributes();
  31629. }
  31630. function dispose() {
  31631. reset();
  31632. for ( const geometryId in bindingStates ) {
  31633. const programMap = bindingStates[ geometryId ];
  31634. for ( const programId in programMap ) {
  31635. const stateMap = programMap[ programId ];
  31636. for ( const wireframe in stateMap ) {
  31637. deleteVertexArrayObject( stateMap[ wireframe ].object );
  31638. delete stateMap[ wireframe ];
  31639. }
  31640. delete programMap[ programId ];
  31641. }
  31642. delete bindingStates[ geometryId ];
  31643. }
  31644. }
  31645. function releaseStatesOfGeometry( geometry ) {
  31646. if ( bindingStates[ geometry.id ] === undefined ) return;
  31647. const programMap = bindingStates[ geometry.id ];
  31648. for ( const programId in programMap ) {
  31649. const stateMap = programMap[ programId ];
  31650. for ( const wireframe in stateMap ) {
  31651. deleteVertexArrayObject( stateMap[ wireframe ].object );
  31652. delete stateMap[ wireframe ];
  31653. }
  31654. delete programMap[ programId ];
  31655. }
  31656. delete bindingStates[ geometry.id ];
  31657. }
  31658. function releaseStatesOfProgram( program ) {
  31659. for ( const geometryId in bindingStates ) {
  31660. const programMap = bindingStates[ geometryId ];
  31661. if ( programMap[ program.id ] === undefined ) continue;
  31662. const stateMap = programMap[ program.id ];
  31663. for ( const wireframe in stateMap ) {
  31664. deleteVertexArrayObject( stateMap[ wireframe ].object );
  31665. delete stateMap[ wireframe ];
  31666. }
  31667. delete programMap[ program.id ];
  31668. }
  31669. }
  31670. function reset() {
  31671. resetDefaultState();
  31672. forceUpdate = true;
  31673. if ( currentState === defaultState ) return;
  31674. currentState = defaultState;
  31675. bindVertexArrayObject( currentState.object );
  31676. }
  31677. // for backward-compatibility
  31678. function resetDefaultState() {
  31679. defaultState.geometry = null;
  31680. defaultState.program = null;
  31681. defaultState.wireframe = false;
  31682. }
  31683. return {
  31684. setup: setup,
  31685. reset: reset,
  31686. resetDefaultState: resetDefaultState,
  31687. dispose: dispose,
  31688. releaseStatesOfGeometry: releaseStatesOfGeometry,
  31689. releaseStatesOfProgram: releaseStatesOfProgram,
  31690. initAttributes: initAttributes,
  31691. enableAttribute: enableAttribute,
  31692. disableUnusedAttributes: disableUnusedAttributes
  31693. };
  31694. }
  31695. function WebGLBufferRenderer( gl, extensions, info ) {
  31696. let mode;
  31697. function setMode( value ) {
  31698. mode = value;
  31699. }
  31700. function render( start, count ) {
  31701. gl.drawArrays( mode, start, count );
  31702. info.update( count, mode, 1 );
  31703. }
  31704. function renderInstances( start, count, primcount ) {
  31705. if ( primcount === 0 ) return;
  31706. gl.drawArraysInstanced( mode, start, count, primcount );
  31707. info.update( count, mode, primcount );
  31708. }
  31709. function renderMultiDraw( starts, counts, drawCount ) {
  31710. if ( drawCount === 0 ) return;
  31711. const extension = extensions.get( 'WEBGL_multi_draw' );
  31712. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  31713. let elementCount = 0;
  31714. for ( let i = 0; i < drawCount; i ++ ) {
  31715. elementCount += counts[ i ];
  31716. }
  31717. info.update( elementCount, mode, 1 );
  31718. }
  31719. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  31720. if ( drawCount === 0 ) return;
  31721. const extension = extensions.get( 'WEBGL_multi_draw' );
  31722. if ( extension === null ) {
  31723. for ( let i = 0; i < starts.length; i ++ ) {
  31724. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  31725. }
  31726. } else {
  31727. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  31728. let elementCount = 0;
  31729. for ( let i = 0; i < drawCount; i ++ ) {
  31730. elementCount += counts[ i ] * primcount[ i ];
  31731. }
  31732. info.update( elementCount, mode, 1 );
  31733. }
  31734. }
  31735. //
  31736. this.setMode = setMode;
  31737. this.render = render;
  31738. this.renderInstances = renderInstances;
  31739. this.renderMultiDraw = renderMultiDraw;
  31740. this.renderMultiDrawInstances = renderMultiDrawInstances;
  31741. }
  31742. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  31743. let maxAnisotropy;
  31744. function getMaxAnisotropy() {
  31745. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  31746. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  31747. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  31748. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  31749. } else {
  31750. maxAnisotropy = 0;
  31751. }
  31752. return maxAnisotropy;
  31753. }
  31754. function textureFormatReadable( textureFormat ) {
  31755. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  31756. return false;
  31757. }
  31758. return true;
  31759. }
  31760. function textureTypeReadable( textureType ) {
  31761. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  31762. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  31763. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  31764. return false;
  31765. }
  31766. return true;
  31767. }
  31768. function getMaxPrecision( precision ) {
  31769. if ( precision === 'highp' ) {
  31770. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  31771. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  31772. return 'highp';
  31773. }
  31774. precision = 'mediump';
  31775. }
  31776. if ( precision === 'mediump' ) {
  31777. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  31778. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  31779. return 'mediump';
  31780. }
  31781. }
  31782. return 'lowp';
  31783. }
  31784. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  31785. const maxPrecision = getMaxPrecision( precision );
  31786. if ( maxPrecision !== precision ) {
  31787. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  31788. precision = maxPrecision;
  31789. }
  31790. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  31791. const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  31792. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  31793. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  31794. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  31795. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  31796. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  31797. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  31798. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  31799. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  31800. const vertexTextures = maxVertexTextures > 0;
  31801. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  31802. return {
  31803. isWebGL2: true, // keeping this for backwards compatibility
  31804. getMaxAnisotropy: getMaxAnisotropy,
  31805. getMaxPrecision: getMaxPrecision,
  31806. textureFormatReadable: textureFormatReadable,
  31807. textureTypeReadable: textureTypeReadable,
  31808. precision: precision,
  31809. logarithmicDepthBuffer: logarithmicDepthBuffer,
  31810. reverseDepthBuffer: reverseDepthBuffer,
  31811. maxTextures: maxTextures,
  31812. maxVertexTextures: maxVertexTextures,
  31813. maxTextureSize: maxTextureSize,
  31814. maxCubemapSize: maxCubemapSize,
  31815. maxAttributes: maxAttributes,
  31816. maxVertexUniforms: maxVertexUniforms,
  31817. maxVaryings: maxVaryings,
  31818. maxFragmentUniforms: maxFragmentUniforms,
  31819. vertexTextures: vertexTextures,
  31820. maxSamples: maxSamples
  31821. };
  31822. }
  31823. function WebGLClipping( properties ) {
  31824. const scope = this;
  31825. let globalState = null,
  31826. numGlobalPlanes = 0,
  31827. localClippingEnabled = false,
  31828. renderingShadows = false;
  31829. const plane = new Plane(),
  31830. viewNormalMatrix = new Matrix3(),
  31831. uniform = { value: null, needsUpdate: false };
  31832. this.uniform = uniform;
  31833. this.numPlanes = 0;
  31834. this.numIntersection = 0;
  31835. this.init = function ( planes, enableLocalClipping ) {
  31836. const enabled =
  31837. planes.length !== 0 ||
  31838. enableLocalClipping ||
  31839. // enable state of previous frame - the clipping code has to
  31840. // run another frame in order to reset the state:
  31841. numGlobalPlanes !== 0 ||
  31842. localClippingEnabled;
  31843. localClippingEnabled = enableLocalClipping;
  31844. numGlobalPlanes = planes.length;
  31845. return enabled;
  31846. };
  31847. this.beginShadows = function () {
  31848. renderingShadows = true;
  31849. projectPlanes( null );
  31850. };
  31851. this.endShadows = function () {
  31852. renderingShadows = false;
  31853. };
  31854. this.setGlobalState = function ( planes, camera ) {
  31855. globalState = projectPlanes( planes, camera, 0 );
  31856. };
  31857. this.setState = function ( material, camera, useCache ) {
  31858. const planes = material.clippingPlanes,
  31859. clipIntersection = material.clipIntersection,
  31860. clipShadows = material.clipShadows;
  31861. const materialProperties = properties.get( material );
  31862. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  31863. // there's no local clipping
  31864. if ( renderingShadows ) {
  31865. // there's no global clipping
  31866. projectPlanes( null );
  31867. } else {
  31868. resetGlobalState();
  31869. }
  31870. } else {
  31871. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  31872. lGlobal = nGlobal * 4;
  31873. let dstArray = materialProperties.clippingState || null;
  31874. uniform.value = dstArray; // ensure unique state
  31875. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  31876. for ( let i = 0; i !== lGlobal; ++ i ) {
  31877. dstArray[ i ] = globalState[ i ];
  31878. }
  31879. materialProperties.clippingState = dstArray;
  31880. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  31881. this.numPlanes += nGlobal;
  31882. }
  31883. };
  31884. function resetGlobalState() {
  31885. if ( uniform.value !== globalState ) {
  31886. uniform.value = globalState;
  31887. uniform.needsUpdate = numGlobalPlanes > 0;
  31888. }
  31889. scope.numPlanes = numGlobalPlanes;
  31890. scope.numIntersection = 0;
  31891. }
  31892. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  31893. const nPlanes = planes !== null ? planes.length : 0;
  31894. let dstArray = null;
  31895. if ( nPlanes !== 0 ) {
  31896. dstArray = uniform.value;
  31897. if ( skipTransform !== true || dstArray === null ) {
  31898. const flatSize = dstOffset + nPlanes * 4,
  31899. viewMatrix = camera.matrixWorldInverse;
  31900. viewNormalMatrix.getNormalMatrix( viewMatrix );
  31901. if ( dstArray === null || dstArray.length < flatSize ) {
  31902. dstArray = new Float32Array( flatSize );
  31903. }
  31904. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  31905. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  31906. plane.normal.toArray( dstArray, i4 );
  31907. dstArray[ i4 + 3 ] = plane.constant;
  31908. }
  31909. }
  31910. uniform.value = dstArray;
  31911. uniform.needsUpdate = true;
  31912. }
  31913. scope.numPlanes = nPlanes;
  31914. scope.numIntersection = 0;
  31915. return dstArray;
  31916. }
  31917. }
  31918. function WebGLCubeMaps( renderer ) {
  31919. let cubemaps = new WeakMap();
  31920. function mapTextureMapping( texture, mapping ) {
  31921. if ( mapping === EquirectangularReflectionMapping ) {
  31922. texture.mapping = CubeReflectionMapping;
  31923. } else if ( mapping === EquirectangularRefractionMapping ) {
  31924. texture.mapping = CubeRefractionMapping;
  31925. }
  31926. return texture;
  31927. }
  31928. function get( texture ) {
  31929. if ( texture && texture.isTexture ) {
  31930. const mapping = texture.mapping;
  31931. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  31932. if ( cubemaps.has( texture ) ) {
  31933. const cubemap = cubemaps.get( texture ).texture;
  31934. return mapTextureMapping( cubemap, texture.mapping );
  31935. } else {
  31936. const image = texture.image;
  31937. if ( image && image.height > 0 ) {
  31938. const renderTarget = new WebGLCubeRenderTarget( image.height );
  31939. renderTarget.fromEquirectangularTexture( renderer, texture );
  31940. cubemaps.set( texture, renderTarget );
  31941. texture.addEventListener( 'dispose', onTextureDispose );
  31942. return mapTextureMapping( renderTarget.texture, texture.mapping );
  31943. } else {
  31944. // image not yet ready. try the conversion next frame
  31945. return null;
  31946. }
  31947. }
  31948. }
  31949. }
  31950. return texture;
  31951. }
  31952. function onTextureDispose( event ) {
  31953. const texture = event.target;
  31954. texture.removeEventListener( 'dispose', onTextureDispose );
  31955. const cubemap = cubemaps.get( texture );
  31956. if ( cubemap !== undefined ) {
  31957. cubemaps.delete( texture );
  31958. cubemap.dispose();
  31959. }
  31960. }
  31961. function dispose() {
  31962. cubemaps = new WeakMap();
  31963. }
  31964. return {
  31965. get: get,
  31966. dispose: dispose
  31967. };
  31968. }
  31969. const LOD_MIN = 4;
  31970. // The standard deviations (radians) associated with the extra mips. These are
  31971. // chosen to approximate a Trowbridge-Reitz distribution function times the
  31972. // geometric shadowing function. These sigma values squared must match the
  31973. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  31974. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  31975. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  31976. // samples and exit early, but not recompile the shader.
  31977. const MAX_SAMPLES = 20;
  31978. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  31979. const _clearColor = /*@__PURE__*/ new Color();
  31980. let _oldTarget = null;
  31981. let _oldActiveCubeFace = 0;
  31982. let _oldActiveMipmapLevel = 0;
  31983. let _oldXrEnabled = false;
  31984. // Golden Ratio
  31985. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  31986. const INV_PHI = 1 / PHI;
  31987. // Vertices of a dodecahedron (except the opposites, which represent the
  31988. // same axis), used as axis directions evenly spread on a sphere.
  31989. const _axisDirections = [
  31990. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  31991. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  31992. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  31993. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  31994. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  31995. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  31996. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  31997. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  31998. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  31999. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  32000. const _origin = /*@__PURE__*/ new Vector3();
  32001. /**
  32002. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  32003. * (PMREM) from a cubeMap environment texture. This allows different levels of
  32004. * blur to be quickly accessed based on material roughness. It is packed into a
  32005. * special CubeUV format that allows us to perform custom interpolation so that
  32006. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  32007. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  32008. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  32009. * higher roughness levels. In this way we maintain resolution to smoothly
  32010. * interpolate diffuse lighting while limiting sampling computation.
  32011. *
  32012. * Paper: Fast, Accurate Image-Based Lighting
  32013. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  32014. */
  32015. class PMREMGenerator {
  32016. constructor( renderer ) {
  32017. this._renderer = renderer;
  32018. this._pingPongRenderTarget = null;
  32019. this._lodMax = 0;
  32020. this._cubeSize = 0;
  32021. this._lodPlanes = [];
  32022. this._sizeLods = [];
  32023. this._sigmas = [];
  32024. this._blurMaterial = null;
  32025. this._cubemapMaterial = null;
  32026. this._equirectMaterial = null;
  32027. this._compileMaterial( this._blurMaterial );
  32028. }
  32029. /**
  32030. * Generates a PMREM from a supplied Scene, which can be faster than using an
  32031. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  32032. * in radians to be applied to the scene before PMREM generation. Optional near
  32033. * and far planes ensure the scene is rendered in its entirety.
  32034. *
  32035. * @param {Scene} scene
  32036. * @param {number} sigma
  32037. * @param {number} near
  32038. * @param {number} far
  32039. * @param {?Object} [options={}]
  32040. * @return {WebGLRenderTarget}
  32041. */
  32042. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  32043. const {
  32044. size = 256,
  32045. position = _origin,
  32046. } = options;
  32047. _oldTarget = this._renderer.getRenderTarget();
  32048. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  32049. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  32050. _oldXrEnabled = this._renderer.xr.enabled;
  32051. this._renderer.xr.enabled = false;
  32052. this._setSize( size );
  32053. const cubeUVRenderTarget = this._allocateTargets();
  32054. cubeUVRenderTarget.depthBuffer = true;
  32055. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  32056. if ( sigma > 0 ) {
  32057. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  32058. }
  32059. this._applyPMREM( cubeUVRenderTarget );
  32060. this._cleanup( cubeUVRenderTarget );
  32061. return cubeUVRenderTarget;
  32062. }
  32063. /**
  32064. * Generates a PMREM from an equirectangular texture, which can be either LDR
  32065. * or HDR. The ideal input image size is 1k (1024 x 512),
  32066. * as this matches best with the 256 x 256 cubemap output.
  32067. * The smallest supported equirectangular image size is 64 x 32.
  32068. *
  32069. * @param {Texture} equirectangular
  32070. * @param {WebGLRenderTarget} [renderTarget=null] - Optional render target.
  32071. * @return {WebGLRenderTarget}
  32072. */
  32073. fromEquirectangular( equirectangular, renderTarget = null ) {
  32074. return this._fromTexture( equirectangular, renderTarget );
  32075. }
  32076. /**
  32077. * Generates a PMREM from an cubemap texture, which can be either LDR
  32078. * or HDR. The ideal input cube size is 256 x 256,
  32079. * as this matches best with the 256 x 256 cubemap output.
  32080. * The smallest supported cube size is 16 x 16.
  32081. *
  32082. * @param {Texture} cubemap
  32083. * @param {null} [renderTarget=null] - Optional render target.
  32084. * @return {WebGLRenderTarget}
  32085. */
  32086. fromCubemap( cubemap, renderTarget = null ) {
  32087. return this._fromTexture( cubemap, renderTarget );
  32088. }
  32089. /**
  32090. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  32091. * your texture's network fetch for increased concurrency.
  32092. */
  32093. compileCubemapShader() {
  32094. if ( this._cubemapMaterial === null ) {
  32095. this._cubemapMaterial = _getCubemapMaterial();
  32096. this._compileMaterial( this._cubemapMaterial );
  32097. }
  32098. }
  32099. /**
  32100. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  32101. * your texture's network fetch for increased concurrency.
  32102. */
  32103. compileEquirectangularShader() {
  32104. if ( this._equirectMaterial === null ) {
  32105. this._equirectMaterial = _getEquirectMaterial();
  32106. this._compileMaterial( this._equirectMaterial );
  32107. }
  32108. }
  32109. /**
  32110. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  32111. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  32112. * one of them will cause any others to also become unusable.
  32113. */
  32114. dispose() {
  32115. this._dispose();
  32116. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  32117. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  32118. }
  32119. // private interface
  32120. _setSize( cubeSize ) {
  32121. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  32122. this._cubeSize = Math.pow( 2, this._lodMax );
  32123. }
  32124. _dispose() {
  32125. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  32126. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  32127. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  32128. this._lodPlanes[ i ].dispose();
  32129. }
  32130. }
  32131. _cleanup( outputTarget ) {
  32132. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  32133. this._renderer.xr.enabled = _oldXrEnabled;
  32134. outputTarget.scissorTest = false;
  32135. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  32136. }
  32137. _fromTexture( texture, renderTarget ) {
  32138. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  32139. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  32140. } else { // Equirectangular
  32141. this._setSize( texture.image.width / 4 );
  32142. }
  32143. _oldTarget = this._renderer.getRenderTarget();
  32144. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  32145. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  32146. _oldXrEnabled = this._renderer.xr.enabled;
  32147. this._renderer.xr.enabled = false;
  32148. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  32149. this._textureToCubeUV( texture, cubeUVRenderTarget );
  32150. this._applyPMREM( cubeUVRenderTarget );
  32151. this._cleanup( cubeUVRenderTarget );
  32152. return cubeUVRenderTarget;
  32153. }
  32154. _allocateTargets() {
  32155. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  32156. const height = 4 * this._cubeSize;
  32157. const params = {
  32158. magFilter: LinearFilter,
  32159. minFilter: LinearFilter,
  32160. generateMipmaps: false,
  32161. type: HalfFloatType,
  32162. format: RGBAFormat,
  32163. colorSpace: LinearSRGBColorSpace,
  32164. depthBuffer: false
  32165. };
  32166. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  32167. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  32168. if ( this._pingPongRenderTarget !== null ) {
  32169. this._dispose();
  32170. }
  32171. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  32172. const { _lodMax } = this;
  32173. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  32174. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  32175. }
  32176. return cubeUVRenderTarget;
  32177. }
  32178. _compileMaterial( material ) {
  32179. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  32180. this._renderer.compile( tmpMesh, _flatCamera );
  32181. }
  32182. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  32183. const fov = 90;
  32184. const aspect = 1;
  32185. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  32186. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  32187. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  32188. const renderer = this._renderer;
  32189. const originalAutoClear = renderer.autoClear;
  32190. const toneMapping = renderer.toneMapping;
  32191. renderer.getClearColor( _clearColor );
  32192. renderer.toneMapping = NoToneMapping;
  32193. renderer.autoClear = false;
  32194. const backgroundMaterial = new MeshBasicMaterial( {
  32195. name: 'PMREM.Background',
  32196. side: BackSide,
  32197. depthWrite: false,
  32198. depthTest: false,
  32199. } );
  32200. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  32201. let useSolidColor = false;
  32202. const background = scene.background;
  32203. if ( background ) {
  32204. if ( background.isColor ) {
  32205. backgroundMaterial.color.copy( background );
  32206. scene.background = null;
  32207. useSolidColor = true;
  32208. }
  32209. } else {
  32210. backgroundMaterial.color.copy( _clearColor );
  32211. useSolidColor = true;
  32212. }
  32213. for ( let i = 0; i < 6; i ++ ) {
  32214. const col = i % 3;
  32215. if ( col === 0 ) {
  32216. cubeCamera.up.set( 0, upSign[ i ], 0 );
  32217. cubeCamera.position.set( position.x, position.y, position.z );
  32218. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  32219. } else if ( col === 1 ) {
  32220. cubeCamera.up.set( 0, 0, upSign[ i ] );
  32221. cubeCamera.position.set( position.x, position.y, position.z );
  32222. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  32223. } else {
  32224. cubeCamera.up.set( 0, upSign[ i ], 0 );
  32225. cubeCamera.position.set( position.x, position.y, position.z );
  32226. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  32227. }
  32228. const size = this._cubeSize;
  32229. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  32230. renderer.setRenderTarget( cubeUVRenderTarget );
  32231. if ( useSolidColor ) {
  32232. renderer.render( backgroundBox, cubeCamera );
  32233. }
  32234. renderer.render( scene, cubeCamera );
  32235. }
  32236. backgroundBox.geometry.dispose();
  32237. backgroundBox.material.dispose();
  32238. renderer.toneMapping = toneMapping;
  32239. renderer.autoClear = originalAutoClear;
  32240. scene.background = background;
  32241. }
  32242. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  32243. const renderer = this._renderer;
  32244. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  32245. if ( isCubeTexture ) {
  32246. if ( this._cubemapMaterial === null ) {
  32247. this._cubemapMaterial = _getCubemapMaterial();
  32248. }
  32249. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  32250. } else {
  32251. if ( this._equirectMaterial === null ) {
  32252. this._equirectMaterial = _getEquirectMaterial();
  32253. }
  32254. }
  32255. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  32256. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  32257. const uniforms = material.uniforms;
  32258. uniforms[ 'envMap' ].value = texture;
  32259. const size = this._cubeSize;
  32260. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  32261. renderer.setRenderTarget( cubeUVRenderTarget );
  32262. renderer.render( mesh, _flatCamera );
  32263. }
  32264. _applyPMREM( cubeUVRenderTarget ) {
  32265. const renderer = this._renderer;
  32266. const autoClear = renderer.autoClear;
  32267. renderer.autoClear = false;
  32268. const n = this._lodPlanes.length;
  32269. for ( let i = 1; i < n; i ++ ) {
  32270. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  32271. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  32272. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  32273. }
  32274. renderer.autoClear = autoClear;
  32275. }
  32276. /**
  32277. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  32278. * vertically and horizontally, but this breaks down on a cube. Here we apply
  32279. * the blur latitudinally (around the poles), and then longitudinally (towards
  32280. * the poles) to approximate the orthogonally-separable blur. It is least
  32281. * accurate at the poles, but still does a decent job.
  32282. *
  32283. * @param {WebGLRenderTarget} cubeUVRenderTarget
  32284. * @param {number} lodIn
  32285. * @param {number} lodOut
  32286. * @param {number} sigma
  32287. * @param {Vector3} [poleAxis]
  32288. */
  32289. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  32290. const pingPongRenderTarget = this._pingPongRenderTarget;
  32291. this._halfBlur(
  32292. cubeUVRenderTarget,
  32293. pingPongRenderTarget,
  32294. lodIn,
  32295. lodOut,
  32296. sigma,
  32297. 'latitudinal',
  32298. poleAxis );
  32299. this._halfBlur(
  32300. pingPongRenderTarget,
  32301. cubeUVRenderTarget,
  32302. lodOut,
  32303. lodOut,
  32304. sigma,
  32305. 'longitudinal',
  32306. poleAxis );
  32307. }
  32308. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  32309. const renderer = this._renderer;
  32310. const blurMaterial = this._blurMaterial;
  32311. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  32312. console.error(
  32313. 'blur direction must be either latitudinal or longitudinal!' );
  32314. }
  32315. // Number of standard deviations at which to cut off the discrete approximation.
  32316. const STANDARD_DEVIATIONS = 3;
  32317. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  32318. const blurUniforms = blurMaterial.uniforms;
  32319. const pixels = this._sizeLods[ lodIn ] - 1;
  32320. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  32321. const sigmaPixels = sigmaRadians / radiansPerPixel;
  32322. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  32323. if ( samples > MAX_SAMPLES ) {
  32324. console.warn( `sigmaRadians, ${
  32325. sigmaRadians}, is too large and will clip, as it requested ${
  32326. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  32327. }
  32328. const weights = [];
  32329. let sum = 0;
  32330. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  32331. const x = i / sigmaPixels;
  32332. const weight = Math.exp( - x * x / 2 );
  32333. weights.push( weight );
  32334. if ( i === 0 ) {
  32335. sum += weight;
  32336. } else if ( i < samples ) {
  32337. sum += 2 * weight;
  32338. }
  32339. }
  32340. for ( let i = 0; i < weights.length; i ++ ) {
  32341. weights[ i ] = weights[ i ] / sum;
  32342. }
  32343. blurUniforms[ 'envMap' ].value = targetIn.texture;
  32344. blurUniforms[ 'samples' ].value = samples;
  32345. blurUniforms[ 'weights' ].value = weights;
  32346. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  32347. if ( poleAxis ) {
  32348. blurUniforms[ 'poleAxis' ].value = poleAxis;
  32349. }
  32350. const { _lodMax } = this;
  32351. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  32352. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  32353. const outputSize = this._sizeLods[ lodOut ];
  32354. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  32355. const y = 4 * ( this._cubeSize - outputSize );
  32356. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  32357. renderer.setRenderTarget( targetOut );
  32358. renderer.render( blurMesh, _flatCamera );
  32359. }
  32360. }
  32361. function _createPlanes( lodMax ) {
  32362. const lodPlanes = [];
  32363. const sizeLods = [];
  32364. const sigmas = [];
  32365. let lod = lodMax;
  32366. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  32367. for ( let i = 0; i < totalLods; i ++ ) {
  32368. const sizeLod = Math.pow( 2, lod );
  32369. sizeLods.push( sizeLod );
  32370. let sigma = 1.0 / sizeLod;
  32371. if ( i > lodMax - LOD_MIN ) {
  32372. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  32373. } else if ( i === 0 ) {
  32374. sigma = 0;
  32375. }
  32376. sigmas.push( sigma );
  32377. const texelSize = 1.0 / ( sizeLod - 2 );
  32378. const min = - texelSize;
  32379. const max = 1 + texelSize;
  32380. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  32381. const cubeFaces = 6;
  32382. const vertices = 6;
  32383. const positionSize = 3;
  32384. const uvSize = 2;
  32385. const faceIndexSize = 1;
  32386. const position = new Float32Array( positionSize * vertices * cubeFaces );
  32387. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  32388. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  32389. for ( let face = 0; face < cubeFaces; face ++ ) {
  32390. const x = ( face % 3 ) * 2 / 3 - 1;
  32391. const y = face > 2 ? 0 : -1;
  32392. const coordinates = [
  32393. x, y, 0,
  32394. x + 2 / 3, y, 0,
  32395. x + 2 / 3, y + 1, 0,
  32396. x, y, 0,
  32397. x + 2 / 3, y + 1, 0,
  32398. x, y + 1, 0
  32399. ];
  32400. position.set( coordinates, positionSize * vertices * face );
  32401. uv.set( uv1, uvSize * vertices * face );
  32402. const fill = [ face, face, face, face, face, face ];
  32403. faceIndex.set( fill, faceIndexSize * vertices * face );
  32404. }
  32405. const planes = new BufferGeometry();
  32406. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  32407. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  32408. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  32409. lodPlanes.push( planes );
  32410. if ( lod > LOD_MIN ) {
  32411. lod --;
  32412. }
  32413. }
  32414. return { lodPlanes, sizeLods, sigmas };
  32415. }
  32416. function _createRenderTarget( width, height, params ) {
  32417. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  32418. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  32419. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  32420. cubeUVRenderTarget.scissorTest = true;
  32421. return cubeUVRenderTarget;
  32422. }
  32423. function _setViewport( target, x, y, width, height ) {
  32424. target.viewport.set( x, y, width, height );
  32425. target.scissor.set( x, y, width, height );
  32426. }
  32427. function _getBlurShader( lodMax, width, height ) {
  32428. const weights = new Float32Array( MAX_SAMPLES );
  32429. const poleAxis = new Vector3( 0, 1, 0 );
  32430. const shaderMaterial = new ShaderMaterial( {
  32431. name: 'SphericalGaussianBlur',
  32432. defines: {
  32433. 'n': MAX_SAMPLES,
  32434. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  32435. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  32436. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  32437. },
  32438. uniforms: {
  32439. 'envMap': { value: null },
  32440. 'samples': { value: 1 },
  32441. 'weights': { value: weights },
  32442. 'latitudinal': { value: false },
  32443. 'dTheta': { value: 0 },
  32444. 'mipInt': { value: 0 },
  32445. 'poleAxis': { value: poleAxis }
  32446. },
  32447. vertexShader: _getCommonVertexShader(),
  32448. fragmentShader: /* glsl */`
  32449. precision mediump float;
  32450. precision mediump int;
  32451. varying vec3 vOutputDirection;
  32452. uniform sampler2D envMap;
  32453. uniform int samples;
  32454. uniform float weights[ n ];
  32455. uniform bool latitudinal;
  32456. uniform float dTheta;
  32457. uniform float mipInt;
  32458. uniform vec3 poleAxis;
  32459. #define ENVMAP_TYPE_CUBE_UV
  32460. #include <cube_uv_reflection_fragment>
  32461. vec3 getSample( float theta, vec3 axis ) {
  32462. float cosTheta = cos( theta );
  32463. // Rodrigues' axis-angle rotation
  32464. vec3 sampleDirection = vOutputDirection * cosTheta
  32465. + cross( axis, vOutputDirection ) * sin( theta )
  32466. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  32467. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  32468. }
  32469. void main() {
  32470. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  32471. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  32472. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  32473. }
  32474. axis = normalize( axis );
  32475. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  32476. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  32477. for ( int i = 1; i < n; i++ ) {
  32478. if ( i >= samples ) {
  32479. break;
  32480. }
  32481. float theta = dTheta * float( i );
  32482. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  32483. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  32484. }
  32485. }
  32486. `,
  32487. blending: NoBlending,
  32488. depthTest: false,
  32489. depthWrite: false
  32490. } );
  32491. return shaderMaterial;
  32492. }
  32493. function _getEquirectMaterial() {
  32494. return new ShaderMaterial( {
  32495. name: 'EquirectangularToCubeUV',
  32496. uniforms: {
  32497. 'envMap': { value: null }
  32498. },
  32499. vertexShader: _getCommonVertexShader(),
  32500. fragmentShader: /* glsl */`
  32501. precision mediump float;
  32502. precision mediump int;
  32503. varying vec3 vOutputDirection;
  32504. uniform sampler2D envMap;
  32505. #include <common>
  32506. void main() {
  32507. vec3 outputDirection = normalize( vOutputDirection );
  32508. vec2 uv = equirectUv( outputDirection );
  32509. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  32510. }
  32511. `,
  32512. blending: NoBlending,
  32513. depthTest: false,
  32514. depthWrite: false
  32515. } );
  32516. }
  32517. function _getCubemapMaterial() {
  32518. return new ShaderMaterial( {
  32519. name: 'CubemapToCubeUV',
  32520. uniforms: {
  32521. 'envMap': { value: null },
  32522. 'flipEnvMap': { value: -1 }
  32523. },
  32524. vertexShader: _getCommonVertexShader(),
  32525. fragmentShader: /* glsl */`
  32526. precision mediump float;
  32527. precision mediump int;
  32528. uniform float flipEnvMap;
  32529. varying vec3 vOutputDirection;
  32530. uniform samplerCube envMap;
  32531. void main() {
  32532. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  32533. }
  32534. `,
  32535. blending: NoBlending,
  32536. depthTest: false,
  32537. depthWrite: false
  32538. } );
  32539. }
  32540. function _getCommonVertexShader() {
  32541. return /* glsl */`
  32542. precision mediump float;
  32543. precision mediump int;
  32544. attribute float faceIndex;
  32545. varying vec3 vOutputDirection;
  32546. // RH coordinate system; PMREM face-indexing convention
  32547. vec3 getDirection( vec2 uv, float face ) {
  32548. uv = 2.0 * uv - 1.0;
  32549. vec3 direction = vec3( uv, 1.0 );
  32550. if ( face == 0.0 ) {
  32551. direction = direction.zyx; // ( 1, v, u ) pos x
  32552. } else if ( face == 1.0 ) {
  32553. direction = direction.xzy;
  32554. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  32555. } else if ( face == 2.0 ) {
  32556. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  32557. } else if ( face == 3.0 ) {
  32558. direction = direction.zyx;
  32559. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  32560. } else if ( face == 4.0 ) {
  32561. direction = direction.xzy;
  32562. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  32563. } else if ( face == 5.0 ) {
  32564. direction.z *= -1.0; // ( u, v, -1 ) neg z
  32565. }
  32566. return direction;
  32567. }
  32568. void main() {
  32569. vOutputDirection = getDirection( uv, faceIndex );
  32570. gl_Position = vec4( position, 1.0 );
  32571. }
  32572. `;
  32573. }
  32574. function WebGLCubeUVMaps( renderer ) {
  32575. let cubeUVmaps = new WeakMap();
  32576. let pmremGenerator = null;
  32577. function get( texture ) {
  32578. if ( texture && texture.isTexture ) {
  32579. const mapping = texture.mapping;
  32580. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  32581. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  32582. // equirect/cube map to cubeUV conversion
  32583. if ( isEquirectMap || isCubeMap ) {
  32584. let renderTarget = cubeUVmaps.get( texture );
  32585. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  32586. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  32587. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  32588. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  32589. renderTarget.texture.pmremVersion = texture.pmremVersion;
  32590. cubeUVmaps.set( texture, renderTarget );
  32591. return renderTarget.texture;
  32592. } else {
  32593. if ( renderTarget !== undefined ) {
  32594. return renderTarget.texture;
  32595. } else {
  32596. const image = texture.image;
  32597. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  32598. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  32599. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  32600. renderTarget.texture.pmremVersion = texture.pmremVersion;
  32601. cubeUVmaps.set( texture, renderTarget );
  32602. texture.addEventListener( 'dispose', onTextureDispose );
  32603. return renderTarget.texture;
  32604. } else {
  32605. // image not yet ready. try the conversion next frame
  32606. return null;
  32607. }
  32608. }
  32609. }
  32610. }
  32611. }
  32612. return texture;
  32613. }
  32614. function isCubeTextureComplete( image ) {
  32615. let count = 0;
  32616. const length = 6;
  32617. for ( let i = 0; i < length; i ++ ) {
  32618. if ( image[ i ] !== undefined ) count ++;
  32619. }
  32620. return count === length;
  32621. }
  32622. function onTextureDispose( event ) {
  32623. const texture = event.target;
  32624. texture.removeEventListener( 'dispose', onTextureDispose );
  32625. const cubemapUV = cubeUVmaps.get( texture );
  32626. if ( cubemapUV !== undefined ) {
  32627. cubeUVmaps.delete( texture );
  32628. cubemapUV.dispose();
  32629. }
  32630. }
  32631. function dispose() {
  32632. cubeUVmaps = new WeakMap();
  32633. if ( pmremGenerator !== null ) {
  32634. pmremGenerator.dispose();
  32635. pmremGenerator = null;
  32636. }
  32637. }
  32638. return {
  32639. get: get,
  32640. dispose: dispose
  32641. };
  32642. }
  32643. function WebGLExtensions( gl ) {
  32644. const extensions = {};
  32645. function getExtension( name ) {
  32646. if ( extensions[ name ] !== undefined ) {
  32647. return extensions[ name ];
  32648. }
  32649. let extension;
  32650. switch ( name ) {
  32651. case 'WEBGL_depth_texture':
  32652. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  32653. break;
  32654. case 'EXT_texture_filter_anisotropic':
  32655. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  32656. break;
  32657. case 'WEBGL_compressed_texture_s3tc':
  32658. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  32659. break;
  32660. case 'WEBGL_compressed_texture_pvrtc':
  32661. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  32662. break;
  32663. default:
  32664. extension = gl.getExtension( name );
  32665. }
  32666. extensions[ name ] = extension;
  32667. return extension;
  32668. }
  32669. return {
  32670. has: function ( name ) {
  32671. return getExtension( name ) !== null;
  32672. },
  32673. init: function () {
  32674. getExtension( 'EXT_color_buffer_float' );
  32675. getExtension( 'WEBGL_clip_cull_distance' );
  32676. getExtension( 'OES_texture_float_linear' );
  32677. getExtension( 'EXT_color_buffer_half_float' );
  32678. getExtension( 'WEBGL_multisampled_render_to_texture' );
  32679. getExtension( 'WEBGL_render_shared_exponent' );
  32680. },
  32681. get: function ( name ) {
  32682. const extension = getExtension( name );
  32683. if ( extension === null ) {
  32684. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  32685. }
  32686. return extension;
  32687. }
  32688. };
  32689. }
  32690. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  32691. const geometries = {};
  32692. const wireframeAttributes = new WeakMap();
  32693. function onGeometryDispose( event ) {
  32694. const geometry = event.target;
  32695. if ( geometry.index !== null ) {
  32696. attributes.remove( geometry.index );
  32697. }
  32698. for ( const name in geometry.attributes ) {
  32699. attributes.remove( geometry.attributes[ name ] );
  32700. }
  32701. geometry.removeEventListener( 'dispose', onGeometryDispose );
  32702. delete geometries[ geometry.id ];
  32703. const attribute = wireframeAttributes.get( geometry );
  32704. if ( attribute ) {
  32705. attributes.remove( attribute );
  32706. wireframeAttributes.delete( geometry );
  32707. }
  32708. bindingStates.releaseStatesOfGeometry( geometry );
  32709. if ( geometry.isInstancedBufferGeometry === true ) {
  32710. delete geometry._maxInstanceCount;
  32711. }
  32712. //
  32713. info.memory.geometries --;
  32714. }
  32715. function get( object, geometry ) {
  32716. if ( geometries[ geometry.id ] === true ) return geometry;
  32717. geometry.addEventListener( 'dispose', onGeometryDispose );
  32718. geometries[ geometry.id ] = true;
  32719. info.memory.geometries ++;
  32720. return geometry;
  32721. }
  32722. function update( geometry ) {
  32723. const geometryAttributes = geometry.attributes;
  32724. // Updating index buffer in VAO now. See WebGLBindingStates.
  32725. for ( const name in geometryAttributes ) {
  32726. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  32727. }
  32728. }
  32729. function updateWireframeAttribute( geometry ) {
  32730. const indices = [];
  32731. const geometryIndex = geometry.index;
  32732. const geometryPosition = geometry.attributes.position;
  32733. let version = 0;
  32734. if ( geometryIndex !== null ) {
  32735. const array = geometryIndex.array;
  32736. version = geometryIndex.version;
  32737. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  32738. const a = array[ i + 0 ];
  32739. const b = array[ i + 1 ];
  32740. const c = array[ i + 2 ];
  32741. indices.push( a, b, b, c, c, a );
  32742. }
  32743. } else if ( geometryPosition !== undefined ) {
  32744. const array = geometryPosition.array;
  32745. version = geometryPosition.version;
  32746. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  32747. const a = i + 0;
  32748. const b = i + 1;
  32749. const c = i + 2;
  32750. indices.push( a, b, b, c, c, a );
  32751. }
  32752. } else {
  32753. return;
  32754. }
  32755. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  32756. attribute.version = version;
  32757. // Updating index buffer in VAO now. See WebGLBindingStates
  32758. //
  32759. const previousAttribute = wireframeAttributes.get( geometry );
  32760. if ( previousAttribute ) attributes.remove( previousAttribute );
  32761. //
  32762. wireframeAttributes.set( geometry, attribute );
  32763. }
  32764. function getWireframeAttribute( geometry ) {
  32765. const currentAttribute = wireframeAttributes.get( geometry );
  32766. if ( currentAttribute ) {
  32767. const geometryIndex = geometry.index;
  32768. if ( geometryIndex !== null ) {
  32769. // if the attribute is obsolete, create a new one
  32770. if ( currentAttribute.version < geometryIndex.version ) {
  32771. updateWireframeAttribute( geometry );
  32772. }
  32773. }
  32774. } else {
  32775. updateWireframeAttribute( geometry );
  32776. }
  32777. return wireframeAttributes.get( geometry );
  32778. }
  32779. return {
  32780. get: get,
  32781. update: update,
  32782. getWireframeAttribute: getWireframeAttribute
  32783. };
  32784. }
  32785. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  32786. let mode;
  32787. function setMode( value ) {
  32788. mode = value;
  32789. }
  32790. let type, bytesPerElement;
  32791. function setIndex( value ) {
  32792. type = value.type;
  32793. bytesPerElement = value.bytesPerElement;
  32794. }
  32795. function render( start, count ) {
  32796. gl.drawElements( mode, count, type, start * bytesPerElement );
  32797. info.update( count, mode, 1 );
  32798. }
  32799. function renderInstances( start, count, primcount ) {
  32800. if ( primcount === 0 ) return;
  32801. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  32802. info.update( count, mode, primcount );
  32803. }
  32804. function renderMultiDraw( starts, counts, drawCount ) {
  32805. if ( drawCount === 0 ) return;
  32806. const extension = extensions.get( 'WEBGL_multi_draw' );
  32807. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  32808. let elementCount = 0;
  32809. for ( let i = 0; i < drawCount; i ++ ) {
  32810. elementCount += counts[ i ];
  32811. }
  32812. info.update( elementCount, mode, 1 );
  32813. }
  32814. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  32815. if ( drawCount === 0 ) return;
  32816. const extension = extensions.get( 'WEBGL_multi_draw' );
  32817. if ( extension === null ) {
  32818. for ( let i = 0; i < starts.length; i ++ ) {
  32819. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  32820. }
  32821. } else {
  32822. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  32823. let elementCount = 0;
  32824. for ( let i = 0; i < drawCount; i ++ ) {
  32825. elementCount += counts[ i ] * primcount[ i ];
  32826. }
  32827. info.update( elementCount, mode, 1 );
  32828. }
  32829. }
  32830. //
  32831. this.setMode = setMode;
  32832. this.setIndex = setIndex;
  32833. this.render = render;
  32834. this.renderInstances = renderInstances;
  32835. this.renderMultiDraw = renderMultiDraw;
  32836. this.renderMultiDrawInstances = renderMultiDrawInstances;
  32837. }
  32838. function WebGLInfo( gl ) {
  32839. const memory = {
  32840. geometries: 0,
  32841. textures: 0
  32842. };
  32843. const render = {
  32844. frame: 0,
  32845. calls: 0,
  32846. triangles: 0,
  32847. points: 0,
  32848. lines: 0
  32849. };
  32850. function update( count, mode, instanceCount ) {
  32851. render.calls ++;
  32852. switch ( mode ) {
  32853. case gl.TRIANGLES:
  32854. render.triangles += instanceCount * ( count / 3 );
  32855. break;
  32856. case gl.LINES:
  32857. render.lines += instanceCount * ( count / 2 );
  32858. break;
  32859. case gl.LINE_STRIP:
  32860. render.lines += instanceCount * ( count - 1 );
  32861. break;
  32862. case gl.LINE_LOOP:
  32863. render.lines += instanceCount * count;
  32864. break;
  32865. case gl.POINTS:
  32866. render.points += instanceCount * count;
  32867. break;
  32868. default:
  32869. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  32870. break;
  32871. }
  32872. }
  32873. function reset() {
  32874. render.calls = 0;
  32875. render.triangles = 0;
  32876. render.points = 0;
  32877. render.lines = 0;
  32878. }
  32879. return {
  32880. memory: memory,
  32881. render: render,
  32882. programs: null,
  32883. autoReset: true,
  32884. reset: reset,
  32885. update: update
  32886. };
  32887. }
  32888. function WebGLMorphtargets( gl, capabilities, textures ) {
  32889. const morphTextures = new WeakMap();
  32890. const morph = new Vector4();
  32891. function update( object, geometry, program ) {
  32892. const objectInfluences = object.morphTargetInfluences;
  32893. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  32894. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  32895. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  32896. let entry = morphTextures.get( geometry );
  32897. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  32898. if ( entry !== undefined ) entry.texture.dispose();
  32899. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  32900. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  32901. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  32902. const morphTargets = geometry.morphAttributes.position || [];
  32903. const morphNormals = geometry.morphAttributes.normal || [];
  32904. const morphColors = geometry.morphAttributes.color || [];
  32905. let vertexDataCount = 0;
  32906. if ( hasMorphPosition === true ) vertexDataCount = 1;
  32907. if ( hasMorphNormals === true ) vertexDataCount = 2;
  32908. if ( hasMorphColors === true ) vertexDataCount = 3;
  32909. let width = geometry.attributes.position.count * vertexDataCount;
  32910. let height = 1;
  32911. if ( width > capabilities.maxTextureSize ) {
  32912. height = Math.ceil( width / capabilities.maxTextureSize );
  32913. width = capabilities.maxTextureSize;
  32914. }
  32915. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  32916. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  32917. texture.type = FloatType;
  32918. texture.needsUpdate = true;
  32919. // fill buffer
  32920. const vertexDataStride = vertexDataCount * 4;
  32921. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  32922. const morphTarget = morphTargets[ i ];
  32923. const morphNormal = morphNormals[ i ];
  32924. const morphColor = morphColors[ i ];
  32925. const offset = width * height * 4 * i;
  32926. for ( let j = 0; j < morphTarget.count; j ++ ) {
  32927. const stride = j * vertexDataStride;
  32928. if ( hasMorphPosition === true ) {
  32929. morph.fromBufferAttribute( morphTarget, j );
  32930. buffer[ offset + stride + 0 ] = morph.x;
  32931. buffer[ offset + stride + 1 ] = morph.y;
  32932. buffer[ offset + stride + 2 ] = morph.z;
  32933. buffer[ offset + stride + 3 ] = 0;
  32934. }
  32935. if ( hasMorphNormals === true ) {
  32936. morph.fromBufferAttribute( morphNormal, j );
  32937. buffer[ offset + stride + 4 ] = morph.x;
  32938. buffer[ offset + stride + 5 ] = morph.y;
  32939. buffer[ offset + stride + 6 ] = morph.z;
  32940. buffer[ offset + stride + 7 ] = 0;
  32941. }
  32942. if ( hasMorphColors === true ) {
  32943. morph.fromBufferAttribute( morphColor, j );
  32944. buffer[ offset + stride + 8 ] = morph.x;
  32945. buffer[ offset + stride + 9 ] = morph.y;
  32946. buffer[ offset + stride + 10 ] = morph.z;
  32947. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  32948. }
  32949. }
  32950. }
  32951. entry = {
  32952. count: morphTargetsCount,
  32953. texture: texture,
  32954. size: new Vector2( width, height )
  32955. };
  32956. morphTextures.set( geometry, entry );
  32957. function disposeTexture() {
  32958. texture.dispose();
  32959. morphTextures.delete( geometry );
  32960. geometry.removeEventListener( 'dispose', disposeTexture );
  32961. }
  32962. geometry.addEventListener( 'dispose', disposeTexture );
  32963. }
  32964. //
  32965. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  32966. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  32967. } else {
  32968. let morphInfluencesSum = 0;
  32969. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  32970. morphInfluencesSum += objectInfluences[ i ];
  32971. }
  32972. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  32973. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  32974. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  32975. }
  32976. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  32977. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  32978. }
  32979. return {
  32980. update: update
  32981. };
  32982. }
  32983. function WebGLObjects( gl, geometries, attributes, info ) {
  32984. let updateMap = new WeakMap();
  32985. function update( object ) {
  32986. const frame = info.render.frame;
  32987. const geometry = object.geometry;
  32988. const buffergeometry = geometries.get( object, geometry );
  32989. // Update once per frame
  32990. if ( updateMap.get( buffergeometry ) !== frame ) {
  32991. geometries.update( buffergeometry );
  32992. updateMap.set( buffergeometry, frame );
  32993. }
  32994. if ( object.isInstancedMesh ) {
  32995. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  32996. object.addEventListener( 'dispose', onInstancedMeshDispose );
  32997. }
  32998. if ( updateMap.get( object ) !== frame ) {
  32999. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  33000. if ( object.instanceColor !== null ) {
  33001. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  33002. }
  33003. updateMap.set( object, frame );
  33004. }
  33005. }
  33006. if ( object.isSkinnedMesh ) {
  33007. const skeleton = object.skeleton;
  33008. if ( updateMap.get( skeleton ) !== frame ) {
  33009. skeleton.update();
  33010. updateMap.set( skeleton, frame );
  33011. }
  33012. }
  33013. return buffergeometry;
  33014. }
  33015. function dispose() {
  33016. updateMap = new WeakMap();
  33017. }
  33018. function onInstancedMeshDispose( event ) {
  33019. const instancedMesh = event.target;
  33020. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  33021. attributes.remove( instancedMesh.instanceMatrix );
  33022. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  33023. }
  33024. return {
  33025. update: update,
  33026. dispose: dispose
  33027. };
  33028. }
  33029. /**
  33030. * Uniforms of a program.
  33031. * Those form a tree structure with a special top-level container for the root,
  33032. * which you get by calling 'new WebGLUniforms( gl, program )'.
  33033. *
  33034. *
  33035. * Properties of inner nodes including the top-level container:
  33036. *
  33037. * .seq - array of nested uniforms
  33038. * .map - nested uniforms by name
  33039. *
  33040. *
  33041. * Methods of all nodes except the top-level container:
  33042. *
  33043. * .setValue( gl, value, [textures] )
  33044. *
  33045. * uploads a uniform value(s)
  33046. * the 'textures' parameter is needed for sampler uniforms
  33047. *
  33048. *
  33049. * Static methods of the top-level container (textures factorizations):
  33050. *
  33051. * .upload( gl, seq, values, textures )
  33052. *
  33053. * sets uniforms in 'seq' to 'values[id].value'
  33054. *
  33055. * .seqWithValue( seq, values ) : filteredSeq
  33056. *
  33057. * filters 'seq' entries with corresponding entry in values
  33058. *
  33059. *
  33060. * Methods of the top-level container (textures factorizations):
  33061. *
  33062. * .setValue( gl, name, value, textures )
  33063. *
  33064. * sets uniform with name 'name' to 'value'
  33065. *
  33066. * .setOptional( gl, obj, prop )
  33067. *
  33068. * like .set for an optional property of the object
  33069. *
  33070. */
  33071. const emptyTexture = /*@__PURE__*/ new Texture();
  33072. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  33073. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  33074. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  33075. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  33076. // --- Utilities ---
  33077. // Array Caches (provide typed arrays for temporary by size)
  33078. const arrayCacheF32 = [];
  33079. const arrayCacheI32 = [];
  33080. // Float32Array caches used for uploading Matrix uniforms
  33081. const mat4array = new Float32Array( 16 );
  33082. const mat3array = new Float32Array( 9 );
  33083. const mat2array = new Float32Array( 4 );
  33084. // Flattening for arrays of vectors and matrices
  33085. function flatten( array, nBlocks, blockSize ) {
  33086. const firstElem = array[ 0 ];
  33087. if ( firstElem <= 0 || firstElem > 0 ) return array;
  33088. // unoptimized: ! isNaN( firstElem )
  33089. // see http://jacksondunstan.com/articles/983
  33090. const n = nBlocks * blockSize;
  33091. let r = arrayCacheF32[ n ];
  33092. if ( r === undefined ) {
  33093. r = new Float32Array( n );
  33094. arrayCacheF32[ n ] = r;
  33095. }
  33096. if ( nBlocks !== 0 ) {
  33097. firstElem.toArray( r, 0 );
  33098. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  33099. offset += blockSize;
  33100. array[ i ].toArray( r, offset );
  33101. }
  33102. }
  33103. return r;
  33104. }
  33105. function arraysEqual( a, b ) {
  33106. if ( a.length !== b.length ) return false;
  33107. for ( let i = 0, l = a.length; i < l; i ++ ) {
  33108. if ( a[ i ] !== b[ i ] ) return false;
  33109. }
  33110. return true;
  33111. }
  33112. function copyArray( a, b ) {
  33113. for ( let i = 0, l = b.length; i < l; i ++ ) {
  33114. a[ i ] = b[ i ];
  33115. }
  33116. }
  33117. // Texture unit allocation
  33118. function allocTexUnits( textures, n ) {
  33119. let r = arrayCacheI32[ n ];
  33120. if ( r === undefined ) {
  33121. r = new Int32Array( n );
  33122. arrayCacheI32[ n ] = r;
  33123. }
  33124. for ( let i = 0; i !== n; ++ i ) {
  33125. r[ i ] = textures.allocateTextureUnit();
  33126. }
  33127. return r;
  33128. }
  33129. // --- Setters ---
  33130. // Note: Defining these methods externally, because they come in a bunch
  33131. // and this way their names minify.
  33132. // Single scalar
  33133. function setValueV1f( gl, v ) {
  33134. const cache = this.cache;
  33135. if ( cache[ 0 ] === v ) return;
  33136. gl.uniform1f( this.addr, v );
  33137. cache[ 0 ] = v;
  33138. }
  33139. // Single float vector (from flat array or THREE.VectorN)
  33140. function setValueV2f( gl, v ) {
  33141. const cache = this.cache;
  33142. if ( v.x !== undefined ) {
  33143. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  33144. gl.uniform2f( this.addr, v.x, v.y );
  33145. cache[ 0 ] = v.x;
  33146. cache[ 1 ] = v.y;
  33147. }
  33148. } else {
  33149. if ( arraysEqual( cache, v ) ) return;
  33150. gl.uniform2fv( this.addr, v );
  33151. copyArray( cache, v );
  33152. }
  33153. }
  33154. function setValueV3f( gl, v ) {
  33155. const cache = this.cache;
  33156. if ( v.x !== undefined ) {
  33157. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  33158. gl.uniform3f( this.addr, v.x, v.y, v.z );
  33159. cache[ 0 ] = v.x;
  33160. cache[ 1 ] = v.y;
  33161. cache[ 2 ] = v.z;
  33162. }
  33163. } else if ( v.r !== undefined ) {
  33164. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  33165. gl.uniform3f( this.addr, v.r, v.g, v.b );
  33166. cache[ 0 ] = v.r;
  33167. cache[ 1 ] = v.g;
  33168. cache[ 2 ] = v.b;
  33169. }
  33170. } else {
  33171. if ( arraysEqual( cache, v ) ) return;
  33172. gl.uniform3fv( this.addr, v );
  33173. copyArray( cache, v );
  33174. }
  33175. }
  33176. function setValueV4f( gl, v ) {
  33177. const cache = this.cache;
  33178. if ( v.x !== undefined ) {
  33179. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  33180. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  33181. cache[ 0 ] = v.x;
  33182. cache[ 1 ] = v.y;
  33183. cache[ 2 ] = v.z;
  33184. cache[ 3 ] = v.w;
  33185. }
  33186. } else {
  33187. if ( arraysEqual( cache, v ) ) return;
  33188. gl.uniform4fv( this.addr, v );
  33189. copyArray( cache, v );
  33190. }
  33191. }
  33192. // Single matrix (from flat array or THREE.MatrixN)
  33193. function setValueM2( gl, v ) {
  33194. const cache = this.cache;
  33195. const elements = v.elements;
  33196. if ( elements === undefined ) {
  33197. if ( arraysEqual( cache, v ) ) return;
  33198. gl.uniformMatrix2fv( this.addr, false, v );
  33199. copyArray( cache, v );
  33200. } else {
  33201. if ( arraysEqual( cache, elements ) ) return;
  33202. mat2array.set( elements );
  33203. gl.uniformMatrix2fv( this.addr, false, mat2array );
  33204. copyArray( cache, elements );
  33205. }
  33206. }
  33207. function setValueM3( gl, v ) {
  33208. const cache = this.cache;
  33209. const elements = v.elements;
  33210. if ( elements === undefined ) {
  33211. if ( arraysEqual( cache, v ) ) return;
  33212. gl.uniformMatrix3fv( this.addr, false, v );
  33213. copyArray( cache, v );
  33214. } else {
  33215. if ( arraysEqual( cache, elements ) ) return;
  33216. mat3array.set( elements );
  33217. gl.uniformMatrix3fv( this.addr, false, mat3array );
  33218. copyArray( cache, elements );
  33219. }
  33220. }
  33221. function setValueM4( gl, v ) {
  33222. const cache = this.cache;
  33223. const elements = v.elements;
  33224. if ( elements === undefined ) {
  33225. if ( arraysEqual( cache, v ) ) return;
  33226. gl.uniformMatrix4fv( this.addr, false, v );
  33227. copyArray( cache, v );
  33228. } else {
  33229. if ( arraysEqual( cache, elements ) ) return;
  33230. mat4array.set( elements );
  33231. gl.uniformMatrix4fv( this.addr, false, mat4array );
  33232. copyArray( cache, elements );
  33233. }
  33234. }
  33235. // Single integer / boolean
  33236. function setValueV1i( gl, v ) {
  33237. const cache = this.cache;
  33238. if ( cache[ 0 ] === v ) return;
  33239. gl.uniform1i( this.addr, v );
  33240. cache[ 0 ] = v;
  33241. }
  33242. // Single integer / boolean vector (from flat array or THREE.VectorN)
  33243. function setValueV2i( gl, v ) {
  33244. const cache = this.cache;
  33245. if ( v.x !== undefined ) {
  33246. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  33247. gl.uniform2i( this.addr, v.x, v.y );
  33248. cache[ 0 ] = v.x;
  33249. cache[ 1 ] = v.y;
  33250. }
  33251. } else {
  33252. if ( arraysEqual( cache, v ) ) return;
  33253. gl.uniform2iv( this.addr, v );
  33254. copyArray( cache, v );
  33255. }
  33256. }
  33257. function setValueV3i( gl, v ) {
  33258. const cache = this.cache;
  33259. if ( v.x !== undefined ) {
  33260. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  33261. gl.uniform3i( this.addr, v.x, v.y, v.z );
  33262. cache[ 0 ] = v.x;
  33263. cache[ 1 ] = v.y;
  33264. cache[ 2 ] = v.z;
  33265. }
  33266. } else {
  33267. if ( arraysEqual( cache, v ) ) return;
  33268. gl.uniform3iv( this.addr, v );
  33269. copyArray( cache, v );
  33270. }
  33271. }
  33272. function setValueV4i( gl, v ) {
  33273. const cache = this.cache;
  33274. if ( v.x !== undefined ) {
  33275. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  33276. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  33277. cache[ 0 ] = v.x;
  33278. cache[ 1 ] = v.y;
  33279. cache[ 2 ] = v.z;
  33280. cache[ 3 ] = v.w;
  33281. }
  33282. } else {
  33283. if ( arraysEqual( cache, v ) ) return;
  33284. gl.uniform4iv( this.addr, v );
  33285. copyArray( cache, v );
  33286. }
  33287. }
  33288. // Single unsigned integer
  33289. function setValueV1ui( gl, v ) {
  33290. const cache = this.cache;
  33291. if ( cache[ 0 ] === v ) return;
  33292. gl.uniform1ui( this.addr, v );
  33293. cache[ 0 ] = v;
  33294. }
  33295. // Single unsigned integer vector (from flat array or THREE.VectorN)
  33296. function setValueV2ui( gl, v ) {
  33297. const cache = this.cache;
  33298. if ( v.x !== undefined ) {
  33299. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  33300. gl.uniform2ui( this.addr, v.x, v.y );
  33301. cache[ 0 ] = v.x;
  33302. cache[ 1 ] = v.y;
  33303. }
  33304. } else {
  33305. if ( arraysEqual( cache, v ) ) return;
  33306. gl.uniform2uiv( this.addr, v );
  33307. copyArray( cache, v );
  33308. }
  33309. }
  33310. function setValueV3ui( gl, v ) {
  33311. const cache = this.cache;
  33312. if ( v.x !== undefined ) {
  33313. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  33314. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  33315. cache[ 0 ] = v.x;
  33316. cache[ 1 ] = v.y;
  33317. cache[ 2 ] = v.z;
  33318. }
  33319. } else {
  33320. if ( arraysEqual( cache, v ) ) return;
  33321. gl.uniform3uiv( this.addr, v );
  33322. copyArray( cache, v );
  33323. }
  33324. }
  33325. function setValueV4ui( gl, v ) {
  33326. const cache = this.cache;
  33327. if ( v.x !== undefined ) {
  33328. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  33329. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  33330. cache[ 0 ] = v.x;
  33331. cache[ 1 ] = v.y;
  33332. cache[ 2 ] = v.z;
  33333. cache[ 3 ] = v.w;
  33334. }
  33335. } else {
  33336. if ( arraysEqual( cache, v ) ) return;
  33337. gl.uniform4uiv( this.addr, v );
  33338. copyArray( cache, v );
  33339. }
  33340. }
  33341. // Single texture (2D / Cube)
  33342. function setValueT1( gl, v, textures ) {
  33343. const cache = this.cache;
  33344. const unit = textures.allocateTextureUnit();
  33345. if ( cache[ 0 ] !== unit ) {
  33346. gl.uniform1i( this.addr, unit );
  33347. cache[ 0 ] = unit;
  33348. }
  33349. let emptyTexture2D;
  33350. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  33351. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  33352. emptyTexture2D = emptyShadowTexture;
  33353. } else {
  33354. emptyTexture2D = emptyTexture;
  33355. }
  33356. textures.setTexture2D( v || emptyTexture2D, unit );
  33357. }
  33358. function setValueT3D1( gl, v, textures ) {
  33359. const cache = this.cache;
  33360. const unit = textures.allocateTextureUnit();
  33361. if ( cache[ 0 ] !== unit ) {
  33362. gl.uniform1i( this.addr, unit );
  33363. cache[ 0 ] = unit;
  33364. }
  33365. textures.setTexture3D( v || empty3dTexture, unit );
  33366. }
  33367. function setValueT6( gl, v, textures ) {
  33368. const cache = this.cache;
  33369. const unit = textures.allocateTextureUnit();
  33370. if ( cache[ 0 ] !== unit ) {
  33371. gl.uniform1i( this.addr, unit );
  33372. cache[ 0 ] = unit;
  33373. }
  33374. textures.setTextureCube( v || emptyCubeTexture, unit );
  33375. }
  33376. function setValueT2DArray1( gl, v, textures ) {
  33377. const cache = this.cache;
  33378. const unit = textures.allocateTextureUnit();
  33379. if ( cache[ 0 ] !== unit ) {
  33380. gl.uniform1i( this.addr, unit );
  33381. cache[ 0 ] = unit;
  33382. }
  33383. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  33384. }
  33385. // Helper to pick the right setter for the singular case
  33386. function getSingularSetter( type ) {
  33387. switch ( type ) {
  33388. case 0x1406: return setValueV1f; // FLOAT
  33389. case 0x8b50: return setValueV2f; // _VEC2
  33390. case 0x8b51: return setValueV3f; // _VEC3
  33391. case 0x8b52: return setValueV4f; // _VEC4
  33392. case 0x8b5a: return setValueM2; // _MAT2
  33393. case 0x8b5b: return setValueM3; // _MAT3
  33394. case 0x8b5c: return setValueM4; // _MAT4
  33395. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  33396. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  33397. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  33398. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  33399. case 0x1405: return setValueV1ui; // UINT
  33400. case 0x8dc6: return setValueV2ui; // _VEC2
  33401. case 0x8dc7: return setValueV3ui; // _VEC3
  33402. case 0x8dc8: return setValueV4ui; // _VEC4
  33403. case 0x8b5e: // SAMPLER_2D
  33404. case 0x8d66: // SAMPLER_EXTERNAL_OES
  33405. case 0x8dca: // INT_SAMPLER_2D
  33406. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  33407. case 0x8b62: // SAMPLER_2D_SHADOW
  33408. return setValueT1;
  33409. case 0x8b5f: // SAMPLER_3D
  33410. case 0x8dcb: // INT_SAMPLER_3D
  33411. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  33412. return setValueT3D1;
  33413. case 0x8b60: // SAMPLER_CUBE
  33414. case 0x8dcc: // INT_SAMPLER_CUBE
  33415. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  33416. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  33417. return setValueT6;
  33418. case 0x8dc1: // SAMPLER_2D_ARRAY
  33419. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  33420. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  33421. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  33422. return setValueT2DArray1;
  33423. }
  33424. }
  33425. // Array of scalars
  33426. function setValueV1fArray( gl, v ) {
  33427. gl.uniform1fv( this.addr, v );
  33428. }
  33429. // Array of vectors (from flat array or array of THREE.VectorN)
  33430. function setValueV2fArray( gl, v ) {
  33431. const data = flatten( v, this.size, 2 );
  33432. gl.uniform2fv( this.addr, data );
  33433. }
  33434. function setValueV3fArray( gl, v ) {
  33435. const data = flatten( v, this.size, 3 );
  33436. gl.uniform3fv( this.addr, data );
  33437. }
  33438. function setValueV4fArray( gl, v ) {
  33439. const data = flatten( v, this.size, 4 );
  33440. gl.uniform4fv( this.addr, data );
  33441. }
  33442. // Array of matrices (from flat array or array of THREE.MatrixN)
  33443. function setValueM2Array( gl, v ) {
  33444. const data = flatten( v, this.size, 4 );
  33445. gl.uniformMatrix2fv( this.addr, false, data );
  33446. }
  33447. function setValueM3Array( gl, v ) {
  33448. const data = flatten( v, this.size, 9 );
  33449. gl.uniformMatrix3fv( this.addr, false, data );
  33450. }
  33451. function setValueM4Array( gl, v ) {
  33452. const data = flatten( v, this.size, 16 );
  33453. gl.uniformMatrix4fv( this.addr, false, data );
  33454. }
  33455. // Array of integer / boolean
  33456. function setValueV1iArray( gl, v ) {
  33457. gl.uniform1iv( this.addr, v );
  33458. }
  33459. // Array of integer / boolean vectors (from flat array)
  33460. function setValueV2iArray( gl, v ) {
  33461. gl.uniform2iv( this.addr, v );
  33462. }
  33463. function setValueV3iArray( gl, v ) {
  33464. gl.uniform3iv( this.addr, v );
  33465. }
  33466. function setValueV4iArray( gl, v ) {
  33467. gl.uniform4iv( this.addr, v );
  33468. }
  33469. // Array of unsigned integer
  33470. function setValueV1uiArray( gl, v ) {
  33471. gl.uniform1uiv( this.addr, v );
  33472. }
  33473. // Array of unsigned integer vectors (from flat array)
  33474. function setValueV2uiArray( gl, v ) {
  33475. gl.uniform2uiv( this.addr, v );
  33476. }
  33477. function setValueV3uiArray( gl, v ) {
  33478. gl.uniform3uiv( this.addr, v );
  33479. }
  33480. function setValueV4uiArray( gl, v ) {
  33481. gl.uniform4uiv( this.addr, v );
  33482. }
  33483. // Array of textures (2D / 3D / Cube / 2DArray)
  33484. function setValueT1Array( gl, v, textures ) {
  33485. const cache = this.cache;
  33486. const n = v.length;
  33487. const units = allocTexUnits( textures, n );
  33488. if ( ! arraysEqual( cache, units ) ) {
  33489. gl.uniform1iv( this.addr, units );
  33490. copyArray( cache, units );
  33491. }
  33492. for ( let i = 0; i !== n; ++ i ) {
  33493. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  33494. }
  33495. }
  33496. function setValueT3DArray( gl, v, textures ) {
  33497. const cache = this.cache;
  33498. const n = v.length;
  33499. const units = allocTexUnits( textures, n );
  33500. if ( ! arraysEqual( cache, units ) ) {
  33501. gl.uniform1iv( this.addr, units );
  33502. copyArray( cache, units );
  33503. }
  33504. for ( let i = 0; i !== n; ++ i ) {
  33505. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  33506. }
  33507. }
  33508. function setValueT6Array( gl, v, textures ) {
  33509. const cache = this.cache;
  33510. const n = v.length;
  33511. const units = allocTexUnits( textures, n );
  33512. if ( ! arraysEqual( cache, units ) ) {
  33513. gl.uniform1iv( this.addr, units );
  33514. copyArray( cache, units );
  33515. }
  33516. for ( let i = 0; i !== n; ++ i ) {
  33517. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  33518. }
  33519. }
  33520. function setValueT2DArrayArray( gl, v, textures ) {
  33521. const cache = this.cache;
  33522. const n = v.length;
  33523. const units = allocTexUnits( textures, n );
  33524. if ( ! arraysEqual( cache, units ) ) {
  33525. gl.uniform1iv( this.addr, units );
  33526. copyArray( cache, units );
  33527. }
  33528. for ( let i = 0; i !== n; ++ i ) {
  33529. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  33530. }
  33531. }
  33532. // Helper to pick the right setter for a pure (bottom-level) array
  33533. function getPureArraySetter( type ) {
  33534. switch ( type ) {
  33535. case 0x1406: return setValueV1fArray; // FLOAT
  33536. case 0x8b50: return setValueV2fArray; // _VEC2
  33537. case 0x8b51: return setValueV3fArray; // _VEC3
  33538. case 0x8b52: return setValueV4fArray; // _VEC4
  33539. case 0x8b5a: return setValueM2Array; // _MAT2
  33540. case 0x8b5b: return setValueM3Array; // _MAT3
  33541. case 0x8b5c: return setValueM4Array; // _MAT4
  33542. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  33543. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  33544. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  33545. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  33546. case 0x1405: return setValueV1uiArray; // UINT
  33547. case 0x8dc6: return setValueV2uiArray; // _VEC2
  33548. case 0x8dc7: return setValueV3uiArray; // _VEC3
  33549. case 0x8dc8: return setValueV4uiArray; // _VEC4
  33550. case 0x8b5e: // SAMPLER_2D
  33551. case 0x8d66: // SAMPLER_EXTERNAL_OES
  33552. case 0x8dca: // INT_SAMPLER_2D
  33553. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  33554. case 0x8b62: // SAMPLER_2D_SHADOW
  33555. return setValueT1Array;
  33556. case 0x8b5f: // SAMPLER_3D
  33557. case 0x8dcb: // INT_SAMPLER_3D
  33558. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  33559. return setValueT3DArray;
  33560. case 0x8b60: // SAMPLER_CUBE
  33561. case 0x8dcc: // INT_SAMPLER_CUBE
  33562. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  33563. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  33564. return setValueT6Array;
  33565. case 0x8dc1: // SAMPLER_2D_ARRAY
  33566. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  33567. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  33568. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  33569. return setValueT2DArrayArray;
  33570. }
  33571. }
  33572. // --- Uniform Classes ---
  33573. class SingleUniform {
  33574. constructor( id, activeInfo, addr ) {
  33575. this.id = id;
  33576. this.addr = addr;
  33577. this.cache = [];
  33578. this.type = activeInfo.type;
  33579. this.setValue = getSingularSetter( activeInfo.type );
  33580. // this.path = activeInfo.name; // DEBUG
  33581. }
  33582. }
  33583. class PureArrayUniform {
  33584. constructor( id, activeInfo, addr ) {
  33585. this.id = id;
  33586. this.addr = addr;
  33587. this.cache = [];
  33588. this.type = activeInfo.type;
  33589. this.size = activeInfo.size;
  33590. this.setValue = getPureArraySetter( activeInfo.type );
  33591. // this.path = activeInfo.name; // DEBUG
  33592. }
  33593. }
  33594. class StructuredUniform {
  33595. constructor( id ) {
  33596. this.id = id;
  33597. this.seq = [];
  33598. this.map = {};
  33599. }
  33600. setValue( gl, value, textures ) {
  33601. const seq = this.seq;
  33602. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  33603. const u = seq[ i ];
  33604. u.setValue( gl, value[ u.id ], textures );
  33605. }
  33606. }
  33607. }
  33608. // --- Top-level ---
  33609. // Parser - builds up the property tree from the path strings
  33610. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  33611. // extracts
  33612. // - the identifier (member name or array index)
  33613. // - followed by an optional right bracket (found when array index)
  33614. // - followed by an optional left bracket or dot (type of subscript)
  33615. //
  33616. // Note: These portions can be read in a non-overlapping fashion and
  33617. // allow straightforward parsing of the hierarchy that WebGL encodes
  33618. // in the uniform names.
  33619. function addUniform( container, uniformObject ) {
  33620. container.seq.push( uniformObject );
  33621. container.map[ uniformObject.id ] = uniformObject;
  33622. }
  33623. function parseUniform( activeInfo, addr, container ) {
  33624. const path = activeInfo.name,
  33625. pathLength = path.length;
  33626. // reset RegExp object, because of the early exit of a previous run
  33627. RePathPart.lastIndex = 0;
  33628. while ( true ) {
  33629. const match = RePathPart.exec( path ),
  33630. matchEnd = RePathPart.lastIndex;
  33631. let id = match[ 1 ];
  33632. const idIsIndex = match[ 2 ] === ']',
  33633. subscript = match[ 3 ];
  33634. if ( idIsIndex ) id = id | 0; // convert to integer
  33635. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  33636. // bare name or "pure" bottom-level array "[0]" suffix
  33637. addUniform( container, subscript === undefined ?
  33638. new SingleUniform( id, activeInfo, addr ) :
  33639. new PureArrayUniform( id, activeInfo, addr ) );
  33640. break;
  33641. } else {
  33642. // step into inner node / create it in case it doesn't exist
  33643. const map = container.map;
  33644. let next = map[ id ];
  33645. if ( next === undefined ) {
  33646. next = new StructuredUniform( id );
  33647. addUniform( container, next );
  33648. }
  33649. container = next;
  33650. }
  33651. }
  33652. }
  33653. // Root Container
  33654. class WebGLUniforms {
  33655. constructor( gl, program ) {
  33656. this.seq = [];
  33657. this.map = {};
  33658. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  33659. for ( let i = 0; i < n; ++ i ) {
  33660. const info = gl.getActiveUniform( program, i ),
  33661. addr = gl.getUniformLocation( program, info.name );
  33662. parseUniform( info, addr, this );
  33663. }
  33664. }
  33665. setValue( gl, name, value, textures ) {
  33666. const u = this.map[ name ];
  33667. if ( u !== undefined ) u.setValue( gl, value, textures );
  33668. }
  33669. setOptional( gl, object, name ) {
  33670. const v = object[ name ];
  33671. if ( v !== undefined ) this.setValue( gl, name, v );
  33672. }
  33673. static upload( gl, seq, values, textures ) {
  33674. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  33675. const u = seq[ i ],
  33676. v = values[ u.id ];
  33677. if ( v.needsUpdate !== false ) {
  33678. // note: always updating when .needsUpdate is undefined
  33679. u.setValue( gl, v.value, textures );
  33680. }
  33681. }
  33682. }
  33683. static seqWithValue( seq, values ) {
  33684. const r = [];
  33685. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  33686. const u = seq[ i ];
  33687. if ( u.id in values ) r.push( u );
  33688. }
  33689. return r;
  33690. }
  33691. }
  33692. function WebGLShader( gl, type, string ) {
  33693. const shader = gl.createShader( type );
  33694. gl.shaderSource( shader, string );
  33695. gl.compileShader( shader );
  33696. return shader;
  33697. }
  33698. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  33699. const COMPLETION_STATUS_KHR = 0x91B1;
  33700. let programIdCount = 0;
  33701. function handleSource( string, errorLine ) {
  33702. const lines = string.split( '\n' );
  33703. const lines2 = [];
  33704. const from = Math.max( errorLine - 6, 0 );
  33705. const to = Math.min( errorLine + 6, lines.length );
  33706. for ( let i = from; i < to; i ++ ) {
  33707. const line = i + 1;
  33708. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  33709. }
  33710. return lines2.join( '\n' );
  33711. }
  33712. const _m0 = /*@__PURE__*/ new Matrix3();
  33713. function getEncodingComponents( colorSpace ) {
  33714. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  33715. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  33716. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  33717. case LinearTransfer:
  33718. return [ encodingMatrix, 'LinearTransferOETF' ];
  33719. case SRGBTransfer:
  33720. return [ encodingMatrix, 'sRGBTransferOETF' ];
  33721. default:
  33722. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  33723. return [ encodingMatrix, 'LinearTransferOETF' ];
  33724. }
  33725. }
  33726. function getShaderErrors( gl, shader, type ) {
  33727. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  33728. const errors = gl.getShaderInfoLog( shader ).trim();
  33729. if ( status && errors === '' ) return '';
  33730. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  33731. if ( errorMatches ) {
  33732. // --enable-privileged-webgl-extension
  33733. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  33734. const errorLine = parseInt( errorMatches[ 1 ] );
  33735. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  33736. } else {
  33737. return errors;
  33738. }
  33739. }
  33740. function getTexelEncodingFunction( functionName, colorSpace ) {
  33741. const components = getEncodingComponents( colorSpace );
  33742. return [
  33743. `vec4 ${functionName}( vec4 value ) {`,
  33744. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  33745. '}',
  33746. ].join( '\n' );
  33747. }
  33748. function getToneMappingFunction( functionName, toneMapping ) {
  33749. let toneMappingName;
  33750. switch ( toneMapping ) {
  33751. case LinearToneMapping:
  33752. toneMappingName = 'Linear';
  33753. break;
  33754. case ReinhardToneMapping:
  33755. toneMappingName = 'Reinhard';
  33756. break;
  33757. case CineonToneMapping:
  33758. toneMappingName = 'Cineon';
  33759. break;
  33760. case ACESFilmicToneMapping:
  33761. toneMappingName = 'ACESFilmic';
  33762. break;
  33763. case AgXToneMapping:
  33764. toneMappingName = 'AgX';
  33765. break;
  33766. case NeutralToneMapping:
  33767. toneMappingName = 'Neutral';
  33768. break;
  33769. case CustomToneMapping:
  33770. toneMappingName = 'Custom';
  33771. break;
  33772. default:
  33773. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  33774. toneMappingName = 'Linear';
  33775. }
  33776. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  33777. }
  33778. const _v0 = /*@__PURE__*/ new Vector3();
  33779. function getLuminanceFunction() {
  33780. ColorManagement.getLuminanceCoefficients( _v0 );
  33781. const r = _v0.x.toFixed( 4 );
  33782. const g = _v0.y.toFixed( 4 );
  33783. const b = _v0.z.toFixed( 4 );
  33784. return [
  33785. 'float luminance( const in vec3 rgb ) {',
  33786. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  33787. ' return dot( weights, rgb );',
  33788. '}'
  33789. ].join( '\n' );
  33790. }
  33791. function generateVertexExtensions( parameters ) {
  33792. const chunks = [
  33793. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  33794. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  33795. ];
  33796. return chunks.filter( filterEmptyLine ).join( '\n' );
  33797. }
  33798. function generateDefines( defines ) {
  33799. const chunks = [];
  33800. for ( const name in defines ) {
  33801. const value = defines[ name ];
  33802. if ( value === false ) continue;
  33803. chunks.push( '#define ' + name + ' ' + value );
  33804. }
  33805. return chunks.join( '\n' );
  33806. }
  33807. function fetchAttributeLocations( gl, program ) {
  33808. const attributes = {};
  33809. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  33810. for ( let i = 0; i < n; i ++ ) {
  33811. const info = gl.getActiveAttrib( program, i );
  33812. const name = info.name;
  33813. let locationSize = 1;
  33814. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  33815. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  33816. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  33817. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  33818. attributes[ name ] = {
  33819. type: info.type,
  33820. location: gl.getAttribLocation( program, name ),
  33821. locationSize: locationSize
  33822. };
  33823. }
  33824. return attributes;
  33825. }
  33826. function filterEmptyLine( string ) {
  33827. return string !== '';
  33828. }
  33829. function replaceLightNums( string, parameters ) {
  33830. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  33831. return string
  33832. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  33833. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  33834. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  33835. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  33836. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  33837. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  33838. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  33839. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  33840. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  33841. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  33842. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  33843. }
  33844. function replaceClippingPlaneNums( string, parameters ) {
  33845. return string
  33846. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  33847. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  33848. }
  33849. // Resolve Includes
  33850. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  33851. function resolveIncludes( string ) {
  33852. return string.replace( includePattern, includeReplacer );
  33853. }
  33854. const shaderChunkMap = new Map();
  33855. function includeReplacer( match, include ) {
  33856. let string = ShaderChunk[ include ];
  33857. if ( string === undefined ) {
  33858. const newInclude = shaderChunkMap.get( include );
  33859. if ( newInclude !== undefined ) {
  33860. string = ShaderChunk[ newInclude ];
  33861. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  33862. } else {
  33863. throw new Error( 'Can not resolve #include <' + include + '>' );
  33864. }
  33865. }
  33866. return resolveIncludes( string );
  33867. }
  33868. // Unroll Loops
  33869. 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;
  33870. function unrollLoops( string ) {
  33871. return string.replace( unrollLoopPattern, loopReplacer );
  33872. }
  33873. function loopReplacer( match, start, end, snippet ) {
  33874. let string = '';
  33875. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  33876. string += snippet
  33877. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  33878. .replace( /UNROLLED_LOOP_INDEX/g, i );
  33879. }
  33880. return string;
  33881. }
  33882. //
  33883. function generatePrecision( parameters ) {
  33884. let precisionstring = `precision ${parameters.precision} float;
  33885. precision ${parameters.precision} int;
  33886. precision ${parameters.precision} sampler2D;
  33887. precision ${parameters.precision} samplerCube;
  33888. precision ${parameters.precision} sampler3D;
  33889. precision ${parameters.precision} sampler2DArray;
  33890. precision ${parameters.precision} sampler2DShadow;
  33891. precision ${parameters.precision} samplerCubeShadow;
  33892. precision ${parameters.precision} sampler2DArrayShadow;
  33893. precision ${parameters.precision} isampler2D;
  33894. precision ${parameters.precision} isampler3D;
  33895. precision ${parameters.precision} isamplerCube;
  33896. precision ${parameters.precision} isampler2DArray;
  33897. precision ${parameters.precision} usampler2D;
  33898. precision ${parameters.precision} usampler3D;
  33899. precision ${parameters.precision} usamplerCube;
  33900. precision ${parameters.precision} usampler2DArray;
  33901. `;
  33902. if ( parameters.precision === 'highp' ) {
  33903. precisionstring += '\n#define HIGH_PRECISION';
  33904. } else if ( parameters.precision === 'mediump' ) {
  33905. precisionstring += '\n#define MEDIUM_PRECISION';
  33906. } else if ( parameters.precision === 'lowp' ) {
  33907. precisionstring += '\n#define LOW_PRECISION';
  33908. }
  33909. return precisionstring;
  33910. }
  33911. function generateShadowMapTypeDefine( parameters ) {
  33912. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  33913. if ( parameters.shadowMapType === PCFShadowMap ) {
  33914. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  33915. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  33916. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  33917. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  33918. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  33919. }
  33920. return shadowMapTypeDefine;
  33921. }
  33922. function generateEnvMapTypeDefine( parameters ) {
  33923. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  33924. if ( parameters.envMap ) {
  33925. switch ( parameters.envMapMode ) {
  33926. case CubeReflectionMapping:
  33927. case CubeRefractionMapping:
  33928. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  33929. break;
  33930. case CubeUVReflectionMapping:
  33931. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  33932. break;
  33933. }
  33934. }
  33935. return envMapTypeDefine;
  33936. }
  33937. function generateEnvMapModeDefine( parameters ) {
  33938. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  33939. if ( parameters.envMap ) {
  33940. switch ( parameters.envMapMode ) {
  33941. case CubeRefractionMapping:
  33942. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  33943. break;
  33944. }
  33945. }
  33946. return envMapModeDefine;
  33947. }
  33948. function generateEnvMapBlendingDefine( parameters ) {
  33949. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  33950. if ( parameters.envMap ) {
  33951. switch ( parameters.combine ) {
  33952. case MultiplyOperation:
  33953. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  33954. break;
  33955. case MixOperation:
  33956. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  33957. break;
  33958. case AddOperation:
  33959. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  33960. break;
  33961. }
  33962. }
  33963. return envMapBlendingDefine;
  33964. }
  33965. function generateCubeUVSize( parameters ) {
  33966. const imageHeight = parameters.envMapCubeUVHeight;
  33967. if ( imageHeight === null ) return null;
  33968. const maxMip = Math.log2( imageHeight ) - 2;
  33969. const texelHeight = 1.0 / imageHeight;
  33970. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  33971. return { texelWidth, texelHeight, maxMip };
  33972. }
  33973. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  33974. // TODO Send this event to Three.js DevTools
  33975. // console.log( 'WebGLProgram', cacheKey );
  33976. const gl = renderer.getContext();
  33977. const defines = parameters.defines;
  33978. let vertexShader = parameters.vertexShader;
  33979. let fragmentShader = parameters.fragmentShader;
  33980. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  33981. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  33982. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  33983. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  33984. const envMapCubeUVSize = generateCubeUVSize( parameters );
  33985. const customVertexExtensions = generateVertexExtensions( parameters );
  33986. const customDefines = generateDefines( defines );
  33987. const program = gl.createProgram();
  33988. let prefixVertex, prefixFragment;
  33989. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  33990. if ( parameters.isRawShaderMaterial ) {
  33991. prefixVertex = [
  33992. '#define SHADER_TYPE ' + parameters.shaderType,
  33993. '#define SHADER_NAME ' + parameters.shaderName,
  33994. customDefines
  33995. ].filter( filterEmptyLine ).join( '\n' );
  33996. if ( prefixVertex.length > 0 ) {
  33997. prefixVertex += '\n';
  33998. }
  33999. prefixFragment = [
  34000. '#define SHADER_TYPE ' + parameters.shaderType,
  34001. '#define SHADER_NAME ' + parameters.shaderName,
  34002. customDefines
  34003. ].filter( filterEmptyLine ).join( '\n' );
  34004. if ( prefixFragment.length > 0 ) {
  34005. prefixFragment += '\n';
  34006. }
  34007. } else {
  34008. prefixVertex = [
  34009. generatePrecision( parameters ),
  34010. '#define SHADER_TYPE ' + parameters.shaderType,
  34011. '#define SHADER_NAME ' + parameters.shaderName,
  34012. customDefines,
  34013. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  34014. parameters.batching ? '#define USE_BATCHING' : '',
  34015. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  34016. parameters.instancing ? '#define USE_INSTANCING' : '',
  34017. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  34018. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  34019. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  34020. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  34021. parameters.map ? '#define USE_MAP' : '',
  34022. parameters.envMap ? '#define USE_ENVMAP' : '',
  34023. parameters.envMap ? '#define ' + envMapModeDefine : '',
  34024. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  34025. parameters.aoMap ? '#define USE_AOMAP' : '',
  34026. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  34027. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  34028. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  34029. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  34030. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  34031. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  34032. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  34033. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  34034. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  34035. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  34036. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  34037. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  34038. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  34039. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  34040. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  34041. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  34042. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  34043. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  34044. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  34045. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  34046. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  34047. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  34048. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  34049. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  34050. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  34051. //
  34052. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  34053. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  34054. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  34055. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  34056. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  34057. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  34058. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  34059. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  34060. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  34061. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  34062. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  34063. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  34064. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  34065. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  34066. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  34067. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  34068. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  34069. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  34070. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  34071. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  34072. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  34073. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  34074. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  34075. //
  34076. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  34077. parameters.vertexColors ? '#define USE_COLOR' : '',
  34078. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  34079. parameters.vertexUv1s ? '#define USE_UV1' : '',
  34080. parameters.vertexUv2s ? '#define USE_UV2' : '',
  34081. parameters.vertexUv3s ? '#define USE_UV3' : '',
  34082. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  34083. parameters.flatShading ? '#define FLAT_SHADED' : '',
  34084. parameters.skinning ? '#define USE_SKINNING' : '',
  34085. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  34086. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  34087. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  34088. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  34089. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  34090. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  34091. parameters.flipSided ? '#define FLIP_SIDED' : '',
  34092. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  34093. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  34094. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  34095. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  34096. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  34097. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  34098. 'uniform mat4 modelMatrix;',
  34099. 'uniform mat4 modelViewMatrix;',
  34100. 'uniform mat4 projectionMatrix;',
  34101. 'uniform mat4 viewMatrix;',
  34102. 'uniform mat3 normalMatrix;',
  34103. 'uniform vec3 cameraPosition;',
  34104. 'uniform bool isOrthographic;',
  34105. '#ifdef USE_INSTANCING',
  34106. ' attribute mat4 instanceMatrix;',
  34107. '#endif',
  34108. '#ifdef USE_INSTANCING_COLOR',
  34109. ' attribute vec3 instanceColor;',
  34110. '#endif',
  34111. '#ifdef USE_INSTANCING_MORPH',
  34112. ' uniform sampler2D morphTexture;',
  34113. '#endif',
  34114. 'attribute vec3 position;',
  34115. 'attribute vec3 normal;',
  34116. 'attribute vec2 uv;',
  34117. '#ifdef USE_UV1',
  34118. ' attribute vec2 uv1;',
  34119. '#endif',
  34120. '#ifdef USE_UV2',
  34121. ' attribute vec2 uv2;',
  34122. '#endif',
  34123. '#ifdef USE_UV3',
  34124. ' attribute vec2 uv3;',
  34125. '#endif',
  34126. '#ifdef USE_TANGENT',
  34127. ' attribute vec4 tangent;',
  34128. '#endif',
  34129. '#if defined( USE_COLOR_ALPHA )',
  34130. ' attribute vec4 color;',
  34131. '#elif defined( USE_COLOR )',
  34132. ' attribute vec3 color;',
  34133. '#endif',
  34134. '#ifdef USE_SKINNING',
  34135. ' attribute vec4 skinIndex;',
  34136. ' attribute vec4 skinWeight;',
  34137. '#endif',
  34138. '\n'
  34139. ].filter( filterEmptyLine ).join( '\n' );
  34140. prefixFragment = [
  34141. generatePrecision( parameters ),
  34142. '#define SHADER_TYPE ' + parameters.shaderType,
  34143. '#define SHADER_NAME ' + parameters.shaderName,
  34144. customDefines,
  34145. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  34146. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  34147. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  34148. parameters.map ? '#define USE_MAP' : '',
  34149. parameters.matcap ? '#define USE_MATCAP' : '',
  34150. parameters.envMap ? '#define USE_ENVMAP' : '',
  34151. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  34152. parameters.envMap ? '#define ' + envMapModeDefine : '',
  34153. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  34154. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  34155. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  34156. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  34157. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  34158. parameters.aoMap ? '#define USE_AOMAP' : '',
  34159. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  34160. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  34161. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  34162. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  34163. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  34164. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  34165. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  34166. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  34167. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  34168. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  34169. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  34170. parameters.dispersion ? '#define USE_DISPERSION' : '',
  34171. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  34172. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  34173. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  34174. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  34175. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  34176. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  34177. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  34178. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  34179. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  34180. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  34181. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  34182. parameters.sheen ? '#define USE_SHEEN' : '',
  34183. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  34184. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  34185. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  34186. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  34187. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  34188. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  34189. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  34190. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  34191. parameters.vertexUv1s ? '#define USE_UV1' : '',
  34192. parameters.vertexUv2s ? '#define USE_UV2' : '',
  34193. parameters.vertexUv3s ? '#define USE_UV3' : '',
  34194. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  34195. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  34196. parameters.flatShading ? '#define FLAT_SHADED' : '',
  34197. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  34198. parameters.flipSided ? '#define FLIP_SIDED' : '',
  34199. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  34200. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  34201. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  34202. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  34203. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  34204. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  34205. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  34206. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  34207. 'uniform mat4 viewMatrix;',
  34208. 'uniform vec3 cameraPosition;',
  34209. 'uniform bool isOrthographic;',
  34210. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  34211. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  34212. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  34213. parameters.dithering ? '#define DITHERING' : '',
  34214. parameters.opaque ? '#define OPAQUE' : '',
  34215. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  34216. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  34217. getLuminanceFunction(),
  34218. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  34219. '\n'
  34220. ].filter( filterEmptyLine ).join( '\n' );
  34221. }
  34222. vertexShader = resolveIncludes( vertexShader );
  34223. vertexShader = replaceLightNums( vertexShader, parameters );
  34224. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  34225. fragmentShader = resolveIncludes( fragmentShader );
  34226. fragmentShader = replaceLightNums( fragmentShader, parameters );
  34227. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  34228. vertexShader = unrollLoops( vertexShader );
  34229. fragmentShader = unrollLoops( fragmentShader );
  34230. if ( parameters.isRawShaderMaterial !== true ) {
  34231. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  34232. versionString = '#version 300 es\n';
  34233. prefixVertex = [
  34234. customVertexExtensions,
  34235. '#define attribute in',
  34236. '#define varying out',
  34237. '#define texture2D texture'
  34238. ].join( '\n' ) + '\n' + prefixVertex;
  34239. prefixFragment = [
  34240. '#define varying in',
  34241. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  34242. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  34243. '#define gl_FragDepthEXT gl_FragDepth',
  34244. '#define texture2D texture',
  34245. '#define textureCube texture',
  34246. '#define texture2DProj textureProj',
  34247. '#define texture2DLodEXT textureLod',
  34248. '#define texture2DProjLodEXT textureProjLod',
  34249. '#define textureCubeLodEXT textureLod',
  34250. '#define texture2DGradEXT textureGrad',
  34251. '#define texture2DProjGradEXT textureProjGrad',
  34252. '#define textureCubeGradEXT textureGrad'
  34253. ].join( '\n' ) + '\n' + prefixFragment;
  34254. }
  34255. const vertexGlsl = versionString + prefixVertex + vertexShader;
  34256. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  34257. // console.log( '*VERTEX*', vertexGlsl );
  34258. // console.log( '*FRAGMENT*', fragmentGlsl );
  34259. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  34260. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  34261. gl.attachShader( program, glVertexShader );
  34262. gl.attachShader( program, glFragmentShader );
  34263. // Force a particular attribute to index 0.
  34264. if ( parameters.index0AttributeName !== undefined ) {
  34265. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  34266. } else if ( parameters.morphTargets === true ) {
  34267. // programs with morphTargets displace position out of attribute 0
  34268. gl.bindAttribLocation( program, 0, 'position' );
  34269. }
  34270. gl.linkProgram( program );
  34271. function onFirstUse( self ) {
  34272. // check for link errors
  34273. if ( renderer.debug.checkShaderErrors ) {
  34274. const programLog = gl.getProgramInfoLog( program ).trim();
  34275. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  34276. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  34277. let runnable = true;
  34278. let haveDiagnostics = true;
  34279. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  34280. runnable = false;
  34281. if ( typeof renderer.debug.onShaderError === 'function' ) {
  34282. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  34283. } else {
  34284. // default error reporting
  34285. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  34286. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  34287. console.error(
  34288. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  34289. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  34290. 'Material Name: ' + self.name + '\n' +
  34291. 'Material Type: ' + self.type + '\n\n' +
  34292. 'Program Info Log: ' + programLog + '\n' +
  34293. vertexErrors + '\n' +
  34294. fragmentErrors
  34295. );
  34296. }
  34297. } else if ( programLog !== '' ) {
  34298. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  34299. } else if ( vertexLog === '' || fragmentLog === '' ) {
  34300. haveDiagnostics = false;
  34301. }
  34302. if ( haveDiagnostics ) {
  34303. self.diagnostics = {
  34304. runnable: runnable,
  34305. programLog: programLog,
  34306. vertexShader: {
  34307. log: vertexLog,
  34308. prefix: prefixVertex
  34309. },
  34310. fragmentShader: {
  34311. log: fragmentLog,
  34312. prefix: prefixFragment
  34313. }
  34314. };
  34315. }
  34316. }
  34317. // Clean up
  34318. // Crashes in iOS9 and iOS10. #18402
  34319. // gl.detachShader( program, glVertexShader );
  34320. // gl.detachShader( program, glFragmentShader );
  34321. gl.deleteShader( glVertexShader );
  34322. gl.deleteShader( glFragmentShader );
  34323. cachedUniforms = new WebGLUniforms( gl, program );
  34324. cachedAttributes = fetchAttributeLocations( gl, program );
  34325. }
  34326. // set up caching for uniform locations
  34327. let cachedUniforms;
  34328. this.getUniforms = function () {
  34329. if ( cachedUniforms === undefined ) {
  34330. // Populates cachedUniforms and cachedAttributes
  34331. onFirstUse( this );
  34332. }
  34333. return cachedUniforms;
  34334. };
  34335. // set up caching for attribute locations
  34336. let cachedAttributes;
  34337. this.getAttributes = function () {
  34338. if ( cachedAttributes === undefined ) {
  34339. // Populates cachedAttributes and cachedUniforms
  34340. onFirstUse( this );
  34341. }
  34342. return cachedAttributes;
  34343. };
  34344. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  34345. // flag the program as ready immediately. It may cause a stall when it's first used.
  34346. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  34347. this.isReady = function () {
  34348. if ( programReady === false ) {
  34349. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  34350. }
  34351. return programReady;
  34352. };
  34353. // free resource
  34354. this.destroy = function () {
  34355. bindingStates.releaseStatesOfProgram( this );
  34356. gl.deleteProgram( program );
  34357. this.program = undefined;
  34358. };
  34359. //
  34360. this.type = parameters.shaderType;
  34361. this.name = parameters.shaderName;
  34362. this.id = programIdCount ++;
  34363. this.cacheKey = cacheKey;
  34364. this.usedTimes = 1;
  34365. this.program = program;
  34366. this.vertexShader = glVertexShader;
  34367. this.fragmentShader = glFragmentShader;
  34368. return this;
  34369. }
  34370. let _id = 0;
  34371. class WebGLShaderCache {
  34372. constructor() {
  34373. this.shaderCache = new Map();
  34374. this.materialCache = new Map();
  34375. }
  34376. update( material ) {
  34377. const vertexShader = material.vertexShader;
  34378. const fragmentShader = material.fragmentShader;
  34379. const vertexShaderStage = this._getShaderStage( vertexShader );
  34380. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  34381. const materialShaders = this._getShaderCacheForMaterial( material );
  34382. if ( materialShaders.has( vertexShaderStage ) === false ) {
  34383. materialShaders.add( vertexShaderStage );
  34384. vertexShaderStage.usedTimes ++;
  34385. }
  34386. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  34387. materialShaders.add( fragmentShaderStage );
  34388. fragmentShaderStage.usedTimes ++;
  34389. }
  34390. return this;
  34391. }
  34392. remove( material ) {
  34393. const materialShaders = this.materialCache.get( material );
  34394. for ( const shaderStage of materialShaders ) {
  34395. shaderStage.usedTimes --;
  34396. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  34397. }
  34398. this.materialCache.delete( material );
  34399. return this;
  34400. }
  34401. getVertexShaderID( material ) {
  34402. return this._getShaderStage( material.vertexShader ).id;
  34403. }
  34404. getFragmentShaderID( material ) {
  34405. return this._getShaderStage( material.fragmentShader ).id;
  34406. }
  34407. dispose() {
  34408. this.shaderCache.clear();
  34409. this.materialCache.clear();
  34410. }
  34411. _getShaderCacheForMaterial( material ) {
  34412. const cache = this.materialCache;
  34413. let set = cache.get( material );
  34414. if ( set === undefined ) {
  34415. set = new Set();
  34416. cache.set( material, set );
  34417. }
  34418. return set;
  34419. }
  34420. _getShaderStage( code ) {
  34421. const cache = this.shaderCache;
  34422. let stage = cache.get( code );
  34423. if ( stage === undefined ) {
  34424. stage = new WebGLShaderStage( code );
  34425. cache.set( code, stage );
  34426. }
  34427. return stage;
  34428. }
  34429. }
  34430. class WebGLShaderStage {
  34431. constructor( code ) {
  34432. this.id = _id ++;
  34433. this.code = code;
  34434. this.usedTimes = 0;
  34435. }
  34436. }
  34437. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  34438. const _programLayers = new Layers();
  34439. const _customShaders = new WebGLShaderCache();
  34440. const _activeChannels = new Set();
  34441. const programs = [];
  34442. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  34443. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  34444. let precision = capabilities.precision;
  34445. const shaderIDs = {
  34446. MeshDepthMaterial: 'depth',
  34447. MeshDistanceMaterial: 'distanceRGBA',
  34448. MeshNormalMaterial: 'normal',
  34449. MeshBasicMaterial: 'basic',
  34450. MeshLambertMaterial: 'lambert',
  34451. MeshPhongMaterial: 'phong',
  34452. MeshToonMaterial: 'toon',
  34453. MeshStandardMaterial: 'physical',
  34454. MeshPhysicalMaterial: 'physical',
  34455. MeshMatcapMaterial: 'matcap',
  34456. LineBasicMaterial: 'basic',
  34457. LineDashedMaterial: 'dashed',
  34458. PointsMaterial: 'points',
  34459. ShadowMaterial: 'shadow',
  34460. SpriteMaterial: 'sprite'
  34461. };
  34462. function getChannel( value ) {
  34463. _activeChannels.add( value );
  34464. if ( value === 0 ) return 'uv';
  34465. return `uv${ value }`;
  34466. }
  34467. function getParameters( material, lights, shadows, scene, object ) {
  34468. const fog = scene.fog;
  34469. const geometry = object.geometry;
  34470. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  34471. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  34472. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  34473. const shaderID = shaderIDs[ material.type ];
  34474. // heuristics to create shader parameters according to lights in the scene
  34475. // (not to blow over maxLights budget)
  34476. if ( material.precision !== null ) {
  34477. precision = capabilities.getMaxPrecision( material.precision );
  34478. if ( precision !== material.precision ) {
  34479. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  34480. }
  34481. }
  34482. //
  34483. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  34484. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  34485. let morphTextureStride = 0;
  34486. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  34487. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  34488. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  34489. //
  34490. let vertexShader, fragmentShader;
  34491. let customVertexShaderID, customFragmentShaderID;
  34492. if ( shaderID ) {
  34493. const shader = ShaderLib[ shaderID ];
  34494. vertexShader = shader.vertexShader;
  34495. fragmentShader = shader.fragmentShader;
  34496. } else {
  34497. vertexShader = material.vertexShader;
  34498. fragmentShader = material.fragmentShader;
  34499. _customShaders.update( material );
  34500. customVertexShaderID = _customShaders.getVertexShaderID( material );
  34501. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  34502. }
  34503. const currentRenderTarget = renderer.getRenderTarget();
  34504. const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
  34505. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  34506. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  34507. const HAS_MAP = !! material.map;
  34508. const HAS_MATCAP = !! material.matcap;
  34509. const HAS_ENVMAP = !! envMap;
  34510. const HAS_AOMAP = !! material.aoMap;
  34511. const HAS_LIGHTMAP = !! material.lightMap;
  34512. const HAS_BUMPMAP = !! material.bumpMap;
  34513. const HAS_NORMALMAP = !! material.normalMap;
  34514. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  34515. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  34516. const HAS_METALNESSMAP = !! material.metalnessMap;
  34517. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  34518. const HAS_ANISOTROPY = material.anisotropy > 0;
  34519. const HAS_CLEARCOAT = material.clearcoat > 0;
  34520. const HAS_DISPERSION = material.dispersion > 0;
  34521. const HAS_IRIDESCENCE = material.iridescence > 0;
  34522. const HAS_SHEEN = material.sheen > 0;
  34523. const HAS_TRANSMISSION = material.transmission > 0;
  34524. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  34525. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  34526. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  34527. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  34528. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  34529. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  34530. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  34531. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  34532. const HAS_SPECULARMAP = !! material.specularMap;
  34533. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  34534. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  34535. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  34536. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  34537. const HAS_GRADIENTMAP = !! material.gradientMap;
  34538. const HAS_ALPHAMAP = !! material.alphaMap;
  34539. const HAS_ALPHATEST = material.alphaTest > 0;
  34540. const HAS_ALPHAHASH = !! material.alphaHash;
  34541. const HAS_EXTENSIONS = !! material.extensions;
  34542. let toneMapping = NoToneMapping;
  34543. if ( material.toneMapped ) {
  34544. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  34545. toneMapping = renderer.toneMapping;
  34546. }
  34547. }
  34548. const parameters = {
  34549. shaderID: shaderID,
  34550. shaderType: material.type,
  34551. shaderName: material.name,
  34552. vertexShader: vertexShader,
  34553. fragmentShader: fragmentShader,
  34554. defines: material.defines,
  34555. customVertexShaderID: customVertexShaderID,
  34556. customFragmentShaderID: customFragmentShaderID,
  34557. isRawShaderMaterial: material.isRawShaderMaterial === true,
  34558. glslVersion: material.glslVersion,
  34559. precision: precision,
  34560. batching: IS_BATCHEDMESH,
  34561. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  34562. instancing: IS_INSTANCEDMESH,
  34563. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  34564. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  34565. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  34566. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  34567. alphaToCoverage: !! material.alphaToCoverage,
  34568. map: HAS_MAP,
  34569. matcap: HAS_MATCAP,
  34570. envMap: HAS_ENVMAP,
  34571. envMapMode: HAS_ENVMAP && envMap.mapping,
  34572. envMapCubeUVHeight: envMapCubeUVHeight,
  34573. aoMap: HAS_AOMAP,
  34574. lightMap: HAS_LIGHTMAP,
  34575. bumpMap: HAS_BUMPMAP,
  34576. normalMap: HAS_NORMALMAP,
  34577. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  34578. emissiveMap: HAS_EMISSIVEMAP,
  34579. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  34580. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  34581. metalnessMap: HAS_METALNESSMAP,
  34582. roughnessMap: HAS_ROUGHNESSMAP,
  34583. anisotropy: HAS_ANISOTROPY,
  34584. anisotropyMap: HAS_ANISOTROPYMAP,
  34585. clearcoat: HAS_CLEARCOAT,
  34586. clearcoatMap: HAS_CLEARCOATMAP,
  34587. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  34588. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  34589. dispersion: HAS_DISPERSION,
  34590. iridescence: HAS_IRIDESCENCE,
  34591. iridescenceMap: HAS_IRIDESCENCEMAP,
  34592. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  34593. sheen: HAS_SHEEN,
  34594. sheenColorMap: HAS_SHEEN_COLORMAP,
  34595. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  34596. specularMap: HAS_SPECULARMAP,
  34597. specularColorMap: HAS_SPECULAR_COLORMAP,
  34598. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  34599. transmission: HAS_TRANSMISSION,
  34600. transmissionMap: HAS_TRANSMISSIONMAP,
  34601. thicknessMap: HAS_THICKNESSMAP,
  34602. gradientMap: HAS_GRADIENTMAP,
  34603. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  34604. alphaMap: HAS_ALPHAMAP,
  34605. alphaTest: HAS_ALPHATEST,
  34606. alphaHash: HAS_ALPHAHASH,
  34607. combine: material.combine,
  34608. //
  34609. mapUv: HAS_MAP && getChannel( material.map.channel ),
  34610. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  34611. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  34612. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  34613. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  34614. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  34615. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  34616. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  34617. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  34618. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  34619. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  34620. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  34621. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  34622. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  34623. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  34624. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  34625. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  34626. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  34627. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  34628. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  34629. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  34630. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  34631. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  34632. //
  34633. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  34634. vertexColors: material.vertexColors,
  34635. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  34636. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  34637. fog: !! fog,
  34638. useFog: material.fog === true,
  34639. fogExp2: ( !! fog && fog.isFogExp2 ),
  34640. flatShading: material.flatShading === true,
  34641. sizeAttenuation: material.sizeAttenuation === true,
  34642. logarithmicDepthBuffer: logarithmicDepthBuffer,
  34643. reverseDepthBuffer: reverseDepthBuffer,
  34644. skinning: object.isSkinnedMesh === true,
  34645. morphTargets: geometry.morphAttributes.position !== undefined,
  34646. morphNormals: geometry.morphAttributes.normal !== undefined,
  34647. morphColors: geometry.morphAttributes.color !== undefined,
  34648. morphTargetsCount: morphTargetsCount,
  34649. morphTextureStride: morphTextureStride,
  34650. numDirLights: lights.directional.length,
  34651. numPointLights: lights.point.length,
  34652. numSpotLights: lights.spot.length,
  34653. numSpotLightMaps: lights.spotLightMap.length,
  34654. numRectAreaLights: lights.rectArea.length,
  34655. numHemiLights: lights.hemi.length,
  34656. numDirLightShadows: lights.directionalShadowMap.length,
  34657. numPointLightShadows: lights.pointShadowMap.length,
  34658. numSpotLightShadows: lights.spotShadowMap.length,
  34659. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  34660. numLightProbes: lights.numLightProbes,
  34661. numClippingPlanes: clipping.numPlanes,
  34662. numClipIntersection: clipping.numIntersection,
  34663. dithering: material.dithering,
  34664. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  34665. shadowMapType: renderer.shadowMap.type,
  34666. toneMapping: toneMapping,
  34667. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  34668. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  34669. premultipliedAlpha: material.premultipliedAlpha,
  34670. doubleSided: material.side === DoubleSide,
  34671. flipSided: material.side === BackSide,
  34672. useDepthPacking: material.depthPacking >= 0,
  34673. depthPacking: material.depthPacking || 0,
  34674. index0AttributeName: material.index0AttributeName,
  34675. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  34676. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  34677. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  34678. customProgramCacheKey: material.customProgramCacheKey()
  34679. };
  34680. // the usage of getChannel() determines the active texture channels for this shader
  34681. parameters.vertexUv1s = _activeChannels.has( 1 );
  34682. parameters.vertexUv2s = _activeChannels.has( 2 );
  34683. parameters.vertexUv3s = _activeChannels.has( 3 );
  34684. _activeChannels.clear();
  34685. return parameters;
  34686. }
  34687. function getProgramCacheKey( parameters ) {
  34688. const array = [];
  34689. if ( parameters.shaderID ) {
  34690. array.push( parameters.shaderID );
  34691. } else {
  34692. array.push( parameters.customVertexShaderID );
  34693. array.push( parameters.customFragmentShaderID );
  34694. }
  34695. if ( parameters.defines !== undefined ) {
  34696. for ( const name in parameters.defines ) {
  34697. array.push( name );
  34698. array.push( parameters.defines[ name ] );
  34699. }
  34700. }
  34701. if ( parameters.isRawShaderMaterial === false ) {
  34702. getProgramCacheKeyParameters( array, parameters );
  34703. getProgramCacheKeyBooleans( array, parameters );
  34704. array.push( renderer.outputColorSpace );
  34705. }
  34706. array.push( parameters.customProgramCacheKey );
  34707. return array.join();
  34708. }
  34709. function getProgramCacheKeyParameters( array, parameters ) {
  34710. array.push( parameters.precision );
  34711. array.push( parameters.outputColorSpace );
  34712. array.push( parameters.envMapMode );
  34713. array.push( parameters.envMapCubeUVHeight );
  34714. array.push( parameters.mapUv );
  34715. array.push( parameters.alphaMapUv );
  34716. array.push( parameters.lightMapUv );
  34717. array.push( parameters.aoMapUv );
  34718. array.push( parameters.bumpMapUv );
  34719. array.push( parameters.normalMapUv );
  34720. array.push( parameters.displacementMapUv );
  34721. array.push( parameters.emissiveMapUv );
  34722. array.push( parameters.metalnessMapUv );
  34723. array.push( parameters.roughnessMapUv );
  34724. array.push( parameters.anisotropyMapUv );
  34725. array.push( parameters.clearcoatMapUv );
  34726. array.push( parameters.clearcoatNormalMapUv );
  34727. array.push( parameters.clearcoatRoughnessMapUv );
  34728. array.push( parameters.iridescenceMapUv );
  34729. array.push( parameters.iridescenceThicknessMapUv );
  34730. array.push( parameters.sheenColorMapUv );
  34731. array.push( parameters.sheenRoughnessMapUv );
  34732. array.push( parameters.specularMapUv );
  34733. array.push( parameters.specularColorMapUv );
  34734. array.push( parameters.specularIntensityMapUv );
  34735. array.push( parameters.transmissionMapUv );
  34736. array.push( parameters.thicknessMapUv );
  34737. array.push( parameters.combine );
  34738. array.push( parameters.fogExp2 );
  34739. array.push( parameters.sizeAttenuation );
  34740. array.push( parameters.morphTargetsCount );
  34741. array.push( parameters.morphAttributeCount );
  34742. array.push( parameters.numDirLights );
  34743. array.push( parameters.numPointLights );
  34744. array.push( parameters.numSpotLights );
  34745. array.push( parameters.numSpotLightMaps );
  34746. array.push( parameters.numHemiLights );
  34747. array.push( parameters.numRectAreaLights );
  34748. array.push( parameters.numDirLightShadows );
  34749. array.push( parameters.numPointLightShadows );
  34750. array.push( parameters.numSpotLightShadows );
  34751. array.push( parameters.numSpotLightShadowsWithMaps );
  34752. array.push( parameters.numLightProbes );
  34753. array.push( parameters.shadowMapType );
  34754. array.push( parameters.toneMapping );
  34755. array.push( parameters.numClippingPlanes );
  34756. array.push( parameters.numClipIntersection );
  34757. array.push( parameters.depthPacking );
  34758. }
  34759. function getProgramCacheKeyBooleans( array, parameters ) {
  34760. _programLayers.disableAll();
  34761. if ( parameters.supportsVertexTextures )
  34762. _programLayers.enable( 0 );
  34763. if ( parameters.instancing )
  34764. _programLayers.enable( 1 );
  34765. if ( parameters.instancingColor )
  34766. _programLayers.enable( 2 );
  34767. if ( parameters.instancingMorph )
  34768. _programLayers.enable( 3 );
  34769. if ( parameters.matcap )
  34770. _programLayers.enable( 4 );
  34771. if ( parameters.envMap )
  34772. _programLayers.enable( 5 );
  34773. if ( parameters.normalMapObjectSpace )
  34774. _programLayers.enable( 6 );
  34775. if ( parameters.normalMapTangentSpace )
  34776. _programLayers.enable( 7 );
  34777. if ( parameters.clearcoat )
  34778. _programLayers.enable( 8 );
  34779. if ( parameters.iridescence )
  34780. _programLayers.enable( 9 );
  34781. if ( parameters.alphaTest )
  34782. _programLayers.enable( 10 );
  34783. if ( parameters.vertexColors )
  34784. _programLayers.enable( 11 );
  34785. if ( parameters.vertexAlphas )
  34786. _programLayers.enable( 12 );
  34787. if ( parameters.vertexUv1s )
  34788. _programLayers.enable( 13 );
  34789. if ( parameters.vertexUv2s )
  34790. _programLayers.enable( 14 );
  34791. if ( parameters.vertexUv3s )
  34792. _programLayers.enable( 15 );
  34793. if ( parameters.vertexTangents )
  34794. _programLayers.enable( 16 );
  34795. if ( parameters.anisotropy )
  34796. _programLayers.enable( 17 );
  34797. if ( parameters.alphaHash )
  34798. _programLayers.enable( 18 );
  34799. if ( parameters.batching )
  34800. _programLayers.enable( 19 );
  34801. if ( parameters.dispersion )
  34802. _programLayers.enable( 20 );
  34803. if ( parameters.batchingColor )
  34804. _programLayers.enable( 21 );
  34805. array.push( _programLayers.mask );
  34806. _programLayers.disableAll();
  34807. if ( parameters.fog )
  34808. _programLayers.enable( 0 );
  34809. if ( parameters.useFog )
  34810. _programLayers.enable( 1 );
  34811. if ( parameters.flatShading )
  34812. _programLayers.enable( 2 );
  34813. if ( parameters.logarithmicDepthBuffer )
  34814. _programLayers.enable( 3 );
  34815. if ( parameters.reverseDepthBuffer )
  34816. _programLayers.enable( 4 );
  34817. if ( parameters.skinning )
  34818. _programLayers.enable( 5 );
  34819. if ( parameters.morphTargets )
  34820. _programLayers.enable( 6 );
  34821. if ( parameters.morphNormals )
  34822. _programLayers.enable( 7 );
  34823. if ( parameters.morphColors )
  34824. _programLayers.enable( 8 );
  34825. if ( parameters.premultipliedAlpha )
  34826. _programLayers.enable( 9 );
  34827. if ( parameters.shadowMapEnabled )
  34828. _programLayers.enable( 10 );
  34829. if ( parameters.doubleSided )
  34830. _programLayers.enable( 11 );
  34831. if ( parameters.flipSided )
  34832. _programLayers.enable( 12 );
  34833. if ( parameters.useDepthPacking )
  34834. _programLayers.enable( 13 );
  34835. if ( parameters.dithering )
  34836. _programLayers.enable( 14 );
  34837. if ( parameters.transmission )
  34838. _programLayers.enable( 15 );
  34839. if ( parameters.sheen )
  34840. _programLayers.enable( 16 );
  34841. if ( parameters.opaque )
  34842. _programLayers.enable( 17 );
  34843. if ( parameters.pointsUvs )
  34844. _programLayers.enable( 18 );
  34845. if ( parameters.decodeVideoTexture )
  34846. _programLayers.enable( 19 );
  34847. if ( parameters.decodeVideoTextureEmissive )
  34848. _programLayers.enable( 20 );
  34849. if ( parameters.alphaToCoverage )
  34850. _programLayers.enable( 21 );
  34851. array.push( _programLayers.mask );
  34852. }
  34853. function getUniforms( material ) {
  34854. const shaderID = shaderIDs[ material.type ];
  34855. let uniforms;
  34856. if ( shaderID ) {
  34857. const shader = ShaderLib[ shaderID ];
  34858. uniforms = UniformsUtils.clone( shader.uniforms );
  34859. } else {
  34860. uniforms = material.uniforms;
  34861. }
  34862. return uniforms;
  34863. }
  34864. function acquireProgram( parameters, cacheKey ) {
  34865. let program;
  34866. // Check if code has been already compiled
  34867. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  34868. const preexistingProgram = programs[ p ];
  34869. if ( preexistingProgram.cacheKey === cacheKey ) {
  34870. program = preexistingProgram;
  34871. ++ program.usedTimes;
  34872. break;
  34873. }
  34874. }
  34875. if ( program === undefined ) {
  34876. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  34877. programs.push( program );
  34878. }
  34879. return program;
  34880. }
  34881. function releaseProgram( program ) {
  34882. if ( -- program.usedTimes === 0 ) {
  34883. // Remove from unordered set
  34884. const i = programs.indexOf( program );
  34885. programs[ i ] = programs[ programs.length - 1 ];
  34886. programs.pop();
  34887. // Free WebGL resources
  34888. program.destroy();
  34889. }
  34890. }
  34891. function releaseShaderCache( material ) {
  34892. _customShaders.remove( material );
  34893. }
  34894. function dispose() {
  34895. _customShaders.dispose();
  34896. }
  34897. return {
  34898. getParameters: getParameters,
  34899. getProgramCacheKey: getProgramCacheKey,
  34900. getUniforms: getUniforms,
  34901. acquireProgram: acquireProgram,
  34902. releaseProgram: releaseProgram,
  34903. releaseShaderCache: releaseShaderCache,
  34904. // Exposed for resource monitoring & error feedback via renderer.info:
  34905. programs: programs,
  34906. dispose: dispose
  34907. };
  34908. }
  34909. function WebGLProperties() {
  34910. let properties = new WeakMap();
  34911. function has( object ) {
  34912. return properties.has( object );
  34913. }
  34914. function get( object ) {
  34915. let map = properties.get( object );
  34916. if ( map === undefined ) {
  34917. map = {};
  34918. properties.set( object, map );
  34919. }
  34920. return map;
  34921. }
  34922. function remove( object ) {
  34923. properties.delete( object );
  34924. }
  34925. function update( object, key, value ) {
  34926. properties.get( object )[ key ] = value;
  34927. }
  34928. function dispose() {
  34929. properties = new WeakMap();
  34930. }
  34931. return {
  34932. has: has,
  34933. get: get,
  34934. remove: remove,
  34935. update: update,
  34936. dispose: dispose
  34937. };
  34938. }
  34939. function painterSortStable( a, b ) {
  34940. if ( a.groupOrder !== b.groupOrder ) {
  34941. return a.groupOrder - b.groupOrder;
  34942. } else if ( a.renderOrder !== b.renderOrder ) {
  34943. return a.renderOrder - b.renderOrder;
  34944. } else if ( a.material.id !== b.material.id ) {
  34945. return a.material.id - b.material.id;
  34946. } else if ( a.z !== b.z ) {
  34947. return a.z - b.z;
  34948. } else {
  34949. return a.id - b.id;
  34950. }
  34951. }
  34952. function reversePainterSortStable( a, b ) {
  34953. if ( a.groupOrder !== b.groupOrder ) {
  34954. return a.groupOrder - b.groupOrder;
  34955. } else if ( a.renderOrder !== b.renderOrder ) {
  34956. return a.renderOrder - b.renderOrder;
  34957. } else if ( a.z !== b.z ) {
  34958. return b.z - a.z;
  34959. } else {
  34960. return a.id - b.id;
  34961. }
  34962. }
  34963. function WebGLRenderList() {
  34964. const renderItems = [];
  34965. let renderItemsIndex = 0;
  34966. const opaque = [];
  34967. const transmissive = [];
  34968. const transparent = [];
  34969. function init() {
  34970. renderItemsIndex = 0;
  34971. opaque.length = 0;
  34972. transmissive.length = 0;
  34973. transparent.length = 0;
  34974. }
  34975. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  34976. let renderItem = renderItems[ renderItemsIndex ];
  34977. if ( renderItem === undefined ) {
  34978. renderItem = {
  34979. id: object.id,
  34980. object: object,
  34981. geometry: geometry,
  34982. material: material,
  34983. groupOrder: groupOrder,
  34984. renderOrder: object.renderOrder,
  34985. z: z,
  34986. group: group
  34987. };
  34988. renderItems[ renderItemsIndex ] = renderItem;
  34989. } else {
  34990. renderItem.id = object.id;
  34991. renderItem.object = object;
  34992. renderItem.geometry = geometry;
  34993. renderItem.material = material;
  34994. renderItem.groupOrder = groupOrder;
  34995. renderItem.renderOrder = object.renderOrder;
  34996. renderItem.z = z;
  34997. renderItem.group = group;
  34998. }
  34999. renderItemsIndex ++;
  35000. return renderItem;
  35001. }
  35002. function push( object, geometry, material, groupOrder, z, group ) {
  35003. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  35004. if ( material.transmission > 0.0 ) {
  35005. transmissive.push( renderItem );
  35006. } else if ( material.transparent === true ) {
  35007. transparent.push( renderItem );
  35008. } else {
  35009. opaque.push( renderItem );
  35010. }
  35011. }
  35012. function unshift( object, geometry, material, groupOrder, z, group ) {
  35013. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  35014. if ( material.transmission > 0.0 ) {
  35015. transmissive.unshift( renderItem );
  35016. } else if ( material.transparent === true ) {
  35017. transparent.unshift( renderItem );
  35018. } else {
  35019. opaque.unshift( renderItem );
  35020. }
  35021. }
  35022. function sort( customOpaqueSort, customTransparentSort ) {
  35023. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  35024. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  35025. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  35026. }
  35027. function finish() {
  35028. // Clear references from inactive renderItems in the list
  35029. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  35030. const renderItem = renderItems[ i ];
  35031. if ( renderItem.id === null ) break;
  35032. renderItem.id = null;
  35033. renderItem.object = null;
  35034. renderItem.geometry = null;
  35035. renderItem.material = null;
  35036. renderItem.group = null;
  35037. }
  35038. }
  35039. return {
  35040. opaque: opaque,
  35041. transmissive: transmissive,
  35042. transparent: transparent,
  35043. init: init,
  35044. push: push,
  35045. unshift: unshift,
  35046. finish: finish,
  35047. sort: sort
  35048. };
  35049. }
  35050. function WebGLRenderLists() {
  35051. let lists = new WeakMap();
  35052. function get( scene, renderCallDepth ) {
  35053. const listArray = lists.get( scene );
  35054. let list;
  35055. if ( listArray === undefined ) {
  35056. list = new WebGLRenderList();
  35057. lists.set( scene, [ list ] );
  35058. } else {
  35059. if ( renderCallDepth >= listArray.length ) {
  35060. list = new WebGLRenderList();
  35061. listArray.push( list );
  35062. } else {
  35063. list = listArray[ renderCallDepth ];
  35064. }
  35065. }
  35066. return list;
  35067. }
  35068. function dispose() {
  35069. lists = new WeakMap();
  35070. }
  35071. return {
  35072. get: get,
  35073. dispose: dispose
  35074. };
  35075. }
  35076. function UniformsCache() {
  35077. const lights = {};
  35078. return {
  35079. get: function ( light ) {
  35080. if ( lights[ light.id ] !== undefined ) {
  35081. return lights[ light.id ];
  35082. }
  35083. let uniforms;
  35084. switch ( light.type ) {
  35085. case 'DirectionalLight':
  35086. uniforms = {
  35087. direction: new Vector3(),
  35088. color: new Color()
  35089. };
  35090. break;
  35091. case 'SpotLight':
  35092. uniforms = {
  35093. position: new Vector3(),
  35094. direction: new Vector3(),
  35095. color: new Color(),
  35096. distance: 0,
  35097. coneCos: 0,
  35098. penumbraCos: 0,
  35099. decay: 0
  35100. };
  35101. break;
  35102. case 'PointLight':
  35103. uniforms = {
  35104. position: new Vector3(),
  35105. color: new Color(),
  35106. distance: 0,
  35107. decay: 0
  35108. };
  35109. break;
  35110. case 'HemisphereLight':
  35111. uniforms = {
  35112. direction: new Vector3(),
  35113. skyColor: new Color(),
  35114. groundColor: new Color()
  35115. };
  35116. break;
  35117. case 'RectAreaLight':
  35118. uniforms = {
  35119. color: new Color(),
  35120. position: new Vector3(),
  35121. halfWidth: new Vector3(),
  35122. halfHeight: new Vector3()
  35123. };
  35124. break;
  35125. }
  35126. lights[ light.id ] = uniforms;
  35127. return uniforms;
  35128. }
  35129. };
  35130. }
  35131. function ShadowUniformsCache() {
  35132. const lights = {};
  35133. return {
  35134. get: function ( light ) {
  35135. if ( lights[ light.id ] !== undefined ) {
  35136. return lights[ light.id ];
  35137. }
  35138. let uniforms;
  35139. switch ( light.type ) {
  35140. case 'DirectionalLight':
  35141. uniforms = {
  35142. shadowIntensity: 1,
  35143. shadowBias: 0,
  35144. shadowNormalBias: 0,
  35145. shadowRadius: 1,
  35146. shadowMapSize: new Vector2()
  35147. };
  35148. break;
  35149. case 'SpotLight':
  35150. uniforms = {
  35151. shadowIntensity: 1,
  35152. shadowBias: 0,
  35153. shadowNormalBias: 0,
  35154. shadowRadius: 1,
  35155. shadowMapSize: new Vector2()
  35156. };
  35157. break;
  35158. case 'PointLight':
  35159. uniforms = {
  35160. shadowIntensity: 1,
  35161. shadowBias: 0,
  35162. shadowNormalBias: 0,
  35163. shadowRadius: 1,
  35164. shadowMapSize: new Vector2(),
  35165. shadowCameraNear: 1,
  35166. shadowCameraFar: 1000
  35167. };
  35168. break;
  35169. // TODO (abelnation): set RectAreaLight shadow uniforms
  35170. }
  35171. lights[ light.id ] = uniforms;
  35172. return uniforms;
  35173. }
  35174. };
  35175. }
  35176. let nextVersion = 0;
  35177. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  35178. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  35179. }
  35180. function WebGLLights( extensions ) {
  35181. const cache = new UniformsCache();
  35182. const shadowCache = ShadowUniformsCache();
  35183. const state = {
  35184. version: 0,
  35185. hash: {
  35186. directionalLength: -1,
  35187. pointLength: -1,
  35188. spotLength: -1,
  35189. rectAreaLength: -1,
  35190. hemiLength: -1,
  35191. numDirectionalShadows: -1,
  35192. numPointShadows: -1,
  35193. numSpotShadows: -1,
  35194. numSpotMaps: -1,
  35195. numLightProbes: -1
  35196. },
  35197. ambient: [ 0, 0, 0 ],
  35198. probe: [],
  35199. directional: [],
  35200. directionalShadow: [],
  35201. directionalShadowMap: [],
  35202. directionalShadowMatrix: [],
  35203. spot: [],
  35204. spotLightMap: [],
  35205. spotShadow: [],
  35206. spotShadowMap: [],
  35207. spotLightMatrix: [],
  35208. rectArea: [],
  35209. rectAreaLTC1: null,
  35210. rectAreaLTC2: null,
  35211. point: [],
  35212. pointShadow: [],
  35213. pointShadowMap: [],
  35214. pointShadowMatrix: [],
  35215. hemi: [],
  35216. numSpotLightShadowsWithMaps: 0,
  35217. numLightProbes: 0
  35218. };
  35219. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  35220. const vector3 = new Vector3();
  35221. const matrix4 = new Matrix4();
  35222. const matrix42 = new Matrix4();
  35223. function setup( lights ) {
  35224. let r = 0, g = 0, b = 0;
  35225. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  35226. let directionalLength = 0;
  35227. let pointLength = 0;
  35228. let spotLength = 0;
  35229. let rectAreaLength = 0;
  35230. let hemiLength = 0;
  35231. let numDirectionalShadows = 0;
  35232. let numPointShadows = 0;
  35233. let numSpotShadows = 0;
  35234. let numSpotMaps = 0;
  35235. let numSpotShadowsWithMaps = 0;
  35236. let numLightProbes = 0;
  35237. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  35238. lights.sort( shadowCastingAndTexturingLightsFirst );
  35239. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  35240. const light = lights[ i ];
  35241. const color = light.color;
  35242. const intensity = light.intensity;
  35243. const distance = light.distance;
  35244. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  35245. if ( light.isAmbientLight ) {
  35246. r += color.r * intensity;
  35247. g += color.g * intensity;
  35248. b += color.b * intensity;
  35249. } else if ( light.isLightProbe ) {
  35250. for ( let j = 0; j < 9; j ++ ) {
  35251. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  35252. }
  35253. numLightProbes ++;
  35254. } else if ( light.isDirectionalLight ) {
  35255. const uniforms = cache.get( light );
  35256. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  35257. if ( light.castShadow ) {
  35258. const shadow = light.shadow;
  35259. const shadowUniforms = shadowCache.get( light );
  35260. shadowUniforms.shadowIntensity = shadow.intensity;
  35261. shadowUniforms.shadowBias = shadow.bias;
  35262. shadowUniforms.shadowNormalBias = shadow.normalBias;
  35263. shadowUniforms.shadowRadius = shadow.radius;
  35264. shadowUniforms.shadowMapSize = shadow.mapSize;
  35265. state.directionalShadow[ directionalLength ] = shadowUniforms;
  35266. state.directionalShadowMap[ directionalLength ] = shadowMap;
  35267. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  35268. numDirectionalShadows ++;
  35269. }
  35270. state.directional[ directionalLength ] = uniforms;
  35271. directionalLength ++;
  35272. } else if ( light.isSpotLight ) {
  35273. const uniforms = cache.get( light );
  35274. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  35275. uniforms.color.copy( color ).multiplyScalar( intensity );
  35276. uniforms.distance = distance;
  35277. uniforms.coneCos = Math.cos( light.angle );
  35278. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  35279. uniforms.decay = light.decay;
  35280. state.spot[ spotLength ] = uniforms;
  35281. const shadow = light.shadow;
  35282. if ( light.map ) {
  35283. state.spotLightMap[ numSpotMaps ] = light.map;
  35284. numSpotMaps ++;
  35285. // make sure the lightMatrix is up to date
  35286. // TODO : do it if required only
  35287. shadow.updateMatrices( light );
  35288. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  35289. }
  35290. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  35291. if ( light.castShadow ) {
  35292. const shadowUniforms = shadowCache.get( light );
  35293. shadowUniforms.shadowIntensity = shadow.intensity;
  35294. shadowUniforms.shadowBias = shadow.bias;
  35295. shadowUniforms.shadowNormalBias = shadow.normalBias;
  35296. shadowUniforms.shadowRadius = shadow.radius;
  35297. shadowUniforms.shadowMapSize = shadow.mapSize;
  35298. state.spotShadow[ spotLength ] = shadowUniforms;
  35299. state.spotShadowMap[ spotLength ] = shadowMap;
  35300. numSpotShadows ++;
  35301. }
  35302. spotLength ++;
  35303. } else if ( light.isRectAreaLight ) {
  35304. const uniforms = cache.get( light );
  35305. uniforms.color.copy( color ).multiplyScalar( intensity );
  35306. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  35307. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  35308. state.rectArea[ rectAreaLength ] = uniforms;
  35309. rectAreaLength ++;
  35310. } else if ( light.isPointLight ) {
  35311. const uniforms = cache.get( light );
  35312. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  35313. uniforms.distance = light.distance;
  35314. uniforms.decay = light.decay;
  35315. if ( light.castShadow ) {
  35316. const shadow = light.shadow;
  35317. const shadowUniforms = shadowCache.get( light );
  35318. shadowUniforms.shadowIntensity = shadow.intensity;
  35319. shadowUniforms.shadowBias = shadow.bias;
  35320. shadowUniforms.shadowNormalBias = shadow.normalBias;
  35321. shadowUniforms.shadowRadius = shadow.radius;
  35322. shadowUniforms.shadowMapSize = shadow.mapSize;
  35323. shadowUniforms.shadowCameraNear = shadow.camera.near;
  35324. shadowUniforms.shadowCameraFar = shadow.camera.far;
  35325. state.pointShadow[ pointLength ] = shadowUniforms;
  35326. state.pointShadowMap[ pointLength ] = shadowMap;
  35327. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  35328. numPointShadows ++;
  35329. }
  35330. state.point[ pointLength ] = uniforms;
  35331. pointLength ++;
  35332. } else if ( light.isHemisphereLight ) {
  35333. const uniforms = cache.get( light );
  35334. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  35335. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  35336. state.hemi[ hemiLength ] = uniforms;
  35337. hemiLength ++;
  35338. }
  35339. }
  35340. if ( rectAreaLength > 0 ) {
  35341. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  35342. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  35343. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  35344. } else {
  35345. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  35346. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  35347. }
  35348. }
  35349. state.ambient[ 0 ] = r;
  35350. state.ambient[ 1 ] = g;
  35351. state.ambient[ 2 ] = b;
  35352. const hash = state.hash;
  35353. if ( hash.directionalLength !== directionalLength ||
  35354. hash.pointLength !== pointLength ||
  35355. hash.spotLength !== spotLength ||
  35356. hash.rectAreaLength !== rectAreaLength ||
  35357. hash.hemiLength !== hemiLength ||
  35358. hash.numDirectionalShadows !== numDirectionalShadows ||
  35359. hash.numPointShadows !== numPointShadows ||
  35360. hash.numSpotShadows !== numSpotShadows ||
  35361. hash.numSpotMaps !== numSpotMaps ||
  35362. hash.numLightProbes !== numLightProbes ) {
  35363. state.directional.length = directionalLength;
  35364. state.spot.length = spotLength;
  35365. state.rectArea.length = rectAreaLength;
  35366. state.point.length = pointLength;
  35367. state.hemi.length = hemiLength;
  35368. state.directionalShadow.length = numDirectionalShadows;
  35369. state.directionalShadowMap.length = numDirectionalShadows;
  35370. state.pointShadow.length = numPointShadows;
  35371. state.pointShadowMap.length = numPointShadows;
  35372. state.spotShadow.length = numSpotShadows;
  35373. state.spotShadowMap.length = numSpotShadows;
  35374. state.directionalShadowMatrix.length = numDirectionalShadows;
  35375. state.pointShadowMatrix.length = numPointShadows;
  35376. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  35377. state.spotLightMap.length = numSpotMaps;
  35378. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  35379. state.numLightProbes = numLightProbes;
  35380. hash.directionalLength = directionalLength;
  35381. hash.pointLength = pointLength;
  35382. hash.spotLength = spotLength;
  35383. hash.rectAreaLength = rectAreaLength;
  35384. hash.hemiLength = hemiLength;
  35385. hash.numDirectionalShadows = numDirectionalShadows;
  35386. hash.numPointShadows = numPointShadows;
  35387. hash.numSpotShadows = numSpotShadows;
  35388. hash.numSpotMaps = numSpotMaps;
  35389. hash.numLightProbes = numLightProbes;
  35390. state.version = nextVersion ++;
  35391. }
  35392. }
  35393. function setupView( lights, camera ) {
  35394. let directionalLength = 0;
  35395. let pointLength = 0;
  35396. let spotLength = 0;
  35397. let rectAreaLength = 0;
  35398. let hemiLength = 0;
  35399. const viewMatrix = camera.matrixWorldInverse;
  35400. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  35401. const light = lights[ i ];
  35402. if ( light.isDirectionalLight ) {
  35403. const uniforms = state.directional[ directionalLength ];
  35404. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  35405. vector3.setFromMatrixPosition( light.target.matrixWorld );
  35406. uniforms.direction.sub( vector3 );
  35407. uniforms.direction.transformDirection( viewMatrix );
  35408. directionalLength ++;
  35409. } else if ( light.isSpotLight ) {
  35410. const uniforms = state.spot[ spotLength ];
  35411. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  35412. uniforms.position.applyMatrix4( viewMatrix );
  35413. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  35414. vector3.setFromMatrixPosition( light.target.matrixWorld );
  35415. uniforms.direction.sub( vector3 );
  35416. uniforms.direction.transformDirection( viewMatrix );
  35417. spotLength ++;
  35418. } else if ( light.isRectAreaLight ) {
  35419. const uniforms = state.rectArea[ rectAreaLength ];
  35420. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  35421. uniforms.position.applyMatrix4( viewMatrix );
  35422. // extract local rotation of light to derive width/height half vectors
  35423. matrix42.identity();
  35424. matrix4.copy( light.matrixWorld );
  35425. matrix4.premultiply( viewMatrix );
  35426. matrix42.extractRotation( matrix4 );
  35427. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  35428. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  35429. uniforms.halfWidth.applyMatrix4( matrix42 );
  35430. uniforms.halfHeight.applyMatrix4( matrix42 );
  35431. rectAreaLength ++;
  35432. } else if ( light.isPointLight ) {
  35433. const uniforms = state.point[ pointLength ];
  35434. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  35435. uniforms.position.applyMatrix4( viewMatrix );
  35436. pointLength ++;
  35437. } else if ( light.isHemisphereLight ) {
  35438. const uniforms = state.hemi[ hemiLength ];
  35439. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  35440. uniforms.direction.transformDirection( viewMatrix );
  35441. hemiLength ++;
  35442. }
  35443. }
  35444. }
  35445. return {
  35446. setup: setup,
  35447. setupView: setupView,
  35448. state: state
  35449. };
  35450. }
  35451. function WebGLRenderState( extensions ) {
  35452. const lights = new WebGLLights( extensions );
  35453. const lightsArray = [];
  35454. const shadowsArray = [];
  35455. function init( camera ) {
  35456. state.camera = camera;
  35457. lightsArray.length = 0;
  35458. shadowsArray.length = 0;
  35459. }
  35460. function pushLight( light ) {
  35461. lightsArray.push( light );
  35462. }
  35463. function pushShadow( shadowLight ) {
  35464. shadowsArray.push( shadowLight );
  35465. }
  35466. function setupLights() {
  35467. lights.setup( lightsArray );
  35468. }
  35469. function setupLightsView( camera ) {
  35470. lights.setupView( lightsArray, camera );
  35471. }
  35472. const state = {
  35473. lightsArray: lightsArray,
  35474. shadowsArray: shadowsArray,
  35475. camera: null,
  35476. lights: lights,
  35477. transmissionRenderTarget: {}
  35478. };
  35479. return {
  35480. init: init,
  35481. state: state,
  35482. setupLights: setupLights,
  35483. setupLightsView: setupLightsView,
  35484. pushLight: pushLight,
  35485. pushShadow: pushShadow
  35486. };
  35487. }
  35488. function WebGLRenderStates( extensions ) {
  35489. let renderStates = new WeakMap();
  35490. function get( scene, renderCallDepth = 0 ) {
  35491. const renderStateArray = renderStates.get( scene );
  35492. let renderState;
  35493. if ( renderStateArray === undefined ) {
  35494. renderState = new WebGLRenderState( extensions );
  35495. renderStates.set( scene, [ renderState ] );
  35496. } else {
  35497. if ( renderCallDepth >= renderStateArray.length ) {
  35498. renderState = new WebGLRenderState( extensions );
  35499. renderStateArray.push( renderState );
  35500. } else {
  35501. renderState = renderStateArray[ renderCallDepth ];
  35502. }
  35503. }
  35504. return renderState;
  35505. }
  35506. function dispose() {
  35507. renderStates = new WeakMap();
  35508. }
  35509. return {
  35510. get: get,
  35511. dispose: dispose
  35512. };
  35513. }
  35514. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  35515. 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}";
  35516. function WebGLShadowMap( renderer, objects, capabilities ) {
  35517. let _frustum = new Frustum();
  35518. const _shadowMapSize = new Vector2(),
  35519. _viewportSize = new Vector2(),
  35520. _viewport = new Vector4(),
  35521. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  35522. _distanceMaterial = new MeshDistanceMaterial(),
  35523. _materialCache = {},
  35524. _maxTextureSize = capabilities.maxTextureSize;
  35525. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  35526. const shadowMaterialVertical = new ShaderMaterial( {
  35527. defines: {
  35528. VSM_SAMPLES: 8
  35529. },
  35530. uniforms: {
  35531. shadow_pass: { value: null },
  35532. resolution: { value: new Vector2() },
  35533. radius: { value: 4.0 }
  35534. },
  35535. vertexShader: vertex,
  35536. fragmentShader: fragment
  35537. } );
  35538. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  35539. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  35540. const fullScreenTri = new BufferGeometry();
  35541. fullScreenTri.setAttribute(
  35542. 'position',
  35543. new BufferAttribute(
  35544. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  35545. 3
  35546. )
  35547. );
  35548. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  35549. const scope = this;
  35550. this.enabled = false;
  35551. this.autoUpdate = true;
  35552. this.needsUpdate = false;
  35553. this.type = PCFShadowMap;
  35554. let _previousType = this.type;
  35555. this.render = function ( lights, scene, camera ) {
  35556. if ( scope.enabled === false ) return;
  35557. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  35558. if ( lights.length === 0 ) return;
  35559. const currentRenderTarget = renderer.getRenderTarget();
  35560. const activeCubeFace = renderer.getActiveCubeFace();
  35561. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  35562. const _state = renderer.state;
  35563. // Set GL state for depth map.
  35564. _state.setBlending( NoBlending );
  35565. _state.buffers.color.setClear( 1, 1, 1, 1 );
  35566. _state.buffers.depth.setTest( true );
  35567. _state.setScissorTest( false );
  35568. // check for shadow map type changes
  35569. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  35570. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  35571. // render depth map
  35572. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  35573. const light = lights[ i ];
  35574. const shadow = light.shadow;
  35575. if ( shadow === undefined ) {
  35576. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  35577. continue;
  35578. }
  35579. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  35580. _shadowMapSize.copy( shadow.mapSize );
  35581. const shadowFrameExtents = shadow.getFrameExtents();
  35582. _shadowMapSize.multiply( shadowFrameExtents );
  35583. _viewportSize.copy( shadow.mapSize );
  35584. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  35585. if ( _shadowMapSize.x > _maxTextureSize ) {
  35586. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  35587. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  35588. shadow.mapSize.x = _viewportSize.x;
  35589. }
  35590. if ( _shadowMapSize.y > _maxTextureSize ) {
  35591. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  35592. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  35593. shadow.mapSize.y = _viewportSize.y;
  35594. }
  35595. }
  35596. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  35597. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  35598. if ( shadow.map !== null ) {
  35599. shadow.map.dispose();
  35600. }
  35601. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  35602. shadow.map.texture.name = light.name + '.shadowMap';
  35603. shadow.camera.updateProjectionMatrix();
  35604. }
  35605. renderer.setRenderTarget( shadow.map );
  35606. renderer.clear();
  35607. const viewportCount = shadow.getViewportCount();
  35608. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  35609. const viewport = shadow.getViewport( vp );
  35610. _viewport.set(
  35611. _viewportSize.x * viewport.x,
  35612. _viewportSize.y * viewport.y,
  35613. _viewportSize.x * viewport.z,
  35614. _viewportSize.y * viewport.w
  35615. );
  35616. _state.viewport( _viewport );
  35617. shadow.updateMatrices( light, vp );
  35618. _frustum = shadow.getFrustum();
  35619. renderObject( scene, camera, shadow.camera, light, this.type );
  35620. }
  35621. // do blur pass for VSM
  35622. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  35623. VSMPass( shadow, camera );
  35624. }
  35625. shadow.needsUpdate = false;
  35626. }
  35627. _previousType = this.type;
  35628. scope.needsUpdate = false;
  35629. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  35630. };
  35631. function VSMPass( shadow, camera ) {
  35632. const geometry = objects.update( fullScreenMesh );
  35633. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  35634. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  35635. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  35636. shadowMaterialVertical.needsUpdate = true;
  35637. shadowMaterialHorizontal.needsUpdate = true;
  35638. }
  35639. if ( shadow.mapPass === null ) {
  35640. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  35641. }
  35642. // vertical pass
  35643. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  35644. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  35645. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  35646. renderer.setRenderTarget( shadow.mapPass );
  35647. renderer.clear();
  35648. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  35649. // horizontal pass
  35650. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  35651. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  35652. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  35653. renderer.setRenderTarget( shadow.map );
  35654. renderer.clear();
  35655. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  35656. }
  35657. function getDepthMaterial( object, material, light, type ) {
  35658. let result = null;
  35659. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  35660. if ( customMaterial !== undefined ) {
  35661. result = customMaterial;
  35662. } else {
  35663. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  35664. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  35665. ( material.displacementMap && material.displacementScale !== 0 ) ||
  35666. ( material.alphaMap && material.alphaTest > 0 ) ||
  35667. ( material.map && material.alphaTest > 0 ) ) {
  35668. // in this case we need a unique material instance reflecting the
  35669. // appropriate state
  35670. const keyA = result.uuid, keyB = material.uuid;
  35671. let materialsForVariant = _materialCache[ keyA ];
  35672. if ( materialsForVariant === undefined ) {
  35673. materialsForVariant = {};
  35674. _materialCache[ keyA ] = materialsForVariant;
  35675. }
  35676. let cachedMaterial = materialsForVariant[ keyB ];
  35677. if ( cachedMaterial === undefined ) {
  35678. cachedMaterial = result.clone();
  35679. materialsForVariant[ keyB ] = cachedMaterial;
  35680. material.addEventListener( 'dispose', onMaterialDispose );
  35681. }
  35682. result = cachedMaterial;
  35683. }
  35684. }
  35685. result.visible = material.visible;
  35686. result.wireframe = material.wireframe;
  35687. if ( type === VSMShadowMap ) {
  35688. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  35689. } else {
  35690. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  35691. }
  35692. result.alphaMap = material.alphaMap;
  35693. result.alphaTest = material.alphaTest;
  35694. result.map = material.map;
  35695. result.clipShadows = material.clipShadows;
  35696. result.clippingPlanes = material.clippingPlanes;
  35697. result.clipIntersection = material.clipIntersection;
  35698. result.displacementMap = material.displacementMap;
  35699. result.displacementScale = material.displacementScale;
  35700. result.displacementBias = material.displacementBias;
  35701. result.wireframeLinewidth = material.wireframeLinewidth;
  35702. result.linewidth = material.linewidth;
  35703. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  35704. const materialProperties = renderer.properties.get( result );
  35705. materialProperties.light = light;
  35706. }
  35707. return result;
  35708. }
  35709. function renderObject( object, camera, shadowCamera, light, type ) {
  35710. if ( object.visible === false ) return;
  35711. const visible = object.layers.test( camera.layers );
  35712. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  35713. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  35714. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  35715. const geometry = objects.update( object );
  35716. const material = object.material;
  35717. if ( Array.isArray( material ) ) {
  35718. const groups = geometry.groups;
  35719. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  35720. const group = groups[ k ];
  35721. const groupMaterial = material[ group.materialIndex ];
  35722. if ( groupMaterial && groupMaterial.visible ) {
  35723. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  35724. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  35725. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  35726. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  35727. }
  35728. }
  35729. } else if ( material.visible ) {
  35730. const depthMaterial = getDepthMaterial( object, material, light, type );
  35731. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  35732. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  35733. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  35734. }
  35735. }
  35736. }
  35737. const children = object.children;
  35738. for ( let i = 0, l = children.length; i < l; i ++ ) {
  35739. renderObject( children[ i ], camera, shadowCamera, light, type );
  35740. }
  35741. }
  35742. function onMaterialDispose( event ) {
  35743. const material = event.target;
  35744. material.removeEventListener( 'dispose', onMaterialDispose );
  35745. // make sure to remove the unique distance/depth materials used for shadow map rendering
  35746. for ( const id in _materialCache ) {
  35747. const cache = _materialCache[ id ];
  35748. const uuid = event.target.uuid;
  35749. if ( uuid in cache ) {
  35750. const shadowMaterial = cache[ uuid ];
  35751. shadowMaterial.dispose();
  35752. delete cache[ uuid ];
  35753. }
  35754. }
  35755. }
  35756. }
  35757. const reversedFuncs = {
  35758. [ NeverDepth ]: AlwaysDepth,
  35759. [ LessDepth ]: GreaterDepth,
  35760. [ EqualDepth ]: NotEqualDepth,
  35761. [ LessEqualDepth ]: GreaterEqualDepth,
  35762. [ AlwaysDepth ]: NeverDepth,
  35763. [ GreaterDepth ]: LessDepth,
  35764. [ NotEqualDepth ]: EqualDepth,
  35765. [ GreaterEqualDepth ]: LessEqualDepth,
  35766. };
  35767. function WebGLState( gl, extensions ) {
  35768. function ColorBuffer() {
  35769. let locked = false;
  35770. const color = new Vector4();
  35771. let currentColorMask = null;
  35772. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  35773. return {
  35774. setMask: function ( colorMask ) {
  35775. if ( currentColorMask !== colorMask && ! locked ) {
  35776. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  35777. currentColorMask = colorMask;
  35778. }
  35779. },
  35780. setLocked: function ( lock ) {
  35781. locked = lock;
  35782. },
  35783. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  35784. if ( premultipliedAlpha === true ) {
  35785. r *= a; g *= a; b *= a;
  35786. }
  35787. color.set( r, g, b, a );
  35788. if ( currentColorClear.equals( color ) === false ) {
  35789. gl.clearColor( r, g, b, a );
  35790. currentColorClear.copy( color );
  35791. }
  35792. },
  35793. reset: function () {
  35794. locked = false;
  35795. currentColorMask = null;
  35796. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  35797. }
  35798. };
  35799. }
  35800. function DepthBuffer() {
  35801. let locked = false;
  35802. let reversed = false;
  35803. let currentDepthMask = null;
  35804. let currentDepthFunc = null;
  35805. let currentDepthClear = null;
  35806. return {
  35807. setReversed: function ( value ) {
  35808. if ( reversed !== value ) {
  35809. const ext = extensions.get( 'EXT_clip_control' );
  35810. if ( reversed ) {
  35811. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  35812. } else {
  35813. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  35814. }
  35815. const oldDepth = currentDepthClear;
  35816. currentDepthClear = null;
  35817. this.setClear( oldDepth );
  35818. }
  35819. reversed = value;
  35820. },
  35821. getReversed: function () {
  35822. return reversed;
  35823. },
  35824. setTest: function ( depthTest ) {
  35825. if ( depthTest ) {
  35826. enable( gl.DEPTH_TEST );
  35827. } else {
  35828. disable( gl.DEPTH_TEST );
  35829. }
  35830. },
  35831. setMask: function ( depthMask ) {
  35832. if ( currentDepthMask !== depthMask && ! locked ) {
  35833. gl.depthMask( depthMask );
  35834. currentDepthMask = depthMask;
  35835. }
  35836. },
  35837. setFunc: function ( depthFunc ) {
  35838. if ( reversed ) depthFunc = reversedFuncs[ depthFunc ];
  35839. if ( currentDepthFunc !== depthFunc ) {
  35840. switch ( depthFunc ) {
  35841. case NeverDepth:
  35842. gl.depthFunc( gl.NEVER );
  35843. break;
  35844. case AlwaysDepth:
  35845. gl.depthFunc( gl.ALWAYS );
  35846. break;
  35847. case LessDepth:
  35848. gl.depthFunc( gl.LESS );
  35849. break;
  35850. case LessEqualDepth:
  35851. gl.depthFunc( gl.LEQUAL );
  35852. break;
  35853. case EqualDepth:
  35854. gl.depthFunc( gl.EQUAL );
  35855. break;
  35856. case GreaterEqualDepth:
  35857. gl.depthFunc( gl.GEQUAL );
  35858. break;
  35859. case GreaterDepth:
  35860. gl.depthFunc( gl.GREATER );
  35861. break;
  35862. case NotEqualDepth:
  35863. gl.depthFunc( gl.NOTEQUAL );
  35864. break;
  35865. default:
  35866. gl.depthFunc( gl.LEQUAL );
  35867. }
  35868. currentDepthFunc = depthFunc;
  35869. }
  35870. },
  35871. setLocked: function ( lock ) {
  35872. locked = lock;
  35873. },
  35874. setClear: function ( depth ) {
  35875. if ( currentDepthClear !== depth ) {
  35876. if ( reversed ) {
  35877. depth = 1 - depth;
  35878. }
  35879. gl.clearDepth( depth );
  35880. currentDepthClear = depth;
  35881. }
  35882. },
  35883. reset: function () {
  35884. locked = false;
  35885. currentDepthMask = null;
  35886. currentDepthFunc = null;
  35887. currentDepthClear = null;
  35888. reversed = false;
  35889. }
  35890. };
  35891. }
  35892. function StencilBuffer() {
  35893. let locked = false;
  35894. let currentStencilMask = null;
  35895. let currentStencilFunc = null;
  35896. let currentStencilRef = null;
  35897. let currentStencilFuncMask = null;
  35898. let currentStencilFail = null;
  35899. let currentStencilZFail = null;
  35900. let currentStencilZPass = null;
  35901. let currentStencilClear = null;
  35902. return {
  35903. setTest: function ( stencilTest ) {
  35904. if ( ! locked ) {
  35905. if ( stencilTest ) {
  35906. enable( gl.STENCIL_TEST );
  35907. } else {
  35908. disable( gl.STENCIL_TEST );
  35909. }
  35910. }
  35911. },
  35912. setMask: function ( stencilMask ) {
  35913. if ( currentStencilMask !== stencilMask && ! locked ) {
  35914. gl.stencilMask( stencilMask );
  35915. currentStencilMask = stencilMask;
  35916. }
  35917. },
  35918. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  35919. if ( currentStencilFunc !== stencilFunc ||
  35920. currentStencilRef !== stencilRef ||
  35921. currentStencilFuncMask !== stencilMask ) {
  35922. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  35923. currentStencilFunc = stencilFunc;
  35924. currentStencilRef = stencilRef;
  35925. currentStencilFuncMask = stencilMask;
  35926. }
  35927. },
  35928. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  35929. if ( currentStencilFail !== stencilFail ||
  35930. currentStencilZFail !== stencilZFail ||
  35931. currentStencilZPass !== stencilZPass ) {
  35932. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  35933. currentStencilFail = stencilFail;
  35934. currentStencilZFail = stencilZFail;
  35935. currentStencilZPass = stencilZPass;
  35936. }
  35937. },
  35938. setLocked: function ( lock ) {
  35939. locked = lock;
  35940. },
  35941. setClear: function ( stencil ) {
  35942. if ( currentStencilClear !== stencil ) {
  35943. gl.clearStencil( stencil );
  35944. currentStencilClear = stencil;
  35945. }
  35946. },
  35947. reset: function () {
  35948. locked = false;
  35949. currentStencilMask = null;
  35950. currentStencilFunc = null;
  35951. currentStencilRef = null;
  35952. currentStencilFuncMask = null;
  35953. currentStencilFail = null;
  35954. currentStencilZFail = null;
  35955. currentStencilZPass = null;
  35956. currentStencilClear = null;
  35957. }
  35958. };
  35959. }
  35960. //
  35961. const colorBuffer = new ColorBuffer();
  35962. const depthBuffer = new DepthBuffer();
  35963. const stencilBuffer = new StencilBuffer();
  35964. const uboBindings = new WeakMap();
  35965. const uboProgramMap = new WeakMap();
  35966. let enabledCapabilities = {};
  35967. let currentBoundFramebuffers = {};
  35968. let currentDrawbuffers = new WeakMap();
  35969. let defaultDrawbuffers = [];
  35970. let currentProgram = null;
  35971. let currentBlendingEnabled = false;
  35972. let currentBlending = null;
  35973. let currentBlendEquation = null;
  35974. let currentBlendSrc = null;
  35975. let currentBlendDst = null;
  35976. let currentBlendEquationAlpha = null;
  35977. let currentBlendSrcAlpha = null;
  35978. let currentBlendDstAlpha = null;
  35979. let currentBlendColor = new Color( 0, 0, 0 );
  35980. let currentBlendAlpha = 0;
  35981. let currentPremultipledAlpha = false;
  35982. let currentFlipSided = null;
  35983. let currentCullFace = null;
  35984. let currentLineWidth = null;
  35985. let currentPolygonOffsetFactor = null;
  35986. let currentPolygonOffsetUnits = null;
  35987. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  35988. let lineWidthAvailable = false;
  35989. let version = 0;
  35990. const glVersion = gl.getParameter( gl.VERSION );
  35991. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  35992. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  35993. lineWidthAvailable = ( version >= 1.0 );
  35994. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  35995. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  35996. lineWidthAvailable = ( version >= 2.0 );
  35997. }
  35998. let currentTextureSlot = null;
  35999. let currentBoundTextures = {};
  36000. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  36001. const viewportParam = gl.getParameter( gl.VIEWPORT );
  36002. const currentScissor = new Vector4().fromArray( scissorParam );
  36003. const currentViewport = new Vector4().fromArray( viewportParam );
  36004. function createTexture( type, target, count, dimensions ) {
  36005. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  36006. const texture = gl.createTexture();
  36007. gl.bindTexture( type, texture );
  36008. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  36009. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  36010. for ( let i = 0; i < count; i ++ ) {
  36011. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  36012. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  36013. } else {
  36014. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  36015. }
  36016. }
  36017. return texture;
  36018. }
  36019. const emptyTextures = {};
  36020. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  36021. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  36022. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  36023. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  36024. // init
  36025. colorBuffer.setClear( 0, 0, 0, 1 );
  36026. depthBuffer.setClear( 1 );
  36027. stencilBuffer.setClear( 0 );
  36028. enable( gl.DEPTH_TEST );
  36029. depthBuffer.setFunc( LessEqualDepth );
  36030. setFlipSided( false );
  36031. setCullFace( CullFaceBack );
  36032. enable( gl.CULL_FACE );
  36033. setBlending( NoBlending );
  36034. //
  36035. function enable( id ) {
  36036. if ( enabledCapabilities[ id ] !== true ) {
  36037. gl.enable( id );
  36038. enabledCapabilities[ id ] = true;
  36039. }
  36040. }
  36041. function disable( id ) {
  36042. if ( enabledCapabilities[ id ] !== false ) {
  36043. gl.disable( id );
  36044. enabledCapabilities[ id ] = false;
  36045. }
  36046. }
  36047. function bindFramebuffer( target, framebuffer ) {
  36048. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  36049. gl.bindFramebuffer( target, framebuffer );
  36050. currentBoundFramebuffers[ target ] = framebuffer;
  36051. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  36052. if ( target === gl.DRAW_FRAMEBUFFER ) {
  36053. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  36054. }
  36055. if ( target === gl.FRAMEBUFFER ) {
  36056. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  36057. }
  36058. return true;
  36059. }
  36060. return false;
  36061. }
  36062. function drawBuffers( renderTarget, framebuffer ) {
  36063. let drawBuffers = defaultDrawbuffers;
  36064. let needsUpdate = false;
  36065. if ( renderTarget ) {
  36066. drawBuffers = currentDrawbuffers.get( framebuffer );
  36067. if ( drawBuffers === undefined ) {
  36068. drawBuffers = [];
  36069. currentDrawbuffers.set( framebuffer, drawBuffers );
  36070. }
  36071. const textures = renderTarget.textures;
  36072. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  36073. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  36074. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  36075. }
  36076. drawBuffers.length = textures.length;
  36077. needsUpdate = true;
  36078. }
  36079. } else {
  36080. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  36081. drawBuffers[ 0 ] = gl.BACK;
  36082. needsUpdate = true;
  36083. }
  36084. }
  36085. if ( needsUpdate ) {
  36086. gl.drawBuffers( drawBuffers );
  36087. }
  36088. }
  36089. function useProgram( program ) {
  36090. if ( currentProgram !== program ) {
  36091. gl.useProgram( program );
  36092. currentProgram = program;
  36093. return true;
  36094. }
  36095. return false;
  36096. }
  36097. const equationToGL = {
  36098. [ AddEquation ]: gl.FUNC_ADD,
  36099. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  36100. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  36101. };
  36102. equationToGL[ MinEquation ] = gl.MIN;
  36103. equationToGL[ MaxEquation ] = gl.MAX;
  36104. const factorToGL = {
  36105. [ ZeroFactor ]: gl.ZERO,
  36106. [ OneFactor ]: gl.ONE,
  36107. [ SrcColorFactor ]: gl.SRC_COLOR,
  36108. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  36109. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  36110. [ DstColorFactor ]: gl.DST_COLOR,
  36111. [ DstAlphaFactor ]: gl.DST_ALPHA,
  36112. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  36113. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  36114. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  36115. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  36116. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  36117. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  36118. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  36119. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  36120. };
  36121. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  36122. if ( blending === NoBlending ) {
  36123. if ( currentBlendingEnabled === true ) {
  36124. disable( gl.BLEND );
  36125. currentBlendingEnabled = false;
  36126. }
  36127. return;
  36128. }
  36129. if ( currentBlendingEnabled === false ) {
  36130. enable( gl.BLEND );
  36131. currentBlendingEnabled = true;
  36132. }
  36133. if ( blending !== CustomBlending ) {
  36134. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  36135. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  36136. gl.blendEquation( gl.FUNC_ADD );
  36137. currentBlendEquation = AddEquation;
  36138. currentBlendEquationAlpha = AddEquation;
  36139. }
  36140. if ( premultipliedAlpha ) {
  36141. switch ( blending ) {
  36142. case NormalBlending:
  36143. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  36144. break;
  36145. case AdditiveBlending:
  36146. gl.blendFunc( gl.ONE, gl.ONE );
  36147. break;
  36148. case SubtractiveBlending:
  36149. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  36150. break;
  36151. case MultiplyBlending:
  36152. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  36153. break;
  36154. default:
  36155. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  36156. break;
  36157. }
  36158. } else {
  36159. switch ( blending ) {
  36160. case NormalBlending:
  36161. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  36162. break;
  36163. case AdditiveBlending:
  36164. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  36165. break;
  36166. case SubtractiveBlending:
  36167. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  36168. break;
  36169. case MultiplyBlending:
  36170. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  36171. break;
  36172. default:
  36173. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  36174. break;
  36175. }
  36176. }
  36177. currentBlendSrc = null;
  36178. currentBlendDst = null;
  36179. currentBlendSrcAlpha = null;
  36180. currentBlendDstAlpha = null;
  36181. currentBlendColor.set( 0, 0, 0 );
  36182. currentBlendAlpha = 0;
  36183. currentBlending = blending;
  36184. currentPremultipledAlpha = premultipliedAlpha;
  36185. }
  36186. return;
  36187. }
  36188. // custom blending
  36189. blendEquationAlpha = blendEquationAlpha || blendEquation;
  36190. blendSrcAlpha = blendSrcAlpha || blendSrc;
  36191. blendDstAlpha = blendDstAlpha || blendDst;
  36192. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  36193. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  36194. currentBlendEquation = blendEquation;
  36195. currentBlendEquationAlpha = blendEquationAlpha;
  36196. }
  36197. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  36198. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  36199. currentBlendSrc = blendSrc;
  36200. currentBlendDst = blendDst;
  36201. currentBlendSrcAlpha = blendSrcAlpha;
  36202. currentBlendDstAlpha = blendDstAlpha;
  36203. }
  36204. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  36205. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  36206. currentBlendColor.copy( blendColor );
  36207. currentBlendAlpha = blendAlpha;
  36208. }
  36209. currentBlending = blending;
  36210. currentPremultipledAlpha = false;
  36211. }
  36212. function setMaterial( material, frontFaceCW ) {
  36213. material.side === DoubleSide
  36214. ? disable( gl.CULL_FACE )
  36215. : enable( gl.CULL_FACE );
  36216. let flipSided = ( material.side === BackSide );
  36217. if ( frontFaceCW ) flipSided = ! flipSided;
  36218. setFlipSided( flipSided );
  36219. ( material.blending === NormalBlending && material.transparent === false )
  36220. ? setBlending( NoBlending )
  36221. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  36222. depthBuffer.setFunc( material.depthFunc );
  36223. depthBuffer.setTest( material.depthTest );
  36224. depthBuffer.setMask( material.depthWrite );
  36225. colorBuffer.setMask( material.colorWrite );
  36226. const stencilWrite = material.stencilWrite;
  36227. stencilBuffer.setTest( stencilWrite );
  36228. if ( stencilWrite ) {
  36229. stencilBuffer.setMask( material.stencilWriteMask );
  36230. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  36231. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  36232. }
  36233. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  36234. material.alphaToCoverage === true
  36235. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  36236. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  36237. }
  36238. //
  36239. function setFlipSided( flipSided ) {
  36240. if ( currentFlipSided !== flipSided ) {
  36241. if ( flipSided ) {
  36242. gl.frontFace( gl.CW );
  36243. } else {
  36244. gl.frontFace( gl.CCW );
  36245. }
  36246. currentFlipSided = flipSided;
  36247. }
  36248. }
  36249. function setCullFace( cullFace ) {
  36250. if ( cullFace !== CullFaceNone ) {
  36251. enable( gl.CULL_FACE );
  36252. if ( cullFace !== currentCullFace ) {
  36253. if ( cullFace === CullFaceBack ) {
  36254. gl.cullFace( gl.BACK );
  36255. } else if ( cullFace === CullFaceFront ) {
  36256. gl.cullFace( gl.FRONT );
  36257. } else {
  36258. gl.cullFace( gl.FRONT_AND_BACK );
  36259. }
  36260. }
  36261. } else {
  36262. disable( gl.CULL_FACE );
  36263. }
  36264. currentCullFace = cullFace;
  36265. }
  36266. function setLineWidth( width ) {
  36267. if ( width !== currentLineWidth ) {
  36268. if ( lineWidthAvailable ) gl.lineWidth( width );
  36269. currentLineWidth = width;
  36270. }
  36271. }
  36272. function setPolygonOffset( polygonOffset, factor, units ) {
  36273. if ( polygonOffset ) {
  36274. enable( gl.POLYGON_OFFSET_FILL );
  36275. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  36276. gl.polygonOffset( factor, units );
  36277. currentPolygonOffsetFactor = factor;
  36278. currentPolygonOffsetUnits = units;
  36279. }
  36280. } else {
  36281. disable( gl.POLYGON_OFFSET_FILL );
  36282. }
  36283. }
  36284. function setScissorTest( scissorTest ) {
  36285. if ( scissorTest ) {
  36286. enable( gl.SCISSOR_TEST );
  36287. } else {
  36288. disable( gl.SCISSOR_TEST );
  36289. }
  36290. }
  36291. // texture
  36292. function activeTexture( webglSlot ) {
  36293. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  36294. if ( currentTextureSlot !== webglSlot ) {
  36295. gl.activeTexture( webglSlot );
  36296. currentTextureSlot = webglSlot;
  36297. }
  36298. }
  36299. function bindTexture( webglType, webglTexture, webglSlot ) {
  36300. if ( webglSlot === undefined ) {
  36301. if ( currentTextureSlot === null ) {
  36302. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  36303. } else {
  36304. webglSlot = currentTextureSlot;
  36305. }
  36306. }
  36307. let boundTexture = currentBoundTextures[ webglSlot ];
  36308. if ( boundTexture === undefined ) {
  36309. boundTexture = { type: undefined, texture: undefined };
  36310. currentBoundTextures[ webglSlot ] = boundTexture;
  36311. }
  36312. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  36313. if ( currentTextureSlot !== webglSlot ) {
  36314. gl.activeTexture( webglSlot );
  36315. currentTextureSlot = webglSlot;
  36316. }
  36317. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  36318. boundTexture.type = webglType;
  36319. boundTexture.texture = webglTexture;
  36320. }
  36321. }
  36322. function unbindTexture() {
  36323. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  36324. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  36325. gl.bindTexture( boundTexture.type, null );
  36326. boundTexture.type = undefined;
  36327. boundTexture.texture = undefined;
  36328. }
  36329. }
  36330. function compressedTexImage2D() {
  36331. try {
  36332. gl.compressedTexImage2D( ...arguments );
  36333. } catch ( error ) {
  36334. console.error( 'THREE.WebGLState:', error );
  36335. }
  36336. }
  36337. function compressedTexImage3D() {
  36338. try {
  36339. gl.compressedTexImage3D( ...arguments );
  36340. } catch ( error ) {
  36341. console.error( 'THREE.WebGLState:', error );
  36342. }
  36343. }
  36344. function texSubImage2D() {
  36345. try {
  36346. gl.texSubImage2D( ...arguments );
  36347. } catch ( error ) {
  36348. console.error( 'THREE.WebGLState:', error );
  36349. }
  36350. }
  36351. function texSubImage3D() {
  36352. try {
  36353. gl.texSubImage3D( ...arguments );
  36354. } catch ( error ) {
  36355. console.error( 'THREE.WebGLState:', error );
  36356. }
  36357. }
  36358. function compressedTexSubImage2D() {
  36359. try {
  36360. gl.compressedTexSubImage2D( ...arguments );
  36361. } catch ( error ) {
  36362. console.error( 'THREE.WebGLState:', error );
  36363. }
  36364. }
  36365. function compressedTexSubImage3D() {
  36366. try {
  36367. gl.compressedTexSubImage3D( ...arguments );
  36368. } catch ( error ) {
  36369. console.error( 'THREE.WebGLState:', error );
  36370. }
  36371. }
  36372. function texStorage2D() {
  36373. try {
  36374. gl.texStorage2D( ...arguments );
  36375. } catch ( error ) {
  36376. console.error( 'THREE.WebGLState:', error );
  36377. }
  36378. }
  36379. function texStorage3D() {
  36380. try {
  36381. gl.texStorage3D( ...arguments );
  36382. } catch ( error ) {
  36383. console.error( 'THREE.WebGLState:', error );
  36384. }
  36385. }
  36386. function texImage2D() {
  36387. try {
  36388. gl.texImage2D( ...arguments );
  36389. } catch ( error ) {
  36390. console.error( 'THREE.WebGLState:', error );
  36391. }
  36392. }
  36393. function texImage3D() {
  36394. try {
  36395. gl.texImage3D( ...arguments );
  36396. } catch ( error ) {
  36397. console.error( 'THREE.WebGLState:', error );
  36398. }
  36399. }
  36400. //
  36401. function scissor( scissor ) {
  36402. if ( currentScissor.equals( scissor ) === false ) {
  36403. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  36404. currentScissor.copy( scissor );
  36405. }
  36406. }
  36407. function viewport( viewport ) {
  36408. if ( currentViewport.equals( viewport ) === false ) {
  36409. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  36410. currentViewport.copy( viewport );
  36411. }
  36412. }
  36413. function updateUBOMapping( uniformsGroup, program ) {
  36414. let mapping = uboProgramMap.get( program );
  36415. if ( mapping === undefined ) {
  36416. mapping = new WeakMap();
  36417. uboProgramMap.set( program, mapping );
  36418. }
  36419. let blockIndex = mapping.get( uniformsGroup );
  36420. if ( blockIndex === undefined ) {
  36421. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  36422. mapping.set( uniformsGroup, blockIndex );
  36423. }
  36424. }
  36425. function uniformBlockBinding( uniformsGroup, program ) {
  36426. const mapping = uboProgramMap.get( program );
  36427. const blockIndex = mapping.get( uniformsGroup );
  36428. if ( uboBindings.get( program ) !== blockIndex ) {
  36429. // bind shader specific block index to global block point
  36430. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  36431. uboBindings.set( program, blockIndex );
  36432. }
  36433. }
  36434. //
  36435. function reset() {
  36436. // reset state
  36437. gl.disable( gl.BLEND );
  36438. gl.disable( gl.CULL_FACE );
  36439. gl.disable( gl.DEPTH_TEST );
  36440. gl.disable( gl.POLYGON_OFFSET_FILL );
  36441. gl.disable( gl.SCISSOR_TEST );
  36442. gl.disable( gl.STENCIL_TEST );
  36443. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  36444. gl.blendEquation( gl.FUNC_ADD );
  36445. gl.blendFunc( gl.ONE, gl.ZERO );
  36446. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  36447. gl.blendColor( 0, 0, 0, 0 );
  36448. gl.colorMask( true, true, true, true );
  36449. gl.clearColor( 0, 0, 0, 0 );
  36450. gl.depthMask( true );
  36451. gl.depthFunc( gl.LESS );
  36452. depthBuffer.setReversed( false );
  36453. gl.clearDepth( 1 );
  36454. gl.stencilMask( 0xffffffff );
  36455. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  36456. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  36457. gl.clearStencil( 0 );
  36458. gl.cullFace( gl.BACK );
  36459. gl.frontFace( gl.CCW );
  36460. gl.polygonOffset( 0, 0 );
  36461. gl.activeTexture( gl.TEXTURE0 );
  36462. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  36463. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  36464. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  36465. gl.useProgram( null );
  36466. gl.lineWidth( 1 );
  36467. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  36468. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  36469. // reset internals
  36470. enabledCapabilities = {};
  36471. currentTextureSlot = null;
  36472. currentBoundTextures = {};
  36473. currentBoundFramebuffers = {};
  36474. currentDrawbuffers = new WeakMap();
  36475. defaultDrawbuffers = [];
  36476. currentProgram = null;
  36477. currentBlendingEnabled = false;
  36478. currentBlending = null;
  36479. currentBlendEquation = null;
  36480. currentBlendSrc = null;
  36481. currentBlendDst = null;
  36482. currentBlendEquationAlpha = null;
  36483. currentBlendSrcAlpha = null;
  36484. currentBlendDstAlpha = null;
  36485. currentBlendColor = new Color( 0, 0, 0 );
  36486. currentBlendAlpha = 0;
  36487. currentPremultipledAlpha = false;
  36488. currentFlipSided = null;
  36489. currentCullFace = null;
  36490. currentLineWidth = null;
  36491. currentPolygonOffsetFactor = null;
  36492. currentPolygonOffsetUnits = null;
  36493. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  36494. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  36495. colorBuffer.reset();
  36496. depthBuffer.reset();
  36497. stencilBuffer.reset();
  36498. }
  36499. return {
  36500. buffers: {
  36501. color: colorBuffer,
  36502. depth: depthBuffer,
  36503. stencil: stencilBuffer
  36504. },
  36505. enable: enable,
  36506. disable: disable,
  36507. bindFramebuffer: bindFramebuffer,
  36508. drawBuffers: drawBuffers,
  36509. useProgram: useProgram,
  36510. setBlending: setBlending,
  36511. setMaterial: setMaterial,
  36512. setFlipSided: setFlipSided,
  36513. setCullFace: setCullFace,
  36514. setLineWidth: setLineWidth,
  36515. setPolygonOffset: setPolygonOffset,
  36516. setScissorTest: setScissorTest,
  36517. activeTexture: activeTexture,
  36518. bindTexture: bindTexture,
  36519. unbindTexture: unbindTexture,
  36520. compressedTexImage2D: compressedTexImage2D,
  36521. compressedTexImage3D: compressedTexImage3D,
  36522. texImage2D: texImage2D,
  36523. texImage3D: texImage3D,
  36524. updateUBOMapping: updateUBOMapping,
  36525. uniformBlockBinding: uniformBlockBinding,
  36526. texStorage2D: texStorage2D,
  36527. texStorage3D: texStorage3D,
  36528. texSubImage2D: texSubImage2D,
  36529. texSubImage3D: texSubImage3D,
  36530. compressedTexSubImage2D: compressedTexSubImage2D,
  36531. compressedTexSubImage3D: compressedTexSubImage3D,
  36532. scissor: scissor,
  36533. viewport: viewport,
  36534. reset: reset
  36535. };
  36536. }
  36537. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  36538. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  36539. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  36540. const _imageDimensions = new Vector2();
  36541. const _videoTextures = new WeakMap();
  36542. let _canvas;
  36543. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  36544. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  36545. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  36546. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  36547. let useOffscreenCanvas = false;
  36548. try {
  36549. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  36550. // eslint-disable-next-line compat/compat
  36551. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  36552. } catch ( err ) {
  36553. // Ignore any errors
  36554. }
  36555. function createCanvas( width, height ) {
  36556. // Use OffscreenCanvas when available. Specially needed in web workers
  36557. return useOffscreenCanvas ?
  36558. // eslint-disable-next-line compat/compat
  36559. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  36560. }
  36561. function resizeImage( image, needsNewCanvas, maxSize ) {
  36562. let scale = 1;
  36563. const dimensions = getDimensions( image );
  36564. // handle case if texture exceeds max size
  36565. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  36566. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  36567. }
  36568. // only perform resize if necessary
  36569. if ( scale < 1 ) {
  36570. // only perform resize for certain image types
  36571. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  36572. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  36573. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  36574. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  36575. const width = Math.floor( scale * dimensions.width );
  36576. const height = Math.floor( scale * dimensions.height );
  36577. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  36578. // cube textures can't reuse the same canvas
  36579. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  36580. canvas.width = width;
  36581. canvas.height = height;
  36582. const context = canvas.getContext( '2d' );
  36583. context.drawImage( image, 0, 0, width, height );
  36584. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  36585. return canvas;
  36586. } else {
  36587. if ( 'data' in image ) {
  36588. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  36589. }
  36590. return image;
  36591. }
  36592. }
  36593. return image;
  36594. }
  36595. function textureNeedsGenerateMipmaps( texture ) {
  36596. return texture.generateMipmaps;
  36597. }
  36598. function generateMipmap( target ) {
  36599. _gl.generateMipmap( target );
  36600. }
  36601. function getTargetType( texture ) {
  36602. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  36603. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  36604. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  36605. return _gl.TEXTURE_2D;
  36606. }
  36607. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  36608. if ( internalFormatName !== null ) {
  36609. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  36610. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  36611. }
  36612. let internalFormat = glFormat;
  36613. if ( glFormat === _gl.RED ) {
  36614. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  36615. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  36616. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  36617. }
  36618. if ( glFormat === _gl.RED_INTEGER ) {
  36619. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  36620. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  36621. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  36622. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  36623. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  36624. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  36625. }
  36626. if ( glFormat === _gl.RG ) {
  36627. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  36628. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  36629. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  36630. }
  36631. if ( glFormat === _gl.RG_INTEGER ) {
  36632. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  36633. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  36634. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  36635. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  36636. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  36637. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  36638. }
  36639. if ( glFormat === _gl.RGB_INTEGER ) {
  36640. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  36641. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  36642. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  36643. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  36644. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  36645. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  36646. }
  36647. if ( glFormat === _gl.RGBA_INTEGER ) {
  36648. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  36649. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  36650. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  36651. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  36652. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  36653. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  36654. }
  36655. if ( glFormat === _gl.RGB ) {
  36656. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  36657. }
  36658. if ( glFormat === _gl.RGBA ) {
  36659. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  36660. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  36661. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  36662. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  36663. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  36664. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  36665. }
  36666. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  36667. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  36668. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  36669. extensions.get( 'EXT_color_buffer_float' );
  36670. }
  36671. return internalFormat;
  36672. }
  36673. function getInternalDepthFormat( useStencil, depthType ) {
  36674. let glInternalFormat;
  36675. if ( useStencil ) {
  36676. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  36677. glInternalFormat = _gl.DEPTH24_STENCIL8;
  36678. } else if ( depthType === FloatType ) {
  36679. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  36680. } else if ( depthType === UnsignedShortType ) {
  36681. glInternalFormat = _gl.DEPTH24_STENCIL8;
  36682. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  36683. }
  36684. } else {
  36685. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  36686. glInternalFormat = _gl.DEPTH_COMPONENT24;
  36687. } else if ( depthType === FloatType ) {
  36688. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  36689. } else if ( depthType === UnsignedShortType ) {
  36690. glInternalFormat = _gl.DEPTH_COMPONENT16;
  36691. }
  36692. }
  36693. return glInternalFormat;
  36694. }
  36695. function getMipLevels( texture, image ) {
  36696. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  36697. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  36698. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  36699. // user-defined mipmaps
  36700. return texture.mipmaps.length;
  36701. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  36702. return image.mipmaps.length;
  36703. } else {
  36704. // texture without mipmaps (only base level)
  36705. return 1;
  36706. }
  36707. }
  36708. //
  36709. function onTextureDispose( event ) {
  36710. const texture = event.target;
  36711. texture.removeEventListener( 'dispose', onTextureDispose );
  36712. deallocateTexture( texture );
  36713. if ( texture.isVideoTexture ) {
  36714. _videoTextures.delete( texture );
  36715. }
  36716. }
  36717. function onRenderTargetDispose( event ) {
  36718. const renderTarget = event.target;
  36719. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  36720. deallocateRenderTarget( renderTarget );
  36721. }
  36722. //
  36723. function deallocateTexture( texture ) {
  36724. const textureProperties = properties.get( texture );
  36725. if ( textureProperties.__webglInit === undefined ) return;
  36726. // check if it's necessary to remove the WebGLTexture object
  36727. const source = texture.source;
  36728. const webglTextures = _sources.get( source );
  36729. if ( webglTextures ) {
  36730. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  36731. webglTexture.usedTimes --;
  36732. // the WebGLTexture object is not used anymore, remove it
  36733. if ( webglTexture.usedTimes === 0 ) {
  36734. deleteTexture( texture );
  36735. }
  36736. // remove the weak map entry if no WebGLTexture uses the source anymore
  36737. if ( Object.keys( webglTextures ).length === 0 ) {
  36738. _sources.delete( source );
  36739. }
  36740. }
  36741. properties.remove( texture );
  36742. }
  36743. function deleteTexture( texture ) {
  36744. const textureProperties = properties.get( texture );
  36745. _gl.deleteTexture( textureProperties.__webglTexture );
  36746. const source = texture.source;
  36747. const webglTextures = _sources.get( source );
  36748. delete webglTextures[ textureProperties.__cacheKey ];
  36749. info.memory.textures --;
  36750. }
  36751. function deallocateRenderTarget( renderTarget ) {
  36752. const renderTargetProperties = properties.get( renderTarget );
  36753. if ( renderTarget.depthTexture ) {
  36754. renderTarget.depthTexture.dispose();
  36755. properties.remove( renderTarget.depthTexture );
  36756. }
  36757. if ( renderTarget.isWebGLCubeRenderTarget ) {
  36758. for ( let i = 0; i < 6; i ++ ) {
  36759. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  36760. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  36761. } else {
  36762. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  36763. }
  36764. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  36765. }
  36766. } else {
  36767. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  36768. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  36769. } else {
  36770. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  36771. }
  36772. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  36773. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  36774. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  36775. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  36776. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  36777. }
  36778. }
  36779. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  36780. }
  36781. const textures = renderTarget.textures;
  36782. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  36783. const attachmentProperties = properties.get( textures[ i ] );
  36784. if ( attachmentProperties.__webglTexture ) {
  36785. _gl.deleteTexture( attachmentProperties.__webglTexture );
  36786. info.memory.textures --;
  36787. }
  36788. properties.remove( textures[ i ] );
  36789. }
  36790. properties.remove( renderTarget );
  36791. }
  36792. //
  36793. let textureUnits = 0;
  36794. function resetTextureUnits() {
  36795. textureUnits = 0;
  36796. }
  36797. function allocateTextureUnit() {
  36798. const textureUnit = textureUnits;
  36799. if ( textureUnit >= capabilities.maxTextures ) {
  36800. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  36801. }
  36802. textureUnits += 1;
  36803. return textureUnit;
  36804. }
  36805. function getTextureCacheKey( texture ) {
  36806. const array = [];
  36807. array.push( texture.wrapS );
  36808. array.push( texture.wrapT );
  36809. array.push( texture.wrapR || 0 );
  36810. array.push( texture.magFilter );
  36811. array.push( texture.minFilter );
  36812. array.push( texture.anisotropy );
  36813. array.push( texture.internalFormat );
  36814. array.push( texture.format );
  36815. array.push( texture.type );
  36816. array.push( texture.generateMipmaps );
  36817. array.push( texture.premultiplyAlpha );
  36818. array.push( texture.flipY );
  36819. array.push( texture.unpackAlignment );
  36820. array.push( texture.colorSpace );
  36821. return array.join();
  36822. }
  36823. //
  36824. function setTexture2D( texture, slot ) {
  36825. const textureProperties = properties.get( texture );
  36826. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  36827. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  36828. const image = texture.image;
  36829. if ( image === null ) {
  36830. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  36831. } else if ( image.complete === false ) {
  36832. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  36833. } else {
  36834. uploadTexture( textureProperties, texture, slot );
  36835. return;
  36836. }
  36837. }
  36838. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  36839. }
  36840. function setTexture2DArray( texture, slot ) {
  36841. const textureProperties = properties.get( texture );
  36842. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  36843. uploadTexture( textureProperties, texture, slot );
  36844. return;
  36845. }
  36846. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  36847. }
  36848. function setTexture3D( texture, slot ) {
  36849. const textureProperties = properties.get( texture );
  36850. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  36851. uploadTexture( textureProperties, texture, slot );
  36852. return;
  36853. }
  36854. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  36855. }
  36856. function setTextureCube( texture, slot ) {
  36857. const textureProperties = properties.get( texture );
  36858. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  36859. uploadCubeTexture( textureProperties, texture, slot );
  36860. return;
  36861. }
  36862. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  36863. }
  36864. const wrappingToGL = {
  36865. [ RepeatWrapping ]: _gl.REPEAT,
  36866. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  36867. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  36868. };
  36869. const filterToGL = {
  36870. [ NearestFilter ]: _gl.NEAREST,
  36871. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  36872. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  36873. [ LinearFilter ]: _gl.LINEAR,
  36874. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  36875. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  36876. };
  36877. const compareToGL = {
  36878. [ NeverCompare ]: _gl.NEVER,
  36879. [ AlwaysCompare ]: _gl.ALWAYS,
  36880. [ LessCompare ]: _gl.LESS,
  36881. [ LessEqualCompare ]: _gl.LEQUAL,
  36882. [ EqualCompare ]: _gl.EQUAL,
  36883. [ GreaterEqualCompare ]: _gl.GEQUAL,
  36884. [ GreaterCompare ]: _gl.GREATER,
  36885. [ NotEqualCompare ]: _gl.NOTEQUAL
  36886. };
  36887. function setTextureParameters( textureType, texture ) {
  36888. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  36889. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36890. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  36891. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  36892. }
  36893. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  36894. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  36895. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  36896. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  36897. }
  36898. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  36899. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  36900. if ( texture.compareFunction ) {
  36901. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  36902. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  36903. }
  36904. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  36905. if ( texture.magFilter === NearestFilter ) return;
  36906. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  36907. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  36908. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  36909. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  36910. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  36911. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  36912. }
  36913. }
  36914. }
  36915. function initTexture( textureProperties, texture ) {
  36916. let forceUpload = false;
  36917. if ( textureProperties.__webglInit === undefined ) {
  36918. textureProperties.__webglInit = true;
  36919. texture.addEventListener( 'dispose', onTextureDispose );
  36920. }
  36921. // create Source <-> WebGLTextures mapping if necessary
  36922. const source = texture.source;
  36923. let webglTextures = _sources.get( source );
  36924. if ( webglTextures === undefined ) {
  36925. webglTextures = {};
  36926. _sources.set( source, webglTextures );
  36927. }
  36928. // check if there is already a WebGLTexture object for the given texture parameters
  36929. const textureCacheKey = getTextureCacheKey( texture );
  36930. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  36931. // if not, create a new instance of WebGLTexture
  36932. if ( webglTextures[ textureCacheKey ] === undefined ) {
  36933. // create new entry
  36934. webglTextures[ textureCacheKey ] = {
  36935. texture: _gl.createTexture(),
  36936. usedTimes: 0
  36937. };
  36938. info.memory.textures ++;
  36939. // when a new instance of WebGLTexture was created, a texture upload is required
  36940. // even if the image contents are identical
  36941. forceUpload = true;
  36942. }
  36943. webglTextures[ textureCacheKey ].usedTimes ++;
  36944. // every time the texture cache key changes, it's necessary to check if an instance of
  36945. // WebGLTexture can be deleted in order to avoid a memory leak.
  36946. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  36947. if ( webglTexture !== undefined ) {
  36948. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  36949. if ( webglTexture.usedTimes === 0 ) {
  36950. deleteTexture( texture );
  36951. }
  36952. }
  36953. // store references to cache key and WebGLTexture object
  36954. textureProperties.__cacheKey = textureCacheKey;
  36955. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  36956. }
  36957. return forceUpload;
  36958. }
  36959. function uploadTexture( textureProperties, texture, slot ) {
  36960. let textureType = _gl.TEXTURE_2D;
  36961. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  36962. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  36963. const forceUpload = initTexture( textureProperties, texture );
  36964. const source = texture.source;
  36965. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  36966. const sourceProperties = properties.get( source );
  36967. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  36968. state.activeTexture( _gl.TEXTURE0 + slot );
  36969. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  36970. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  36971. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  36972. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  36973. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  36974. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  36975. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  36976. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  36977. image = verifyColorSpace( texture, image );
  36978. const glFormat = utils.convert( texture.format, texture.colorSpace );
  36979. const glType = utils.convert( texture.type );
  36980. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  36981. setTextureParameters( textureType, texture );
  36982. let mipmap;
  36983. const mipmaps = texture.mipmaps;
  36984. const useTexStorage = ( texture.isVideoTexture !== true );
  36985. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  36986. const dataReady = source.dataReady;
  36987. const levels = getMipLevels( texture, image );
  36988. if ( texture.isDepthTexture ) {
  36989. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  36990. //
  36991. if ( allocateMemory ) {
  36992. if ( useTexStorage ) {
  36993. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  36994. } else {
  36995. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  36996. }
  36997. }
  36998. } else if ( texture.isDataTexture ) {
  36999. // use manually created mipmaps if available
  37000. // if there are no manual mipmaps
  37001. // set 0 level mipmap and then use GL to generate other mipmap levels
  37002. if ( mipmaps.length > 0 ) {
  37003. if ( useTexStorage && allocateMemory ) {
  37004. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  37005. }
  37006. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  37007. mipmap = mipmaps[ i ];
  37008. if ( useTexStorage ) {
  37009. if ( dataReady ) {
  37010. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  37011. }
  37012. } else {
  37013. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  37014. }
  37015. }
  37016. texture.generateMipmaps = false;
  37017. } else {
  37018. if ( useTexStorage ) {
  37019. if ( allocateMemory ) {
  37020. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  37021. }
  37022. if ( dataReady ) {
  37023. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  37024. }
  37025. } else {
  37026. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  37027. }
  37028. }
  37029. } else if ( texture.isCompressedTexture ) {
  37030. if ( texture.isCompressedArrayTexture ) {
  37031. if ( useTexStorage && allocateMemory ) {
  37032. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  37033. }
  37034. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  37035. mipmap = mipmaps[ i ];
  37036. if ( texture.format !== RGBAFormat ) {
  37037. if ( glFormat !== null ) {
  37038. if ( useTexStorage ) {
  37039. if ( dataReady ) {
  37040. if ( texture.layerUpdates.size > 0 ) {
  37041. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  37042. for ( const layerIndex of texture.layerUpdates ) {
  37043. const layerData = mipmap.data.subarray(
  37044. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  37045. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  37046. );
  37047. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  37048. }
  37049. texture.clearLayerUpdates();
  37050. } else {
  37051. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  37052. }
  37053. }
  37054. } else {
  37055. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  37056. }
  37057. } else {
  37058. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  37059. }
  37060. } else {
  37061. if ( useTexStorage ) {
  37062. if ( dataReady ) {
  37063. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  37064. }
  37065. } else {
  37066. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  37067. }
  37068. }
  37069. }
  37070. } else {
  37071. if ( useTexStorage && allocateMemory ) {
  37072. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  37073. }
  37074. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  37075. mipmap = mipmaps[ i ];
  37076. if ( texture.format !== RGBAFormat ) {
  37077. if ( glFormat !== null ) {
  37078. if ( useTexStorage ) {
  37079. if ( dataReady ) {
  37080. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  37081. }
  37082. } else {
  37083. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  37084. }
  37085. } else {
  37086. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  37087. }
  37088. } else {
  37089. if ( useTexStorage ) {
  37090. if ( dataReady ) {
  37091. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  37092. }
  37093. } else {
  37094. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  37095. }
  37096. }
  37097. }
  37098. }
  37099. } else if ( texture.isDataArrayTexture ) {
  37100. if ( useTexStorage ) {
  37101. if ( allocateMemory ) {
  37102. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  37103. }
  37104. if ( dataReady ) {
  37105. if ( texture.layerUpdates.size > 0 ) {
  37106. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  37107. for ( const layerIndex of texture.layerUpdates ) {
  37108. const layerData = image.data.subarray(
  37109. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  37110. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  37111. );
  37112. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  37113. }
  37114. texture.clearLayerUpdates();
  37115. } else {
  37116. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  37117. }
  37118. }
  37119. } else {
  37120. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  37121. }
  37122. } else if ( texture.isData3DTexture ) {
  37123. if ( useTexStorage ) {
  37124. if ( allocateMemory ) {
  37125. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  37126. }
  37127. if ( dataReady ) {
  37128. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  37129. }
  37130. } else {
  37131. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  37132. }
  37133. } else if ( texture.isFramebufferTexture ) {
  37134. if ( allocateMemory ) {
  37135. if ( useTexStorage ) {
  37136. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  37137. } else {
  37138. let width = image.width, height = image.height;
  37139. for ( let i = 0; i < levels; i ++ ) {
  37140. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  37141. width >>= 1;
  37142. height >>= 1;
  37143. }
  37144. }
  37145. }
  37146. } else {
  37147. // regular Texture (image, video, canvas)
  37148. // use manually created mipmaps if available
  37149. // if there are no manual mipmaps
  37150. // set 0 level mipmap and then use GL to generate other mipmap levels
  37151. if ( mipmaps.length > 0 ) {
  37152. if ( useTexStorage && allocateMemory ) {
  37153. const dimensions = getDimensions( mipmaps[ 0 ] );
  37154. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  37155. }
  37156. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  37157. mipmap = mipmaps[ i ];
  37158. if ( useTexStorage ) {
  37159. if ( dataReady ) {
  37160. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  37161. }
  37162. } else {
  37163. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  37164. }
  37165. }
  37166. texture.generateMipmaps = false;
  37167. } else {
  37168. if ( useTexStorage ) {
  37169. if ( allocateMemory ) {
  37170. const dimensions = getDimensions( image );
  37171. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  37172. }
  37173. if ( dataReady ) {
  37174. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  37175. }
  37176. } else {
  37177. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  37178. }
  37179. }
  37180. }
  37181. if ( textureNeedsGenerateMipmaps( texture ) ) {
  37182. generateMipmap( textureType );
  37183. }
  37184. sourceProperties.__version = source.version;
  37185. if ( texture.onUpdate ) texture.onUpdate( texture );
  37186. }
  37187. textureProperties.__version = texture.version;
  37188. }
  37189. function uploadCubeTexture( textureProperties, texture, slot ) {
  37190. if ( texture.image.length !== 6 ) return;
  37191. const forceUpload = initTexture( textureProperties, texture );
  37192. const source = texture.source;
  37193. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  37194. const sourceProperties = properties.get( source );
  37195. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  37196. state.activeTexture( _gl.TEXTURE0 + slot );
  37197. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  37198. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  37199. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  37200. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  37201. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  37202. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  37203. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  37204. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  37205. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  37206. const cubeImage = [];
  37207. for ( let i = 0; i < 6; i ++ ) {
  37208. if ( ! isCompressed && ! isDataTexture ) {
  37209. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  37210. } else {
  37211. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  37212. }
  37213. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  37214. }
  37215. const image = cubeImage[ 0 ],
  37216. glFormat = utils.convert( texture.format, texture.colorSpace ),
  37217. glType = utils.convert( texture.type ),
  37218. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  37219. const useTexStorage = ( texture.isVideoTexture !== true );
  37220. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  37221. const dataReady = source.dataReady;
  37222. let levels = getMipLevels( texture, image );
  37223. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  37224. let mipmaps;
  37225. if ( isCompressed ) {
  37226. if ( useTexStorage && allocateMemory ) {
  37227. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  37228. }
  37229. for ( let i = 0; i < 6; i ++ ) {
  37230. mipmaps = cubeImage[ i ].mipmaps;
  37231. for ( let j = 0; j < mipmaps.length; j ++ ) {
  37232. const mipmap = mipmaps[ j ];
  37233. if ( texture.format !== RGBAFormat ) {
  37234. if ( glFormat !== null ) {
  37235. if ( useTexStorage ) {
  37236. if ( dataReady ) {
  37237. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  37238. }
  37239. } else {
  37240. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  37241. }
  37242. } else {
  37243. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  37244. }
  37245. } else {
  37246. if ( useTexStorage ) {
  37247. if ( dataReady ) {
  37248. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  37249. }
  37250. } else {
  37251. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  37252. }
  37253. }
  37254. }
  37255. }
  37256. } else {
  37257. mipmaps = texture.mipmaps;
  37258. if ( useTexStorage && allocateMemory ) {
  37259. // TODO: Uniformly handle mipmap definitions
  37260. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  37261. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  37262. if ( mipmaps.length > 0 ) levels ++;
  37263. const dimensions = getDimensions( cubeImage[ 0 ] );
  37264. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  37265. }
  37266. for ( let i = 0; i < 6; i ++ ) {
  37267. if ( isDataTexture ) {
  37268. if ( useTexStorage ) {
  37269. if ( dataReady ) {
  37270. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  37271. }
  37272. } else {
  37273. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  37274. }
  37275. for ( let j = 0; j < mipmaps.length; j ++ ) {
  37276. const mipmap = mipmaps[ j ];
  37277. const mipmapImage = mipmap.image[ i ].image;
  37278. if ( useTexStorage ) {
  37279. if ( dataReady ) {
  37280. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  37281. }
  37282. } else {
  37283. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  37284. }
  37285. }
  37286. } else {
  37287. if ( useTexStorage ) {
  37288. if ( dataReady ) {
  37289. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  37290. }
  37291. } else {
  37292. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  37293. }
  37294. for ( let j = 0; j < mipmaps.length; j ++ ) {
  37295. const mipmap = mipmaps[ j ];
  37296. if ( useTexStorage ) {
  37297. if ( dataReady ) {
  37298. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  37299. }
  37300. } else {
  37301. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  37302. }
  37303. }
  37304. }
  37305. }
  37306. }
  37307. if ( textureNeedsGenerateMipmaps( texture ) ) {
  37308. // We assume images for cube map have the same size.
  37309. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  37310. }
  37311. sourceProperties.__version = source.version;
  37312. if ( texture.onUpdate ) texture.onUpdate( texture );
  37313. }
  37314. textureProperties.__version = texture.version;
  37315. }
  37316. // Render targets
  37317. // Setup storage for target texture and bind it to correct framebuffer
  37318. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  37319. const glFormat = utils.convert( texture.format, texture.colorSpace );
  37320. const glType = utils.convert( texture.type );
  37321. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  37322. const renderTargetProperties = properties.get( renderTarget );
  37323. const textureProperties = properties.get( texture );
  37324. textureProperties.__renderTarget = renderTarget;
  37325. if ( ! renderTargetProperties.__hasExternalTextures ) {
  37326. const width = Math.max( 1, renderTarget.width >> level );
  37327. const height = Math.max( 1, renderTarget.height >> level );
  37328. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  37329. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  37330. } else {
  37331. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  37332. }
  37333. }
  37334. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  37335. if ( useMultisampledRTT( renderTarget ) ) {
  37336. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  37337. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  37338. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  37339. }
  37340. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  37341. }
  37342. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  37343. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  37344. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  37345. if ( renderTarget.depthBuffer ) {
  37346. // retrieve the depth attachment types
  37347. const depthTexture = renderTarget.depthTexture;
  37348. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  37349. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  37350. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  37351. // set up the attachment
  37352. const samples = getRenderTargetSamples( renderTarget );
  37353. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  37354. if ( isUseMultisampledRTT ) {
  37355. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  37356. } else if ( isMultisample ) {
  37357. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  37358. } else {
  37359. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  37360. }
  37361. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  37362. } else {
  37363. const textures = renderTarget.textures;
  37364. for ( let i = 0; i < textures.length; i ++ ) {
  37365. const texture = textures[ i ];
  37366. const glFormat = utils.convert( texture.format, texture.colorSpace );
  37367. const glType = utils.convert( texture.type );
  37368. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  37369. const samples = getRenderTargetSamples( renderTarget );
  37370. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  37371. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  37372. } else if ( useMultisampledRTT( renderTarget ) ) {
  37373. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  37374. } else {
  37375. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  37376. }
  37377. }
  37378. }
  37379. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  37380. }
  37381. // Setup resources for a Depth Texture for a FBO (needs an extension)
  37382. function setupDepthTexture( framebuffer, renderTarget ) {
  37383. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  37384. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  37385. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  37386. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  37387. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  37388. }
  37389. const textureProperties = properties.get( renderTarget.depthTexture );
  37390. textureProperties.__renderTarget = renderTarget;
  37391. // upload an empty depth texture with framebuffer size
  37392. if ( ! textureProperties.__webglTexture ||
  37393. renderTarget.depthTexture.image.width !== renderTarget.width ||
  37394. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  37395. renderTarget.depthTexture.image.width = renderTarget.width;
  37396. renderTarget.depthTexture.image.height = renderTarget.height;
  37397. renderTarget.depthTexture.needsUpdate = true;
  37398. }
  37399. setTexture2D( renderTarget.depthTexture, 0 );
  37400. const webglDepthTexture = textureProperties.__webglTexture;
  37401. const samples = getRenderTargetSamples( renderTarget );
  37402. if ( renderTarget.depthTexture.format === DepthFormat ) {
  37403. if ( useMultisampledRTT( renderTarget ) ) {
  37404. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  37405. } else {
  37406. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  37407. }
  37408. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  37409. if ( useMultisampledRTT( renderTarget ) ) {
  37410. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  37411. } else {
  37412. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  37413. }
  37414. } else {
  37415. throw new Error( 'Unknown depthTexture format' );
  37416. }
  37417. }
  37418. // Setup GL resources for a non-texture depth buffer
  37419. function setupDepthRenderbuffer( renderTarget ) {
  37420. const renderTargetProperties = properties.get( renderTarget );
  37421. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  37422. // if the bound depth texture has changed
  37423. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  37424. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  37425. const depthTexture = renderTarget.depthTexture;
  37426. if ( renderTargetProperties.__depthDisposeCallback ) {
  37427. renderTargetProperties.__depthDisposeCallback();
  37428. }
  37429. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  37430. if ( depthTexture ) {
  37431. const disposeEvent = () => {
  37432. delete renderTargetProperties.__boundDepthTexture;
  37433. delete renderTargetProperties.__depthDisposeCallback;
  37434. depthTexture.removeEventListener( 'dispose', disposeEvent );
  37435. };
  37436. depthTexture.addEventListener( 'dispose', disposeEvent );
  37437. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  37438. }
  37439. renderTargetProperties.__boundDepthTexture = depthTexture;
  37440. }
  37441. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  37442. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  37443. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  37444. } else {
  37445. if ( isCube ) {
  37446. renderTargetProperties.__webglDepthbuffer = [];
  37447. for ( let i = 0; i < 6; i ++ ) {
  37448. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  37449. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  37450. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  37451. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  37452. } else {
  37453. // attach buffer if it's been created already
  37454. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  37455. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  37456. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  37457. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  37458. }
  37459. }
  37460. } else {
  37461. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  37462. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  37463. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  37464. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  37465. } else {
  37466. // attach buffer if it's been created already
  37467. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  37468. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  37469. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  37470. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  37471. }
  37472. }
  37473. }
  37474. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  37475. }
  37476. // rebind framebuffer with external textures
  37477. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  37478. const renderTargetProperties = properties.get( renderTarget );
  37479. if ( colorTexture !== undefined ) {
  37480. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  37481. }
  37482. if ( depthTexture !== undefined ) {
  37483. setupDepthRenderbuffer( renderTarget );
  37484. }
  37485. }
  37486. // Set up GL resources for the render target
  37487. function setupRenderTarget( renderTarget ) {
  37488. const texture = renderTarget.texture;
  37489. const renderTargetProperties = properties.get( renderTarget );
  37490. const textureProperties = properties.get( texture );
  37491. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  37492. const textures = renderTarget.textures;
  37493. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  37494. const isMultipleRenderTargets = ( textures.length > 1 );
  37495. if ( ! isMultipleRenderTargets ) {
  37496. if ( textureProperties.__webglTexture === undefined ) {
  37497. textureProperties.__webglTexture = _gl.createTexture();
  37498. }
  37499. textureProperties.__version = texture.version;
  37500. info.memory.textures ++;
  37501. }
  37502. // Setup framebuffer
  37503. if ( isCube ) {
  37504. renderTargetProperties.__webglFramebuffer = [];
  37505. for ( let i = 0; i < 6; i ++ ) {
  37506. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  37507. renderTargetProperties.__webglFramebuffer[ i ] = [];
  37508. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  37509. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  37510. }
  37511. } else {
  37512. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  37513. }
  37514. }
  37515. } else {
  37516. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  37517. renderTargetProperties.__webglFramebuffer = [];
  37518. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  37519. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  37520. }
  37521. } else {
  37522. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  37523. }
  37524. if ( isMultipleRenderTargets ) {
  37525. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37526. const attachmentProperties = properties.get( textures[ i ] );
  37527. if ( attachmentProperties.__webglTexture === undefined ) {
  37528. attachmentProperties.__webglTexture = _gl.createTexture();
  37529. info.memory.textures ++;
  37530. }
  37531. }
  37532. }
  37533. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  37534. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  37535. renderTargetProperties.__webglColorRenderbuffer = [];
  37536. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  37537. for ( let i = 0; i < textures.length; i ++ ) {
  37538. const texture = textures[ i ];
  37539. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  37540. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  37541. const glFormat = utils.convert( texture.format, texture.colorSpace );
  37542. const glType = utils.convert( texture.type );
  37543. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  37544. const samples = getRenderTargetSamples( renderTarget );
  37545. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  37546. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  37547. }
  37548. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  37549. if ( renderTarget.depthBuffer ) {
  37550. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  37551. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  37552. }
  37553. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  37554. }
  37555. }
  37556. // Setup color buffer
  37557. if ( isCube ) {
  37558. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  37559. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  37560. for ( let i = 0; i < 6; i ++ ) {
  37561. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  37562. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  37563. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  37564. }
  37565. } else {
  37566. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  37567. }
  37568. }
  37569. if ( textureNeedsGenerateMipmaps( texture ) ) {
  37570. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  37571. }
  37572. state.unbindTexture();
  37573. } else if ( isMultipleRenderTargets ) {
  37574. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37575. const attachment = textures[ i ];
  37576. const attachmentProperties = properties.get( attachment );
  37577. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  37578. setTextureParameters( _gl.TEXTURE_2D, attachment );
  37579. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  37580. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  37581. generateMipmap( _gl.TEXTURE_2D );
  37582. }
  37583. }
  37584. state.unbindTexture();
  37585. } else {
  37586. let glTextureType = _gl.TEXTURE_2D;
  37587. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  37588. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  37589. }
  37590. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  37591. setTextureParameters( glTextureType, texture );
  37592. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  37593. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  37594. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  37595. }
  37596. } else {
  37597. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  37598. }
  37599. if ( textureNeedsGenerateMipmaps( texture ) ) {
  37600. generateMipmap( glTextureType );
  37601. }
  37602. state.unbindTexture();
  37603. }
  37604. // Setup depth and stencil buffers
  37605. if ( renderTarget.depthBuffer ) {
  37606. setupDepthRenderbuffer( renderTarget );
  37607. }
  37608. }
  37609. function updateRenderTargetMipmap( renderTarget ) {
  37610. const textures = renderTarget.textures;
  37611. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37612. const texture = textures[ i ];
  37613. if ( textureNeedsGenerateMipmaps( texture ) ) {
  37614. const targetType = getTargetType( renderTarget );
  37615. const webglTexture = properties.get( texture ).__webglTexture;
  37616. state.bindTexture( targetType, webglTexture );
  37617. generateMipmap( targetType );
  37618. state.unbindTexture();
  37619. }
  37620. }
  37621. }
  37622. const invalidationArrayRead = [];
  37623. const invalidationArrayDraw = [];
  37624. function updateMultisampleRenderTarget( renderTarget ) {
  37625. if ( renderTarget.samples > 0 ) {
  37626. if ( useMultisampledRTT( renderTarget ) === false ) {
  37627. const textures = renderTarget.textures;
  37628. const width = renderTarget.width;
  37629. const height = renderTarget.height;
  37630. let mask = _gl.COLOR_BUFFER_BIT;
  37631. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  37632. const renderTargetProperties = properties.get( renderTarget );
  37633. const isMultipleRenderTargets = ( textures.length > 1 );
  37634. // If MRT we need to remove FBO attachments
  37635. if ( isMultipleRenderTargets ) {
  37636. for ( let i = 0; i < textures.length; i ++ ) {
  37637. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  37638. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  37639. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  37640. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  37641. }
  37642. }
  37643. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  37644. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  37645. for ( let i = 0; i < textures.length; i ++ ) {
  37646. if ( renderTarget.resolveDepthBuffer ) {
  37647. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  37648. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  37649. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  37650. }
  37651. if ( isMultipleRenderTargets ) {
  37652. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  37653. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  37654. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  37655. }
  37656. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  37657. if ( supportsInvalidateFramebuffer === true ) {
  37658. invalidationArrayRead.length = 0;
  37659. invalidationArrayDraw.length = 0;
  37660. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  37661. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  37662. invalidationArrayRead.push( depthStyle );
  37663. invalidationArrayDraw.push( depthStyle );
  37664. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  37665. }
  37666. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  37667. }
  37668. }
  37669. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  37670. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  37671. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  37672. if ( isMultipleRenderTargets ) {
  37673. for ( let i = 0; i < textures.length; i ++ ) {
  37674. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  37675. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  37676. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  37677. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  37678. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  37679. }
  37680. }
  37681. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  37682. } else {
  37683. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  37684. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  37685. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  37686. }
  37687. }
  37688. }
  37689. }
  37690. function getRenderTargetSamples( renderTarget ) {
  37691. return Math.min( capabilities.maxSamples, renderTarget.samples );
  37692. }
  37693. function useMultisampledRTT( renderTarget ) {
  37694. const renderTargetProperties = properties.get( renderTarget );
  37695. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  37696. }
  37697. function updateVideoTexture( texture ) {
  37698. const frame = info.render.frame;
  37699. // Check the last frame we updated the VideoTexture
  37700. if ( _videoTextures.get( texture ) !== frame ) {
  37701. _videoTextures.set( texture, frame );
  37702. texture.update();
  37703. }
  37704. }
  37705. function verifyColorSpace( texture, image ) {
  37706. const colorSpace = texture.colorSpace;
  37707. const format = texture.format;
  37708. const type = texture.type;
  37709. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  37710. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  37711. // sRGB
  37712. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  37713. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  37714. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  37715. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  37716. }
  37717. } else {
  37718. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  37719. }
  37720. }
  37721. return image;
  37722. }
  37723. function getDimensions( image ) {
  37724. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  37725. // if intrinsic data are not available, fallback to width/height
  37726. _imageDimensions.width = image.naturalWidth || image.width;
  37727. _imageDimensions.height = image.naturalHeight || image.height;
  37728. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  37729. _imageDimensions.width = image.displayWidth;
  37730. _imageDimensions.height = image.displayHeight;
  37731. } else {
  37732. _imageDimensions.width = image.width;
  37733. _imageDimensions.height = image.height;
  37734. }
  37735. return _imageDimensions;
  37736. }
  37737. //
  37738. this.allocateTextureUnit = allocateTextureUnit;
  37739. this.resetTextureUnits = resetTextureUnits;
  37740. this.setTexture2D = setTexture2D;
  37741. this.setTexture2DArray = setTexture2DArray;
  37742. this.setTexture3D = setTexture3D;
  37743. this.setTextureCube = setTextureCube;
  37744. this.rebindTextures = rebindTextures;
  37745. this.setupRenderTarget = setupRenderTarget;
  37746. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  37747. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  37748. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  37749. this.setupFrameBufferTexture = setupFrameBufferTexture;
  37750. this.useMultisampledRTT = useMultisampledRTT;
  37751. }
  37752. function WebGLUtils( gl, extensions ) {
  37753. function convert( p, colorSpace = NoColorSpace ) {
  37754. let extension;
  37755. const transfer = ColorManagement.getTransfer( colorSpace );
  37756. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  37757. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  37758. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  37759. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  37760. if ( p === ByteType ) return gl.BYTE;
  37761. if ( p === ShortType ) return gl.SHORT;
  37762. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  37763. if ( p === IntType ) return gl.INT;
  37764. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  37765. if ( p === FloatType ) return gl.FLOAT;
  37766. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  37767. if ( p === AlphaFormat ) return gl.ALPHA;
  37768. if ( p === RGBFormat ) return gl.RGB;
  37769. if ( p === RGBAFormat ) return gl.RGBA;
  37770. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  37771. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  37772. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  37773. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  37774. // WebGL2 formats.
  37775. if ( p === RedFormat ) return gl.RED;
  37776. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  37777. if ( p === RGFormat ) return gl.RG;
  37778. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  37779. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  37780. // S3TC
  37781. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  37782. if ( transfer === SRGBTransfer ) {
  37783. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  37784. if ( extension !== null ) {
  37785. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  37786. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  37787. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  37788. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  37789. } else {
  37790. return null;
  37791. }
  37792. } else {
  37793. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  37794. if ( extension !== null ) {
  37795. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  37796. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  37797. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  37798. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  37799. } else {
  37800. return null;
  37801. }
  37802. }
  37803. }
  37804. // PVRTC
  37805. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  37806. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  37807. if ( extension !== null ) {
  37808. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  37809. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  37810. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  37811. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  37812. } else {
  37813. return null;
  37814. }
  37815. }
  37816. // ETC
  37817. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  37818. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  37819. if ( extension !== null ) {
  37820. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  37821. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  37822. } else {
  37823. return null;
  37824. }
  37825. }
  37826. // ASTC
  37827. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  37828. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  37829. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  37830. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  37831. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  37832. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  37833. if ( extension !== null ) {
  37834. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  37835. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  37836. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  37837. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  37838. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  37839. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  37840. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  37841. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  37842. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  37843. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  37844. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  37845. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  37846. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  37847. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  37848. } else {
  37849. return null;
  37850. }
  37851. }
  37852. // BPTC
  37853. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  37854. extension = extensions.get( 'EXT_texture_compression_bptc' );
  37855. if ( extension !== null ) {
  37856. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  37857. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  37858. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  37859. } else {
  37860. return null;
  37861. }
  37862. }
  37863. // RGTC
  37864. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  37865. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  37866. if ( extension !== null ) {
  37867. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  37868. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  37869. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  37870. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  37871. } else {
  37872. return null;
  37873. }
  37874. }
  37875. //
  37876. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  37877. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  37878. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  37879. }
  37880. return { convert: convert };
  37881. }
  37882. const _occlusion_vertex = `
  37883. void main() {
  37884. gl_Position = vec4( position, 1.0 );
  37885. }`;
  37886. const _occlusion_fragment = `
  37887. uniform sampler2DArray depthColor;
  37888. uniform float depthWidth;
  37889. uniform float depthHeight;
  37890. void main() {
  37891. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  37892. if ( coord.x >= 1.0 ) {
  37893. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  37894. } else {
  37895. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  37896. }
  37897. }`;
  37898. class WebXRDepthSensing {
  37899. constructor() {
  37900. this.texture = null;
  37901. this.mesh = null;
  37902. this.depthNear = 0;
  37903. this.depthFar = 0;
  37904. }
  37905. init( renderer, depthData, renderState ) {
  37906. if ( this.texture === null ) {
  37907. const texture = new Texture();
  37908. const texProps = renderer.properties.get( texture );
  37909. texProps.__webglTexture = depthData.texture;
  37910. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  37911. this.depthNear = depthData.depthNear;
  37912. this.depthFar = depthData.depthFar;
  37913. }
  37914. this.texture = texture;
  37915. }
  37916. }
  37917. getMesh( cameraXR ) {
  37918. if ( this.texture !== null ) {
  37919. if ( this.mesh === null ) {
  37920. const viewport = cameraXR.cameras[ 0 ].viewport;
  37921. const material = new ShaderMaterial( {
  37922. vertexShader: _occlusion_vertex,
  37923. fragmentShader: _occlusion_fragment,
  37924. uniforms: {
  37925. depthColor: { value: this.texture },
  37926. depthWidth: { value: viewport.z },
  37927. depthHeight: { value: viewport.w }
  37928. }
  37929. } );
  37930. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  37931. }
  37932. }
  37933. return this.mesh;
  37934. }
  37935. reset() {
  37936. this.texture = null;
  37937. this.mesh = null;
  37938. }
  37939. getDepthTexture() {
  37940. return this.texture;
  37941. }
  37942. }
  37943. class WebXRManager extends EventDispatcher {
  37944. constructor( renderer, gl ) {
  37945. super();
  37946. const scope = this;
  37947. let session = null;
  37948. let framebufferScaleFactor = 1.0;
  37949. let referenceSpace = null;
  37950. let referenceSpaceType = 'local-floor';
  37951. // Set default foveation to maximum.
  37952. let foveation = 1.0;
  37953. let customReferenceSpace = null;
  37954. let pose = null;
  37955. let glBinding = null;
  37956. let glProjLayer = null;
  37957. let glBaseLayer = null;
  37958. let xrFrame = null;
  37959. const depthSensing = new WebXRDepthSensing();
  37960. const attributes = gl.getContextAttributes();
  37961. let initialRenderTarget = null;
  37962. let newRenderTarget = null;
  37963. const controllers = [];
  37964. const controllerInputSources = [];
  37965. const currentSize = new Vector2();
  37966. let currentPixelRatio = null;
  37967. //
  37968. const cameraL = new PerspectiveCamera();
  37969. cameraL.viewport = new Vector4();
  37970. const cameraR = new PerspectiveCamera();
  37971. cameraR.viewport = new Vector4();
  37972. const cameras = [ cameraL, cameraR ];
  37973. const cameraXR = new ArrayCamera();
  37974. let _currentDepthNear = null;
  37975. let _currentDepthFar = null;
  37976. //
  37977. this.cameraAutoUpdate = true;
  37978. this.enabled = false;
  37979. this.isPresenting = false;
  37980. this.getController = function ( index ) {
  37981. let controller = controllers[ index ];
  37982. if ( controller === undefined ) {
  37983. controller = new WebXRController();
  37984. controllers[ index ] = controller;
  37985. }
  37986. return controller.getTargetRaySpace();
  37987. };
  37988. this.getControllerGrip = function ( index ) {
  37989. let controller = controllers[ index ];
  37990. if ( controller === undefined ) {
  37991. controller = new WebXRController();
  37992. controllers[ index ] = controller;
  37993. }
  37994. return controller.getGripSpace();
  37995. };
  37996. this.getHand = function ( index ) {
  37997. let controller = controllers[ index ];
  37998. if ( controller === undefined ) {
  37999. controller = new WebXRController();
  38000. controllers[ index ] = controller;
  38001. }
  38002. return controller.getHandSpace();
  38003. };
  38004. //
  38005. function onSessionEvent( event ) {
  38006. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  38007. if ( controllerIndex === -1 ) {
  38008. return;
  38009. }
  38010. const controller = controllers[ controllerIndex ];
  38011. if ( controller !== undefined ) {
  38012. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  38013. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38014. }
  38015. }
  38016. function onSessionEnd() {
  38017. session.removeEventListener( 'select', onSessionEvent );
  38018. session.removeEventListener( 'selectstart', onSessionEvent );
  38019. session.removeEventListener( 'selectend', onSessionEvent );
  38020. session.removeEventListener( 'squeeze', onSessionEvent );
  38021. session.removeEventListener( 'squeezestart', onSessionEvent );
  38022. session.removeEventListener( 'squeezeend', onSessionEvent );
  38023. session.removeEventListener( 'end', onSessionEnd );
  38024. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  38025. for ( let i = 0; i < controllers.length; i ++ ) {
  38026. const inputSource = controllerInputSources[ i ];
  38027. if ( inputSource === null ) continue;
  38028. controllerInputSources[ i ] = null;
  38029. controllers[ i ].disconnect( inputSource );
  38030. }
  38031. _currentDepthNear = null;
  38032. _currentDepthFar = null;
  38033. depthSensing.reset();
  38034. // restore framebuffer/rendering state
  38035. renderer.setRenderTarget( initialRenderTarget );
  38036. glBaseLayer = null;
  38037. glProjLayer = null;
  38038. glBinding = null;
  38039. session = null;
  38040. newRenderTarget = null;
  38041. //
  38042. animation.stop();
  38043. scope.isPresenting = false;
  38044. renderer.setPixelRatio( currentPixelRatio );
  38045. renderer.setSize( currentSize.width, currentSize.height, false );
  38046. scope.dispatchEvent( { type: 'sessionend' } );
  38047. }
  38048. this.setFramebufferScaleFactor = function ( value ) {
  38049. framebufferScaleFactor = value;
  38050. if ( scope.isPresenting === true ) {
  38051. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  38052. }
  38053. };
  38054. this.setReferenceSpaceType = function ( value ) {
  38055. referenceSpaceType = value;
  38056. if ( scope.isPresenting === true ) {
  38057. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  38058. }
  38059. };
  38060. this.getReferenceSpace = function () {
  38061. return customReferenceSpace || referenceSpace;
  38062. };
  38063. this.setReferenceSpace = function ( space ) {
  38064. customReferenceSpace = space;
  38065. };
  38066. this.getBaseLayer = function () {
  38067. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  38068. };
  38069. this.getBinding = function () {
  38070. return glBinding;
  38071. };
  38072. this.getFrame = function () {
  38073. return xrFrame;
  38074. };
  38075. this.getSession = function () {
  38076. return session;
  38077. };
  38078. this.setSession = async function ( value ) {
  38079. session = value;
  38080. if ( session !== null ) {
  38081. initialRenderTarget = renderer.getRenderTarget();
  38082. session.addEventListener( 'select', onSessionEvent );
  38083. session.addEventListener( 'selectstart', onSessionEvent );
  38084. session.addEventListener( 'selectend', onSessionEvent );
  38085. session.addEventListener( 'squeeze', onSessionEvent );
  38086. session.addEventListener( 'squeezestart', onSessionEvent );
  38087. session.addEventListener( 'squeezeend', onSessionEvent );
  38088. session.addEventListener( 'end', onSessionEnd );
  38089. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  38090. if ( attributes.xrCompatible !== true ) {
  38091. await gl.makeXRCompatible();
  38092. }
  38093. currentPixelRatio = renderer.getPixelRatio();
  38094. renderer.getSize( currentSize );
  38095. // Check that the browser implements the necessary APIs to use an
  38096. // XRProjectionLayer rather than an XRWebGLLayer
  38097. const useLayers = typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype;
  38098. if ( ! useLayers ) {
  38099. const layerInit = {
  38100. antialias: attributes.antialias,
  38101. alpha: true,
  38102. depth: attributes.depth,
  38103. stencil: attributes.stencil,
  38104. framebufferScaleFactor: framebufferScaleFactor
  38105. };
  38106. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38107. session.updateRenderState( { baseLayer: glBaseLayer } );
  38108. renderer.setPixelRatio( 1 );
  38109. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  38110. newRenderTarget = new WebGLRenderTarget(
  38111. glBaseLayer.framebufferWidth,
  38112. glBaseLayer.framebufferHeight,
  38113. {
  38114. format: RGBAFormat,
  38115. type: UnsignedByteType,
  38116. colorSpace: renderer.outputColorSpace,
  38117. stencilBuffer: attributes.stencil,
  38118. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38119. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  38120. }
  38121. );
  38122. } else {
  38123. let depthFormat = null;
  38124. let depthType = null;
  38125. let glDepthFormat = null;
  38126. if ( attributes.depth ) {
  38127. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38128. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  38129. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  38130. }
  38131. const projectionlayerInit = {
  38132. colorFormat: gl.RGBA8,
  38133. depthFormat: glDepthFormat,
  38134. scaleFactor: framebufferScaleFactor
  38135. };
  38136. glBinding = new XRWebGLBinding( session, gl );
  38137. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  38138. session.updateRenderState( { layers: [ glProjLayer ] } );
  38139. renderer.setPixelRatio( 1 );
  38140. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  38141. newRenderTarget = new WebGLRenderTarget(
  38142. glProjLayer.textureWidth,
  38143. glProjLayer.textureHeight,
  38144. {
  38145. format: RGBAFormat,
  38146. type: UnsignedByteType,
  38147. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  38148. stencilBuffer: attributes.stencil,
  38149. colorSpace: renderer.outputColorSpace,
  38150. samples: attributes.antialias ? 4 : 0,
  38151. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38152. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  38153. } );
  38154. }
  38155. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  38156. this.setFoveation( foveation );
  38157. customReferenceSpace = null;
  38158. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  38159. animation.setContext( session );
  38160. animation.start();
  38161. scope.isPresenting = true;
  38162. scope.dispatchEvent( { type: 'sessionstart' } );
  38163. }
  38164. };
  38165. this.getEnvironmentBlendMode = function () {
  38166. if ( session !== null ) {
  38167. return session.environmentBlendMode;
  38168. }
  38169. };
  38170. this.getDepthTexture = function () {
  38171. return depthSensing.getDepthTexture();
  38172. };
  38173. function onInputSourcesChange( event ) {
  38174. // Notify disconnected
  38175. for ( let i = 0; i < event.removed.length; i ++ ) {
  38176. const inputSource = event.removed[ i ];
  38177. const index = controllerInputSources.indexOf( inputSource );
  38178. if ( index >= 0 ) {
  38179. controllerInputSources[ index ] = null;
  38180. controllers[ index ].disconnect( inputSource );
  38181. }
  38182. }
  38183. // Notify connected
  38184. for ( let i = 0; i < event.added.length; i ++ ) {
  38185. const inputSource = event.added[ i ];
  38186. let controllerIndex = controllerInputSources.indexOf( inputSource );
  38187. if ( controllerIndex === -1 ) {
  38188. // Assign input source a controller that currently has no input source
  38189. for ( let i = 0; i < controllers.length; i ++ ) {
  38190. if ( i >= controllerInputSources.length ) {
  38191. controllerInputSources.push( inputSource );
  38192. controllerIndex = i;
  38193. break;
  38194. } else if ( controllerInputSources[ i ] === null ) {
  38195. controllerInputSources[ i ] = inputSource;
  38196. controllerIndex = i;
  38197. break;
  38198. }
  38199. }
  38200. // If all controllers do currently receive input we ignore new ones
  38201. if ( controllerIndex === -1 ) break;
  38202. }
  38203. const controller = controllers[ controllerIndex ];
  38204. if ( controller ) {
  38205. controller.connect( inputSource );
  38206. }
  38207. }
  38208. }
  38209. //
  38210. const cameraLPos = new Vector3();
  38211. const cameraRPos = new Vector3();
  38212. /**
  38213. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38214. * the cameras' projection and world matrices have already been set.
  38215. * And that near and far planes are identical for both cameras.
  38216. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38217. *
  38218. * @param {ArrayCamera} camera - The camera to update.
  38219. * @param {PerspectiveCamera} cameraL - The left camera.
  38220. * @param {PerspectiveCamera} cameraR - The right camera.
  38221. */
  38222. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38223. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38224. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38225. const ipd = cameraLPos.distanceTo( cameraRPos );
  38226. const projL = cameraL.projectionMatrix.elements;
  38227. const projR = cameraR.projectionMatrix.elements;
  38228. // VR systems will have identical far and near planes, and
  38229. // most likely identical top and bottom frustum extents.
  38230. // Use the left camera for these values.
  38231. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38232. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38233. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38234. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38235. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38236. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38237. const left = near * leftFov;
  38238. const right = near * rightFov;
  38239. // Calculate the new camera's position offset from the
  38240. // left camera. xOffset should be roughly half `ipd`.
  38241. const zOffset = ipd / ( - leftFov + rightFov );
  38242. const xOffset = zOffset * - leftFov;
  38243. // TODO: Better way to apply this offset?
  38244. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38245. camera.translateX( xOffset );
  38246. camera.translateZ( zOffset );
  38247. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38248. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38249. // Check if the projection uses an infinite far plane.
  38250. if ( projL[ 10 ] === -1 ) {
  38251. // Use the projection matrix from the left eye.
  38252. // The camera offset is sufficient to include the view volumes
  38253. // of both eyes (assuming symmetric projections).
  38254. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38255. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38256. } else {
  38257. // Find the union of the frustum values of the cameras and scale
  38258. // the values so that the near plane's position does not change in world space,
  38259. // although must now be relative to the new union camera.
  38260. const near2 = near + zOffset;
  38261. const far2 = far + zOffset;
  38262. const left2 = left - xOffset;
  38263. const right2 = right + ( ipd - xOffset );
  38264. const top2 = topFov * far / far2 * near2;
  38265. const bottom2 = bottomFov * far / far2 * near2;
  38266. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38267. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38268. }
  38269. }
  38270. function updateCamera( camera, parent ) {
  38271. if ( parent === null ) {
  38272. camera.matrixWorld.copy( camera.matrix );
  38273. } else {
  38274. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38275. }
  38276. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38277. }
  38278. this.updateCamera = function ( camera ) {
  38279. if ( session === null ) return;
  38280. let depthNear = camera.near;
  38281. let depthFar = camera.far;
  38282. if ( depthSensing.texture !== null ) {
  38283. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  38284. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  38285. }
  38286. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38287. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38288. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  38289. // Note that the new renderState won't apply until the next frame. See #18320
  38290. session.updateRenderState( {
  38291. depthNear: cameraXR.near,
  38292. depthFar: cameraXR.far
  38293. } );
  38294. _currentDepthNear = cameraXR.near;
  38295. _currentDepthFar = cameraXR.far;
  38296. }
  38297. cameraL.layers.mask = camera.layers.mask | 0b010;
  38298. cameraR.layers.mask = camera.layers.mask | 0b100;
  38299. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  38300. const parent = camera.parent;
  38301. const cameras = cameraXR.cameras;
  38302. updateCamera( cameraXR, parent );
  38303. for ( let i = 0; i < cameras.length; i ++ ) {
  38304. updateCamera( cameras[ i ], parent );
  38305. }
  38306. // update projection matrix for proper view frustum culling
  38307. if ( cameras.length === 2 ) {
  38308. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38309. } else {
  38310. // assume single camera setup (AR)
  38311. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38312. }
  38313. // update user camera and its children
  38314. updateUserCamera( camera, cameraXR, parent );
  38315. };
  38316. function updateUserCamera( camera, cameraXR, parent ) {
  38317. if ( parent === null ) {
  38318. camera.matrix.copy( cameraXR.matrixWorld );
  38319. } else {
  38320. camera.matrix.copy( parent.matrixWorld );
  38321. camera.matrix.invert();
  38322. camera.matrix.multiply( cameraXR.matrixWorld );
  38323. }
  38324. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38325. camera.updateMatrixWorld( true );
  38326. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38327. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38328. if ( camera.isPerspectiveCamera ) {
  38329. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38330. camera.zoom = 1;
  38331. }
  38332. }
  38333. this.getCamera = function () {
  38334. return cameraXR;
  38335. };
  38336. this.getFoveation = function () {
  38337. if ( glProjLayer === null && glBaseLayer === null ) {
  38338. return undefined;
  38339. }
  38340. return foveation;
  38341. };
  38342. this.setFoveation = function ( value ) {
  38343. // 0 = no foveation = full resolution
  38344. // 1 = maximum foveation = the edges render at lower resolution
  38345. foveation = value;
  38346. if ( glProjLayer !== null ) {
  38347. glProjLayer.fixedFoveation = value;
  38348. }
  38349. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  38350. glBaseLayer.fixedFoveation = value;
  38351. }
  38352. };
  38353. this.hasDepthSensing = function () {
  38354. return depthSensing.texture !== null;
  38355. };
  38356. this.getDepthSensingMesh = function () {
  38357. return depthSensing.getMesh( cameraXR );
  38358. };
  38359. // Animation Loop
  38360. let onAnimationFrameCallback = null;
  38361. function onAnimationFrame( time, frame ) {
  38362. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  38363. xrFrame = frame;
  38364. if ( pose !== null ) {
  38365. const views = pose.views;
  38366. if ( glBaseLayer !== null ) {
  38367. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  38368. renderer.setRenderTarget( newRenderTarget );
  38369. }
  38370. let cameraXRNeedsUpdate = false;
  38371. // check if it's necessary to rebuild cameraXR's camera list
  38372. if ( views.length !== cameraXR.cameras.length ) {
  38373. cameraXR.cameras.length = 0;
  38374. cameraXRNeedsUpdate = true;
  38375. }
  38376. for ( let i = 0; i < views.length; i ++ ) {
  38377. const view = views[ i ];
  38378. let viewport = null;
  38379. if ( glBaseLayer !== null ) {
  38380. viewport = glBaseLayer.getViewport( view );
  38381. } else {
  38382. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  38383. viewport = glSubImage.viewport;
  38384. // For side-by-side projection, we only produce a single texture for both eyes.
  38385. if ( i === 0 ) {
  38386. renderer.setRenderTargetTextures(
  38387. newRenderTarget,
  38388. glSubImage.colorTexture,
  38389. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  38390. renderer.setRenderTarget( newRenderTarget );
  38391. }
  38392. }
  38393. let camera = cameras[ i ];
  38394. if ( camera === undefined ) {
  38395. camera = new PerspectiveCamera();
  38396. camera.layers.enable( i );
  38397. camera.viewport = new Vector4();
  38398. cameras[ i ] = camera;
  38399. }
  38400. camera.matrix.fromArray( view.transform.matrix );
  38401. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38402. camera.projectionMatrix.fromArray( view.projectionMatrix );
  38403. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38404. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  38405. if ( i === 0 ) {
  38406. cameraXR.matrix.copy( camera.matrix );
  38407. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  38408. }
  38409. if ( cameraXRNeedsUpdate === true ) {
  38410. cameraXR.cameras.push( camera );
  38411. }
  38412. }
  38413. //
  38414. const enabledFeatures = session.enabledFeatures;
  38415. const gpuDepthSensingEnabled = enabledFeatures &&
  38416. enabledFeatures.includes( 'depth-sensing' ) &&
  38417. session.depthUsage == 'gpu-optimized';
  38418. if ( gpuDepthSensingEnabled && glBinding ) {
  38419. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  38420. if ( depthData && depthData.isValid && depthData.texture ) {
  38421. depthSensing.init( renderer, depthData, session.renderState );
  38422. }
  38423. }
  38424. }
  38425. //
  38426. for ( let i = 0; i < controllers.length; i ++ ) {
  38427. const inputSource = controllerInputSources[ i ];
  38428. const controller = controllers[ i ];
  38429. if ( inputSource !== null && controller !== undefined ) {
  38430. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  38431. }
  38432. }
  38433. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  38434. if ( frame.detectedPlanes ) {
  38435. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  38436. }
  38437. xrFrame = null;
  38438. }
  38439. const animation = new WebGLAnimation();
  38440. animation.setAnimationLoop( onAnimationFrame );
  38441. this.setAnimationLoop = function ( callback ) {
  38442. onAnimationFrameCallback = callback;
  38443. };
  38444. this.dispose = function () {};
  38445. }
  38446. }
  38447. const _e1 = /*@__PURE__*/ new Euler();
  38448. const _m1 = /*@__PURE__*/ new Matrix4();
  38449. function WebGLMaterials( renderer, properties ) {
  38450. function refreshTransformUniform( map, uniform ) {
  38451. if ( map.matrixAutoUpdate === true ) {
  38452. map.updateMatrix();
  38453. }
  38454. uniform.value.copy( map.matrix );
  38455. }
  38456. function refreshFogUniforms( uniforms, fog ) {
  38457. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  38458. if ( fog.isFog ) {
  38459. uniforms.fogNear.value = fog.near;
  38460. uniforms.fogFar.value = fog.far;
  38461. } else if ( fog.isFogExp2 ) {
  38462. uniforms.fogDensity.value = fog.density;
  38463. }
  38464. }
  38465. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  38466. if ( material.isMeshBasicMaterial ) {
  38467. refreshUniformsCommon( uniforms, material );
  38468. } else if ( material.isMeshLambertMaterial ) {
  38469. refreshUniformsCommon( uniforms, material );
  38470. } else if ( material.isMeshToonMaterial ) {
  38471. refreshUniformsCommon( uniforms, material );
  38472. refreshUniformsToon( uniforms, material );
  38473. } else if ( material.isMeshPhongMaterial ) {
  38474. refreshUniformsCommon( uniforms, material );
  38475. refreshUniformsPhong( uniforms, material );
  38476. } else if ( material.isMeshStandardMaterial ) {
  38477. refreshUniformsCommon( uniforms, material );
  38478. refreshUniformsStandard( uniforms, material );
  38479. if ( material.isMeshPhysicalMaterial ) {
  38480. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  38481. }
  38482. } else if ( material.isMeshMatcapMaterial ) {
  38483. refreshUniformsCommon( uniforms, material );
  38484. refreshUniformsMatcap( uniforms, material );
  38485. } else if ( material.isMeshDepthMaterial ) {
  38486. refreshUniformsCommon( uniforms, material );
  38487. } else if ( material.isMeshDistanceMaterial ) {
  38488. refreshUniformsCommon( uniforms, material );
  38489. refreshUniformsDistance( uniforms, material );
  38490. } else if ( material.isMeshNormalMaterial ) {
  38491. refreshUniformsCommon( uniforms, material );
  38492. } else if ( material.isLineBasicMaterial ) {
  38493. refreshUniformsLine( uniforms, material );
  38494. if ( material.isLineDashedMaterial ) {
  38495. refreshUniformsDash( uniforms, material );
  38496. }
  38497. } else if ( material.isPointsMaterial ) {
  38498. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  38499. } else if ( material.isSpriteMaterial ) {
  38500. refreshUniformsSprites( uniforms, material );
  38501. } else if ( material.isShadowMaterial ) {
  38502. uniforms.color.value.copy( material.color );
  38503. uniforms.opacity.value = material.opacity;
  38504. } else if ( material.isShaderMaterial ) {
  38505. material.uniformsNeedUpdate = false; // #15581
  38506. }
  38507. }
  38508. function refreshUniformsCommon( uniforms, material ) {
  38509. uniforms.opacity.value = material.opacity;
  38510. if ( material.color ) {
  38511. uniforms.diffuse.value.copy( material.color );
  38512. }
  38513. if ( material.emissive ) {
  38514. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  38515. }
  38516. if ( material.map ) {
  38517. uniforms.map.value = material.map;
  38518. refreshTransformUniform( material.map, uniforms.mapTransform );
  38519. }
  38520. if ( material.alphaMap ) {
  38521. uniforms.alphaMap.value = material.alphaMap;
  38522. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  38523. }
  38524. if ( material.bumpMap ) {
  38525. uniforms.bumpMap.value = material.bumpMap;
  38526. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  38527. uniforms.bumpScale.value = material.bumpScale;
  38528. if ( material.side === BackSide ) {
  38529. uniforms.bumpScale.value *= -1;
  38530. }
  38531. }
  38532. if ( material.normalMap ) {
  38533. uniforms.normalMap.value = material.normalMap;
  38534. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  38535. uniforms.normalScale.value.copy( material.normalScale );
  38536. if ( material.side === BackSide ) {
  38537. uniforms.normalScale.value.negate();
  38538. }
  38539. }
  38540. if ( material.displacementMap ) {
  38541. uniforms.displacementMap.value = material.displacementMap;
  38542. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  38543. uniforms.displacementScale.value = material.displacementScale;
  38544. uniforms.displacementBias.value = material.displacementBias;
  38545. }
  38546. if ( material.emissiveMap ) {
  38547. uniforms.emissiveMap.value = material.emissiveMap;
  38548. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  38549. }
  38550. if ( material.specularMap ) {
  38551. uniforms.specularMap.value = material.specularMap;
  38552. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  38553. }
  38554. if ( material.alphaTest > 0 ) {
  38555. uniforms.alphaTest.value = material.alphaTest;
  38556. }
  38557. const materialProperties = properties.get( material );
  38558. const envMap = materialProperties.envMap;
  38559. const envMapRotation = materialProperties.envMapRotation;
  38560. if ( envMap ) {
  38561. uniforms.envMap.value = envMap;
  38562. _e1.copy( envMapRotation );
  38563. // accommodate left-handed frame
  38564. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  38565. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  38566. // environment maps which are not cube render targets or PMREMs follow a different convention
  38567. _e1.y *= -1;
  38568. _e1.z *= -1;
  38569. }
  38570. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  38571. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  38572. uniforms.reflectivity.value = material.reflectivity;
  38573. uniforms.ior.value = material.ior;
  38574. uniforms.refractionRatio.value = material.refractionRatio;
  38575. }
  38576. if ( material.lightMap ) {
  38577. uniforms.lightMap.value = material.lightMap;
  38578. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  38579. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  38580. }
  38581. if ( material.aoMap ) {
  38582. uniforms.aoMap.value = material.aoMap;
  38583. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  38584. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  38585. }
  38586. }
  38587. function refreshUniformsLine( uniforms, material ) {
  38588. uniforms.diffuse.value.copy( material.color );
  38589. uniforms.opacity.value = material.opacity;
  38590. if ( material.map ) {
  38591. uniforms.map.value = material.map;
  38592. refreshTransformUniform( material.map, uniforms.mapTransform );
  38593. }
  38594. }
  38595. function refreshUniformsDash( uniforms, material ) {
  38596. uniforms.dashSize.value = material.dashSize;
  38597. uniforms.totalSize.value = material.dashSize + material.gapSize;
  38598. uniforms.scale.value = material.scale;
  38599. }
  38600. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  38601. uniforms.diffuse.value.copy( material.color );
  38602. uniforms.opacity.value = material.opacity;
  38603. uniforms.size.value = material.size * pixelRatio;
  38604. uniforms.scale.value = height * 0.5;
  38605. if ( material.map ) {
  38606. uniforms.map.value = material.map;
  38607. refreshTransformUniform( material.map, uniforms.uvTransform );
  38608. }
  38609. if ( material.alphaMap ) {
  38610. uniforms.alphaMap.value = material.alphaMap;
  38611. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  38612. }
  38613. if ( material.alphaTest > 0 ) {
  38614. uniforms.alphaTest.value = material.alphaTest;
  38615. }
  38616. }
  38617. function refreshUniformsSprites( uniforms, material ) {
  38618. uniforms.diffuse.value.copy( material.color );
  38619. uniforms.opacity.value = material.opacity;
  38620. uniforms.rotation.value = material.rotation;
  38621. if ( material.map ) {
  38622. uniforms.map.value = material.map;
  38623. refreshTransformUniform( material.map, uniforms.mapTransform );
  38624. }
  38625. if ( material.alphaMap ) {
  38626. uniforms.alphaMap.value = material.alphaMap;
  38627. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  38628. }
  38629. if ( material.alphaTest > 0 ) {
  38630. uniforms.alphaTest.value = material.alphaTest;
  38631. }
  38632. }
  38633. function refreshUniformsPhong( uniforms, material ) {
  38634. uniforms.specular.value.copy( material.specular );
  38635. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  38636. }
  38637. function refreshUniformsToon( uniforms, material ) {
  38638. if ( material.gradientMap ) {
  38639. uniforms.gradientMap.value = material.gradientMap;
  38640. }
  38641. }
  38642. function refreshUniformsStandard( uniforms, material ) {
  38643. uniforms.metalness.value = material.metalness;
  38644. if ( material.metalnessMap ) {
  38645. uniforms.metalnessMap.value = material.metalnessMap;
  38646. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  38647. }
  38648. uniforms.roughness.value = material.roughness;
  38649. if ( material.roughnessMap ) {
  38650. uniforms.roughnessMap.value = material.roughnessMap;
  38651. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  38652. }
  38653. if ( material.envMap ) {
  38654. //uniforms.envMap.value = material.envMap; // part of uniforms common
  38655. uniforms.envMapIntensity.value = material.envMapIntensity;
  38656. }
  38657. }
  38658. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  38659. uniforms.ior.value = material.ior; // also part of uniforms common
  38660. if ( material.sheen > 0 ) {
  38661. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  38662. uniforms.sheenRoughness.value = material.sheenRoughness;
  38663. if ( material.sheenColorMap ) {
  38664. uniforms.sheenColorMap.value = material.sheenColorMap;
  38665. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  38666. }
  38667. if ( material.sheenRoughnessMap ) {
  38668. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  38669. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  38670. }
  38671. }
  38672. if ( material.clearcoat > 0 ) {
  38673. uniforms.clearcoat.value = material.clearcoat;
  38674. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  38675. if ( material.clearcoatMap ) {
  38676. uniforms.clearcoatMap.value = material.clearcoatMap;
  38677. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  38678. }
  38679. if ( material.clearcoatRoughnessMap ) {
  38680. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  38681. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  38682. }
  38683. if ( material.clearcoatNormalMap ) {
  38684. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  38685. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  38686. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  38687. if ( material.side === BackSide ) {
  38688. uniforms.clearcoatNormalScale.value.negate();
  38689. }
  38690. }
  38691. }
  38692. if ( material.dispersion > 0 ) {
  38693. uniforms.dispersion.value = material.dispersion;
  38694. }
  38695. if ( material.iridescence > 0 ) {
  38696. uniforms.iridescence.value = material.iridescence;
  38697. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  38698. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  38699. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  38700. if ( material.iridescenceMap ) {
  38701. uniforms.iridescenceMap.value = material.iridescenceMap;
  38702. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  38703. }
  38704. if ( material.iridescenceThicknessMap ) {
  38705. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  38706. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  38707. }
  38708. }
  38709. if ( material.transmission > 0 ) {
  38710. uniforms.transmission.value = material.transmission;
  38711. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  38712. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  38713. if ( material.transmissionMap ) {
  38714. uniforms.transmissionMap.value = material.transmissionMap;
  38715. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  38716. }
  38717. uniforms.thickness.value = material.thickness;
  38718. if ( material.thicknessMap ) {
  38719. uniforms.thicknessMap.value = material.thicknessMap;
  38720. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  38721. }
  38722. uniforms.attenuationDistance.value = material.attenuationDistance;
  38723. uniforms.attenuationColor.value.copy( material.attenuationColor );
  38724. }
  38725. if ( material.anisotropy > 0 ) {
  38726. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  38727. if ( material.anisotropyMap ) {
  38728. uniforms.anisotropyMap.value = material.anisotropyMap;
  38729. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  38730. }
  38731. }
  38732. uniforms.specularIntensity.value = material.specularIntensity;
  38733. uniforms.specularColor.value.copy( material.specularColor );
  38734. if ( material.specularColorMap ) {
  38735. uniforms.specularColorMap.value = material.specularColorMap;
  38736. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  38737. }
  38738. if ( material.specularIntensityMap ) {
  38739. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  38740. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  38741. }
  38742. }
  38743. function refreshUniformsMatcap( uniforms, material ) {
  38744. if ( material.matcap ) {
  38745. uniforms.matcap.value = material.matcap;
  38746. }
  38747. }
  38748. function refreshUniformsDistance( uniforms, material ) {
  38749. const light = properties.get( material ).light;
  38750. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  38751. uniforms.nearDistance.value = light.shadow.camera.near;
  38752. uniforms.farDistance.value = light.shadow.camera.far;
  38753. }
  38754. return {
  38755. refreshFogUniforms: refreshFogUniforms,
  38756. refreshMaterialUniforms: refreshMaterialUniforms
  38757. };
  38758. }
  38759. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  38760. let buffers = {};
  38761. let updateList = {};
  38762. let allocatedBindingPoints = [];
  38763. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  38764. function bind( uniformsGroup, program ) {
  38765. const webglProgram = program.program;
  38766. state.uniformBlockBinding( uniformsGroup, webglProgram );
  38767. }
  38768. function update( uniformsGroup, program ) {
  38769. let buffer = buffers[ uniformsGroup.id ];
  38770. if ( buffer === undefined ) {
  38771. prepareUniformsGroup( uniformsGroup );
  38772. buffer = createBuffer( uniformsGroup );
  38773. buffers[ uniformsGroup.id ] = buffer;
  38774. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  38775. }
  38776. // ensure to update the binding points/block indices mapping for this program
  38777. const webglProgram = program.program;
  38778. state.updateUBOMapping( uniformsGroup, webglProgram );
  38779. // update UBO once per frame
  38780. const frame = info.render.frame;
  38781. if ( updateList[ uniformsGroup.id ] !== frame ) {
  38782. updateBufferData( uniformsGroup );
  38783. updateList[ uniformsGroup.id ] = frame;
  38784. }
  38785. }
  38786. function createBuffer( uniformsGroup ) {
  38787. // the setup of an UBO is independent of a particular shader program but global
  38788. const bindingPointIndex = allocateBindingPointIndex();
  38789. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  38790. const buffer = gl.createBuffer();
  38791. const size = uniformsGroup.__size;
  38792. const usage = uniformsGroup.usage;
  38793. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  38794. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  38795. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  38796. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  38797. return buffer;
  38798. }
  38799. function allocateBindingPointIndex() {
  38800. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  38801. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  38802. allocatedBindingPoints.push( i );
  38803. return i;
  38804. }
  38805. }
  38806. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  38807. return 0;
  38808. }
  38809. function updateBufferData( uniformsGroup ) {
  38810. const buffer = buffers[ uniformsGroup.id ];
  38811. const uniforms = uniformsGroup.uniforms;
  38812. const cache = uniformsGroup.__cache;
  38813. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  38814. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  38815. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  38816. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  38817. const uniform = uniformArray[ j ];
  38818. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  38819. const offset = uniform.__offset;
  38820. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  38821. let arrayOffset = 0;
  38822. for ( let k = 0; k < values.length; k ++ ) {
  38823. const value = values[ k ];
  38824. const info = getUniformSize( value );
  38825. // TODO add integer and struct support
  38826. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  38827. uniform.__data[ 0 ] = value;
  38828. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  38829. } else if ( value.isMatrix3 ) {
  38830. // manually converting 3x3 to 3x4
  38831. uniform.__data[ 0 ] = value.elements[ 0 ];
  38832. uniform.__data[ 1 ] = value.elements[ 1 ];
  38833. uniform.__data[ 2 ] = value.elements[ 2 ];
  38834. uniform.__data[ 3 ] = 0;
  38835. uniform.__data[ 4 ] = value.elements[ 3 ];
  38836. uniform.__data[ 5 ] = value.elements[ 4 ];
  38837. uniform.__data[ 6 ] = value.elements[ 5 ];
  38838. uniform.__data[ 7 ] = 0;
  38839. uniform.__data[ 8 ] = value.elements[ 6 ];
  38840. uniform.__data[ 9 ] = value.elements[ 7 ];
  38841. uniform.__data[ 10 ] = value.elements[ 8 ];
  38842. uniform.__data[ 11 ] = 0;
  38843. } else {
  38844. value.toArray( uniform.__data, arrayOffset );
  38845. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  38846. }
  38847. }
  38848. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  38849. }
  38850. }
  38851. }
  38852. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  38853. }
  38854. function hasUniformChanged( uniform, index, indexArray, cache ) {
  38855. const value = uniform.value;
  38856. const indexString = index + '_' + indexArray;
  38857. if ( cache[ indexString ] === undefined ) {
  38858. // cache entry does not exist so far
  38859. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  38860. cache[ indexString ] = value;
  38861. } else {
  38862. cache[ indexString ] = value.clone();
  38863. }
  38864. return true;
  38865. } else {
  38866. const cachedObject = cache[ indexString ];
  38867. // compare current value with cached entry
  38868. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  38869. if ( cachedObject !== value ) {
  38870. cache[ indexString ] = value;
  38871. return true;
  38872. }
  38873. } else {
  38874. if ( cachedObject.equals( value ) === false ) {
  38875. cachedObject.copy( value );
  38876. return true;
  38877. }
  38878. }
  38879. }
  38880. return false;
  38881. }
  38882. function prepareUniformsGroup( uniformsGroup ) {
  38883. // determine total buffer size according to the STD140 layout
  38884. // Hint: STD140 is the only supported layout in WebGL 2
  38885. const uniforms = uniformsGroup.uniforms;
  38886. let offset = 0; // global buffer offset in bytes
  38887. const chunkSize = 16; // size of a chunk in bytes
  38888. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  38889. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  38890. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  38891. const uniform = uniformArray[ j ];
  38892. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  38893. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  38894. const value = values[ k ];
  38895. const info = getUniformSize( value );
  38896. const chunkOffset = offset % chunkSize; // offset in the current chunk
  38897. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  38898. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  38899. offset += chunkPadding;
  38900. // Check for chunk overflow
  38901. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  38902. // Add padding and adjust offset
  38903. offset += ( chunkSize - chunkStart );
  38904. }
  38905. // the following two properties will be used for partial buffer updates
  38906. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  38907. uniform.__offset = offset;
  38908. // Update the global offset
  38909. offset += info.storage;
  38910. }
  38911. }
  38912. }
  38913. // ensure correct final padding
  38914. const chunkOffset = offset % chunkSize;
  38915. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  38916. //
  38917. uniformsGroup.__size = offset;
  38918. uniformsGroup.__cache = {};
  38919. return this;
  38920. }
  38921. function getUniformSize( value ) {
  38922. const info = {
  38923. boundary: 0, // bytes
  38924. storage: 0 // bytes
  38925. };
  38926. // determine sizes according to STD140
  38927. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  38928. // float/int/bool
  38929. info.boundary = 4;
  38930. info.storage = 4;
  38931. } else if ( value.isVector2 ) {
  38932. // vec2
  38933. info.boundary = 8;
  38934. info.storage = 8;
  38935. } else if ( value.isVector3 || value.isColor ) {
  38936. // vec3
  38937. info.boundary = 16;
  38938. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  38939. } else if ( value.isVector4 ) {
  38940. // vec4
  38941. info.boundary = 16;
  38942. info.storage = 16;
  38943. } else if ( value.isMatrix3 ) {
  38944. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  38945. info.boundary = 48;
  38946. info.storage = 48;
  38947. } else if ( value.isMatrix4 ) {
  38948. // mat4
  38949. info.boundary = 64;
  38950. info.storage = 64;
  38951. } else if ( value.isTexture ) {
  38952. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  38953. } else {
  38954. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  38955. }
  38956. return info;
  38957. }
  38958. function onUniformsGroupsDispose( event ) {
  38959. const uniformsGroup = event.target;
  38960. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  38961. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  38962. allocatedBindingPoints.splice( index, 1 );
  38963. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  38964. delete buffers[ uniformsGroup.id ];
  38965. delete updateList[ uniformsGroup.id ];
  38966. }
  38967. function dispose() {
  38968. for ( const id in buffers ) {
  38969. gl.deleteBuffer( buffers[ id ] );
  38970. }
  38971. allocatedBindingPoints = [];
  38972. buffers = {};
  38973. updateList = {};
  38974. }
  38975. return {
  38976. bind: bind,
  38977. update: update,
  38978. dispose: dispose
  38979. };
  38980. }
  38981. class WebGLRenderer {
  38982. constructor( parameters = {} ) {
  38983. const {
  38984. canvas = createCanvasElement(),
  38985. context = null,
  38986. depth = true,
  38987. stencil = false,
  38988. alpha = false,
  38989. antialias = false,
  38990. premultipliedAlpha = true,
  38991. preserveDrawingBuffer = false,
  38992. powerPreference = 'default',
  38993. failIfMajorPerformanceCaveat = false,
  38994. reverseDepthBuffer = false,
  38995. } = parameters;
  38996. this.isWebGLRenderer = true;
  38997. let _alpha;
  38998. if ( context !== null ) {
  38999. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  39000. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  39001. }
  39002. _alpha = context.getContextAttributes().alpha;
  39003. } else {
  39004. _alpha = alpha;
  39005. }
  39006. const uintClearColor = new Uint32Array( 4 );
  39007. const intClearColor = new Int32Array( 4 );
  39008. let currentRenderList = null;
  39009. let currentRenderState = null;
  39010. // render() can be called from within a callback triggered by another render.
  39011. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  39012. const renderListStack = [];
  39013. const renderStateStack = [];
  39014. // public properties
  39015. this.domElement = canvas;
  39016. // Debug configuration container
  39017. this.debug = {
  39018. /**
  39019. * Enables error checking and reporting when shader programs are being compiled
  39020. * @type {boolean}
  39021. */
  39022. checkShaderErrors: true,
  39023. /**
  39024. * Callback for custom error reporting.
  39025. * @type {?Function}
  39026. */
  39027. onShaderError: null
  39028. };
  39029. // clearing
  39030. this.autoClear = true;
  39031. this.autoClearColor = true;
  39032. this.autoClearDepth = true;
  39033. this.autoClearStencil = true;
  39034. // scene graph
  39035. this.sortObjects = true;
  39036. // user-defined clipping
  39037. this.clippingPlanes = [];
  39038. this.localClippingEnabled = false;
  39039. // physically based shading
  39040. this._outputColorSpace = SRGBColorSpace;
  39041. // tone mapping
  39042. this.toneMapping = NoToneMapping;
  39043. this.toneMappingExposure = 1.0;
  39044. // internal properties
  39045. const _this = this;
  39046. let _isContextLost = false;
  39047. // internal state cache
  39048. let _currentActiveCubeFace = 0;
  39049. let _currentActiveMipmapLevel = 0;
  39050. let _currentRenderTarget = null;
  39051. let _currentMaterialId = -1;
  39052. let _currentCamera = null;
  39053. const _currentViewport = new Vector4();
  39054. const _currentScissor = new Vector4();
  39055. let _currentScissorTest = null;
  39056. const _currentClearColor = new Color( 0x000000 );
  39057. let _currentClearAlpha = 0;
  39058. //
  39059. let _width = canvas.width;
  39060. let _height = canvas.height;
  39061. let _pixelRatio = 1;
  39062. let _opaqueSort = null;
  39063. let _transparentSort = null;
  39064. const _viewport = new Vector4( 0, 0, _width, _height );
  39065. const _scissor = new Vector4( 0, 0, _width, _height );
  39066. let _scissorTest = false;
  39067. // frustum
  39068. const _frustum = new Frustum();
  39069. // clipping
  39070. let _clippingEnabled = false;
  39071. let _localClippingEnabled = false;
  39072. // transmission render target scale
  39073. this.transmissionResolutionScale = 1.0;
  39074. // camera matrices cache
  39075. const _currentProjectionMatrix = new Matrix4();
  39076. const _projScreenMatrix = new Matrix4();
  39077. const _vector3 = new Vector3();
  39078. const _vector4 = new Vector4();
  39079. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  39080. let _renderBackground = false;
  39081. function getTargetPixelRatio() {
  39082. return _currentRenderTarget === null ? _pixelRatio : 1;
  39083. }
  39084. // initialize
  39085. let _gl = context;
  39086. function getContext( contextName, contextAttributes ) {
  39087. return canvas.getContext( contextName, contextAttributes );
  39088. }
  39089. try {
  39090. const contextAttributes = {
  39091. alpha: true,
  39092. depth,
  39093. stencil,
  39094. antialias,
  39095. premultipliedAlpha,
  39096. preserveDrawingBuffer,
  39097. powerPreference,
  39098. failIfMajorPerformanceCaveat,
  39099. };
  39100. // OffscreenCanvas does not have setAttribute, see #22811
  39101. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  39102. // event listeners must be registered before WebGL context is created, see #12753
  39103. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  39104. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  39105. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  39106. if ( _gl === null ) {
  39107. const contextName = 'webgl2';
  39108. _gl = getContext( contextName, contextAttributes );
  39109. if ( _gl === null ) {
  39110. if ( getContext( contextName ) ) {
  39111. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  39112. } else {
  39113. throw new Error( 'Error creating WebGL context.' );
  39114. }
  39115. }
  39116. }
  39117. } catch ( error ) {
  39118. console.error( 'THREE.WebGLRenderer: ' + error.message );
  39119. throw error;
  39120. }
  39121. let extensions, capabilities, state, info;
  39122. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  39123. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  39124. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  39125. let utils, bindingStates, uniformsGroups;
  39126. function initGLContext() {
  39127. extensions = new WebGLExtensions( _gl );
  39128. extensions.init();
  39129. utils = new WebGLUtils( _gl, extensions );
  39130. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  39131. state = new WebGLState( _gl, extensions );
  39132. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  39133. state.buffers.depth.setReversed( true );
  39134. }
  39135. info = new WebGLInfo( _gl );
  39136. properties = new WebGLProperties();
  39137. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  39138. cubemaps = new WebGLCubeMaps( _this );
  39139. cubeuvmaps = new WebGLCubeUVMaps( _this );
  39140. attributes = new WebGLAttributes( _gl );
  39141. bindingStates = new WebGLBindingStates( _gl, attributes );
  39142. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  39143. objects = new WebGLObjects( _gl, geometries, attributes, info );
  39144. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  39145. clipping = new WebGLClipping( properties );
  39146. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  39147. materials = new WebGLMaterials( _this, properties );
  39148. renderLists = new WebGLRenderLists();
  39149. renderStates = new WebGLRenderStates( extensions );
  39150. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  39151. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  39152. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  39153. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  39154. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  39155. info.programs = programCache.programs;
  39156. _this.capabilities = capabilities;
  39157. _this.extensions = extensions;
  39158. _this.properties = properties;
  39159. _this.renderLists = renderLists;
  39160. _this.shadowMap = shadowMap;
  39161. _this.state = state;
  39162. _this.info = info;
  39163. }
  39164. initGLContext();
  39165. // xr
  39166. const xr = new WebXRManager( _this, _gl );
  39167. this.xr = xr;
  39168. // API
  39169. this.getContext = function () {
  39170. return _gl;
  39171. };
  39172. this.getContextAttributes = function () {
  39173. return _gl.getContextAttributes();
  39174. };
  39175. this.forceContextLoss = function () {
  39176. const extension = extensions.get( 'WEBGL_lose_context' );
  39177. if ( extension ) extension.loseContext();
  39178. };
  39179. this.forceContextRestore = function () {
  39180. const extension = extensions.get( 'WEBGL_lose_context' );
  39181. if ( extension ) extension.restoreContext();
  39182. };
  39183. this.getPixelRatio = function () {
  39184. return _pixelRatio;
  39185. };
  39186. this.setPixelRatio = function ( value ) {
  39187. if ( value === undefined ) return;
  39188. _pixelRatio = value;
  39189. this.setSize( _width, _height, false );
  39190. };
  39191. this.getSize = function ( target ) {
  39192. return target.set( _width, _height );
  39193. };
  39194. this.setSize = function ( width, height, updateStyle = true ) {
  39195. if ( xr.isPresenting ) {
  39196. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  39197. return;
  39198. }
  39199. _width = width;
  39200. _height = height;
  39201. canvas.width = Math.floor( width * _pixelRatio );
  39202. canvas.height = Math.floor( height * _pixelRatio );
  39203. if ( updateStyle === true ) {
  39204. canvas.style.width = width + 'px';
  39205. canvas.style.height = height + 'px';
  39206. }
  39207. this.setViewport( 0, 0, width, height );
  39208. };
  39209. this.getDrawingBufferSize = function ( target ) {
  39210. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  39211. };
  39212. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  39213. _width = width;
  39214. _height = height;
  39215. _pixelRatio = pixelRatio;
  39216. canvas.width = Math.floor( width * pixelRatio );
  39217. canvas.height = Math.floor( height * pixelRatio );
  39218. this.setViewport( 0, 0, width, height );
  39219. };
  39220. this.getCurrentViewport = function ( target ) {
  39221. return target.copy( _currentViewport );
  39222. };
  39223. this.getViewport = function ( target ) {
  39224. return target.copy( _viewport );
  39225. };
  39226. this.setViewport = function ( x, y, width, height ) {
  39227. if ( x.isVector4 ) {
  39228. _viewport.set( x.x, x.y, x.z, x.w );
  39229. } else {
  39230. _viewport.set( x, y, width, height );
  39231. }
  39232. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  39233. };
  39234. this.getScissor = function ( target ) {
  39235. return target.copy( _scissor );
  39236. };
  39237. this.setScissor = function ( x, y, width, height ) {
  39238. if ( x.isVector4 ) {
  39239. _scissor.set( x.x, x.y, x.z, x.w );
  39240. } else {
  39241. _scissor.set( x, y, width, height );
  39242. }
  39243. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  39244. };
  39245. this.getScissorTest = function () {
  39246. return _scissorTest;
  39247. };
  39248. this.setScissorTest = function ( boolean ) {
  39249. state.setScissorTest( _scissorTest = boolean );
  39250. };
  39251. this.setOpaqueSort = function ( method ) {
  39252. _opaqueSort = method;
  39253. };
  39254. this.setTransparentSort = function ( method ) {
  39255. _transparentSort = method;
  39256. };
  39257. // Clearing
  39258. this.getClearColor = function ( target ) {
  39259. return target.copy( background.getClearColor() );
  39260. };
  39261. this.setClearColor = function () {
  39262. background.setClearColor( ...arguments );
  39263. };
  39264. this.getClearAlpha = function () {
  39265. return background.getClearAlpha();
  39266. };
  39267. this.setClearAlpha = function () {
  39268. background.setClearAlpha( ...arguments );
  39269. };
  39270. this.clear = function ( color = true, depth = true, stencil = true ) {
  39271. let bits = 0;
  39272. if ( color ) {
  39273. // check if we're trying to clear an integer target
  39274. let isIntegerFormat = false;
  39275. if ( _currentRenderTarget !== null ) {
  39276. const targetFormat = _currentRenderTarget.texture.format;
  39277. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  39278. targetFormat === RGIntegerFormat ||
  39279. targetFormat === RedIntegerFormat;
  39280. }
  39281. // use the appropriate clear functions to clear the target if it's a signed
  39282. // or unsigned integer target
  39283. if ( isIntegerFormat ) {
  39284. const targetType = _currentRenderTarget.texture.type;
  39285. const isUnsignedType = targetType === UnsignedByteType ||
  39286. targetType === UnsignedIntType ||
  39287. targetType === UnsignedShortType ||
  39288. targetType === UnsignedInt248Type ||
  39289. targetType === UnsignedShort4444Type ||
  39290. targetType === UnsignedShort5551Type;
  39291. const clearColor = background.getClearColor();
  39292. const a = background.getClearAlpha();
  39293. const r = clearColor.r;
  39294. const g = clearColor.g;
  39295. const b = clearColor.b;
  39296. if ( isUnsignedType ) {
  39297. uintClearColor[ 0 ] = r;
  39298. uintClearColor[ 1 ] = g;
  39299. uintClearColor[ 2 ] = b;
  39300. uintClearColor[ 3 ] = a;
  39301. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  39302. } else {
  39303. intClearColor[ 0 ] = r;
  39304. intClearColor[ 1 ] = g;
  39305. intClearColor[ 2 ] = b;
  39306. intClearColor[ 3 ] = a;
  39307. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  39308. }
  39309. } else {
  39310. bits |= _gl.COLOR_BUFFER_BIT;
  39311. }
  39312. }
  39313. if ( depth ) {
  39314. bits |= _gl.DEPTH_BUFFER_BIT;
  39315. }
  39316. if ( stencil ) {
  39317. bits |= _gl.STENCIL_BUFFER_BIT;
  39318. this.state.buffers.stencil.setMask( 0xffffffff );
  39319. }
  39320. _gl.clear( bits );
  39321. };
  39322. this.clearColor = function () {
  39323. this.clear( true, false, false );
  39324. };
  39325. this.clearDepth = function () {
  39326. this.clear( false, true, false );
  39327. };
  39328. this.clearStencil = function () {
  39329. this.clear( false, false, true );
  39330. };
  39331. //
  39332. this.dispose = function () {
  39333. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  39334. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  39335. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  39336. background.dispose();
  39337. renderLists.dispose();
  39338. renderStates.dispose();
  39339. properties.dispose();
  39340. cubemaps.dispose();
  39341. cubeuvmaps.dispose();
  39342. objects.dispose();
  39343. bindingStates.dispose();
  39344. uniformsGroups.dispose();
  39345. programCache.dispose();
  39346. xr.dispose();
  39347. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  39348. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  39349. animation.stop();
  39350. };
  39351. // Events
  39352. function onContextLost( event ) {
  39353. event.preventDefault();
  39354. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  39355. _isContextLost = true;
  39356. }
  39357. function onContextRestore( /* event */ ) {
  39358. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  39359. _isContextLost = false;
  39360. const infoAutoReset = info.autoReset;
  39361. const shadowMapEnabled = shadowMap.enabled;
  39362. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  39363. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  39364. const shadowMapType = shadowMap.type;
  39365. initGLContext();
  39366. info.autoReset = infoAutoReset;
  39367. shadowMap.enabled = shadowMapEnabled;
  39368. shadowMap.autoUpdate = shadowMapAutoUpdate;
  39369. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  39370. shadowMap.type = shadowMapType;
  39371. }
  39372. function onContextCreationError( event ) {
  39373. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  39374. }
  39375. function onMaterialDispose( event ) {
  39376. const material = event.target;
  39377. material.removeEventListener( 'dispose', onMaterialDispose );
  39378. deallocateMaterial( material );
  39379. }
  39380. // Buffer deallocation
  39381. function deallocateMaterial( material ) {
  39382. releaseMaterialProgramReferences( material );
  39383. properties.remove( material );
  39384. }
  39385. function releaseMaterialProgramReferences( material ) {
  39386. const programs = properties.get( material ).programs;
  39387. if ( programs !== undefined ) {
  39388. programs.forEach( function ( program ) {
  39389. programCache.releaseProgram( program );
  39390. } );
  39391. if ( material.isShaderMaterial ) {
  39392. programCache.releaseShaderCache( material );
  39393. }
  39394. }
  39395. }
  39396. // Buffer rendering
  39397. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  39398. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  39399. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39400. const program = setProgram( camera, scene, geometry, material, object );
  39401. state.setMaterial( material, frontFaceCW );
  39402. //
  39403. let index = geometry.index;
  39404. let rangeFactor = 1;
  39405. if ( material.wireframe === true ) {
  39406. index = geometries.getWireframeAttribute( geometry );
  39407. if ( index === undefined ) return;
  39408. rangeFactor = 2;
  39409. }
  39410. //
  39411. const drawRange = geometry.drawRange;
  39412. const position = geometry.attributes.position;
  39413. let drawStart = drawRange.start * rangeFactor;
  39414. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  39415. if ( group !== null ) {
  39416. drawStart = Math.max( drawStart, group.start * rangeFactor );
  39417. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  39418. }
  39419. if ( index !== null ) {
  39420. drawStart = Math.max( drawStart, 0 );
  39421. drawEnd = Math.min( drawEnd, index.count );
  39422. } else if ( position !== undefined && position !== null ) {
  39423. drawStart = Math.max( drawStart, 0 );
  39424. drawEnd = Math.min( drawEnd, position.count );
  39425. }
  39426. const drawCount = drawEnd - drawStart;
  39427. if ( drawCount < 0 || drawCount === Infinity ) return;
  39428. //
  39429. bindingStates.setup( object, material, program, geometry, index );
  39430. let attribute;
  39431. let renderer = bufferRenderer;
  39432. if ( index !== null ) {
  39433. attribute = attributes.get( index );
  39434. renderer = indexedBufferRenderer;
  39435. renderer.setIndex( attribute );
  39436. }
  39437. //
  39438. if ( object.isMesh ) {
  39439. if ( material.wireframe === true ) {
  39440. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  39441. renderer.setMode( _gl.LINES );
  39442. } else {
  39443. renderer.setMode( _gl.TRIANGLES );
  39444. }
  39445. } else if ( object.isLine ) {
  39446. let lineWidth = material.linewidth;
  39447. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  39448. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  39449. if ( object.isLineSegments ) {
  39450. renderer.setMode( _gl.LINES );
  39451. } else if ( object.isLineLoop ) {
  39452. renderer.setMode( _gl.LINE_LOOP );
  39453. } else {
  39454. renderer.setMode( _gl.LINE_STRIP );
  39455. }
  39456. } else if ( object.isPoints ) {
  39457. renderer.setMode( _gl.POINTS );
  39458. } else if ( object.isSprite ) {
  39459. renderer.setMode( _gl.TRIANGLES );
  39460. }
  39461. if ( object.isBatchedMesh ) {
  39462. if ( object._multiDrawInstances !== null ) {
  39463. // @deprecated, r174
  39464. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  39465. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39466. } else {
  39467. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  39468. const starts = object._multiDrawStarts;
  39469. const counts = object._multiDrawCounts;
  39470. const drawCount = object._multiDrawCount;
  39471. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  39472. const uniforms = properties.get( material ).currentProgram.getUniforms();
  39473. for ( let i = 0; i < drawCount; i ++ ) {
  39474. uniforms.setValue( _gl, '_gl_DrawID', i );
  39475. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  39476. }
  39477. } else {
  39478. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39479. }
  39480. }
  39481. } else if ( object.isInstancedMesh ) {
  39482. renderer.renderInstances( drawStart, drawCount, object.count );
  39483. } else if ( geometry.isInstancedBufferGeometry ) {
  39484. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  39485. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  39486. renderer.renderInstances( drawStart, drawCount, instanceCount );
  39487. } else {
  39488. renderer.render( drawStart, drawCount );
  39489. }
  39490. };
  39491. // Compile
  39492. function prepareMaterial( material, scene, object ) {
  39493. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39494. material.side = BackSide;
  39495. material.needsUpdate = true;
  39496. getProgram( material, scene, object );
  39497. material.side = FrontSide;
  39498. material.needsUpdate = true;
  39499. getProgram( material, scene, object );
  39500. material.side = DoubleSide;
  39501. } else {
  39502. getProgram( material, scene, object );
  39503. }
  39504. }
  39505. this.compile = function ( scene, camera, targetScene = null ) {
  39506. if ( targetScene === null ) targetScene = scene;
  39507. currentRenderState = renderStates.get( targetScene );
  39508. currentRenderState.init( camera );
  39509. renderStateStack.push( currentRenderState );
  39510. // gather lights from both the target scene and the new object that will be added to the scene.
  39511. targetScene.traverseVisible( function ( object ) {
  39512. if ( object.isLight && object.layers.test( camera.layers ) ) {
  39513. currentRenderState.pushLight( object );
  39514. if ( object.castShadow ) {
  39515. currentRenderState.pushShadow( object );
  39516. }
  39517. }
  39518. } );
  39519. if ( scene !== targetScene ) {
  39520. scene.traverseVisible( function ( object ) {
  39521. if ( object.isLight && object.layers.test( camera.layers ) ) {
  39522. currentRenderState.pushLight( object );
  39523. if ( object.castShadow ) {
  39524. currentRenderState.pushShadow( object );
  39525. }
  39526. }
  39527. } );
  39528. }
  39529. currentRenderState.setupLights();
  39530. // Only initialize materials in the new scene, not the targetScene.
  39531. const materials = new Set();
  39532. scene.traverse( function ( object ) {
  39533. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  39534. return;
  39535. }
  39536. const material = object.material;
  39537. if ( material ) {
  39538. if ( Array.isArray( material ) ) {
  39539. for ( let i = 0; i < material.length; i ++ ) {
  39540. const material2 = material[ i ];
  39541. prepareMaterial( material2, targetScene, object );
  39542. materials.add( material2 );
  39543. }
  39544. } else {
  39545. prepareMaterial( material, targetScene, object );
  39546. materials.add( material );
  39547. }
  39548. }
  39549. } );
  39550. renderStateStack.pop();
  39551. currentRenderState = null;
  39552. return materials;
  39553. };
  39554. // compileAsync
  39555. this.compileAsync = function ( scene, camera, targetScene = null ) {
  39556. const materials = this.compile( scene, camera, targetScene );
  39557. // Wait for all the materials in the new object to indicate that they're
  39558. // ready to be used before resolving the promise.
  39559. return new Promise( ( resolve ) => {
  39560. function checkMaterialsReady() {
  39561. materials.forEach( function ( material ) {
  39562. const materialProperties = properties.get( material );
  39563. const program = materialProperties.currentProgram;
  39564. if ( program.isReady() ) {
  39565. // remove any programs that report they're ready to use from the list
  39566. materials.delete( material );
  39567. }
  39568. } );
  39569. // once the list of compiling materials is empty, call the callback
  39570. if ( materials.size === 0 ) {
  39571. resolve( scene );
  39572. return;
  39573. }
  39574. // if some materials are still not ready, wait a bit and check again
  39575. setTimeout( checkMaterialsReady, 10 );
  39576. }
  39577. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  39578. // If we can check the compilation status of the materials without
  39579. // blocking then do so right away.
  39580. checkMaterialsReady();
  39581. } else {
  39582. // Otherwise start by waiting a bit to give the materials we just
  39583. // initialized a chance to finish.
  39584. setTimeout( checkMaterialsReady, 10 );
  39585. }
  39586. } );
  39587. };
  39588. // Animation Loop
  39589. let onAnimationFrameCallback = null;
  39590. function onAnimationFrame( time ) {
  39591. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  39592. }
  39593. function onXRSessionStart() {
  39594. animation.stop();
  39595. }
  39596. function onXRSessionEnd() {
  39597. animation.start();
  39598. }
  39599. const animation = new WebGLAnimation();
  39600. animation.setAnimationLoop( onAnimationFrame );
  39601. if ( typeof self !== 'undefined' ) animation.setContext( self );
  39602. this.setAnimationLoop = function ( callback ) {
  39603. onAnimationFrameCallback = callback;
  39604. xr.setAnimationLoop( callback );
  39605. ( callback === null ) ? animation.stop() : animation.start();
  39606. };
  39607. xr.addEventListener( 'sessionstart', onXRSessionStart );
  39608. xr.addEventListener( 'sessionend', onXRSessionEnd );
  39609. // Rendering
  39610. this.render = function ( scene, camera ) {
  39611. if ( camera !== undefined && camera.isCamera !== true ) {
  39612. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  39613. return;
  39614. }
  39615. if ( _isContextLost === true ) return;
  39616. // update scene graph
  39617. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  39618. // update camera matrices and frustum
  39619. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  39620. if ( xr.enabled === true && xr.isPresenting === true ) {
  39621. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  39622. camera = xr.getCamera(); // use XR camera for rendering
  39623. }
  39624. //
  39625. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  39626. currentRenderState = renderStates.get( scene, renderStateStack.length );
  39627. currentRenderState.init( camera );
  39628. renderStateStack.push( currentRenderState );
  39629. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  39630. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  39631. _localClippingEnabled = this.localClippingEnabled;
  39632. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  39633. currentRenderList = renderLists.get( scene, renderListStack.length );
  39634. currentRenderList.init();
  39635. renderListStack.push( currentRenderList );
  39636. if ( xr.enabled === true && xr.isPresenting === true ) {
  39637. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  39638. if ( depthSensingMesh !== null ) {
  39639. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  39640. }
  39641. }
  39642. projectObject( scene, camera, 0, _this.sortObjects );
  39643. currentRenderList.finish();
  39644. if ( _this.sortObjects === true ) {
  39645. currentRenderList.sort( _opaqueSort, _transparentSort );
  39646. }
  39647. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  39648. if ( _renderBackground ) {
  39649. background.addToRenderList( currentRenderList, scene );
  39650. }
  39651. //
  39652. this.info.render.frame ++;
  39653. if ( _clippingEnabled === true ) clipping.beginShadows();
  39654. const shadowsArray = currentRenderState.state.shadowsArray;
  39655. shadowMap.render( shadowsArray, scene, camera );
  39656. if ( _clippingEnabled === true ) clipping.endShadows();
  39657. //
  39658. if ( this.info.autoReset === true ) this.info.reset();
  39659. // render scene
  39660. const opaqueObjects = currentRenderList.opaque;
  39661. const transmissiveObjects = currentRenderList.transmissive;
  39662. currentRenderState.setupLights();
  39663. if ( camera.isArrayCamera ) {
  39664. const cameras = camera.cameras;
  39665. if ( transmissiveObjects.length > 0 ) {
  39666. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  39667. const camera2 = cameras[ i ];
  39668. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  39669. }
  39670. }
  39671. if ( _renderBackground ) background.render( scene );
  39672. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  39673. const camera2 = cameras[ i ];
  39674. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  39675. }
  39676. } else {
  39677. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  39678. if ( _renderBackground ) background.render( scene );
  39679. renderScene( currentRenderList, scene, camera );
  39680. }
  39681. //
  39682. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  39683. // resolve multisample renderbuffers to a single-sample texture if necessary
  39684. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  39685. // Generate mipmap if we're using any kind of mipmap filtering
  39686. textures.updateRenderTargetMipmap( _currentRenderTarget );
  39687. }
  39688. //
  39689. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  39690. // _gl.finish();
  39691. bindingStates.resetDefaultState();
  39692. _currentMaterialId = -1;
  39693. _currentCamera = null;
  39694. renderStateStack.pop();
  39695. if ( renderStateStack.length > 0 ) {
  39696. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  39697. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  39698. } else {
  39699. currentRenderState = null;
  39700. }
  39701. renderListStack.pop();
  39702. if ( renderListStack.length > 0 ) {
  39703. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  39704. } else {
  39705. currentRenderList = null;
  39706. }
  39707. };
  39708. function projectObject( object, camera, groupOrder, sortObjects ) {
  39709. if ( object.visible === false ) return;
  39710. const visible = object.layers.test( camera.layers );
  39711. if ( visible ) {
  39712. if ( object.isGroup ) {
  39713. groupOrder = object.renderOrder;
  39714. } else if ( object.isLOD ) {
  39715. if ( object.autoUpdate === true ) object.update( camera );
  39716. } else if ( object.isLight ) {
  39717. currentRenderState.pushLight( object );
  39718. if ( object.castShadow ) {
  39719. currentRenderState.pushShadow( object );
  39720. }
  39721. } else if ( object.isSprite ) {
  39722. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  39723. if ( sortObjects ) {
  39724. _vector4.setFromMatrixPosition( object.matrixWorld )
  39725. .applyMatrix4( _projScreenMatrix );
  39726. }
  39727. const geometry = objects.update( object );
  39728. const material = object.material;
  39729. if ( material.visible ) {
  39730. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  39731. }
  39732. }
  39733. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  39734. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  39735. const geometry = objects.update( object );
  39736. const material = object.material;
  39737. if ( sortObjects ) {
  39738. if ( object.boundingSphere !== undefined ) {
  39739. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  39740. _vector4.copy( object.boundingSphere.center );
  39741. } else {
  39742. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  39743. _vector4.copy( geometry.boundingSphere.center );
  39744. }
  39745. _vector4
  39746. .applyMatrix4( object.matrixWorld )
  39747. .applyMatrix4( _projScreenMatrix );
  39748. }
  39749. if ( Array.isArray( material ) ) {
  39750. const groups = geometry.groups;
  39751. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  39752. const group = groups[ i ];
  39753. const groupMaterial = material[ group.materialIndex ];
  39754. if ( groupMaterial && groupMaterial.visible ) {
  39755. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  39756. }
  39757. }
  39758. } else if ( material.visible ) {
  39759. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  39760. }
  39761. }
  39762. }
  39763. }
  39764. const children = object.children;
  39765. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39766. projectObject( children[ i ], camera, groupOrder, sortObjects );
  39767. }
  39768. }
  39769. function renderScene( currentRenderList, scene, camera, viewport ) {
  39770. const opaqueObjects = currentRenderList.opaque;
  39771. const transmissiveObjects = currentRenderList.transmissive;
  39772. const transparentObjects = currentRenderList.transparent;
  39773. currentRenderState.setupLightsView( camera );
  39774. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  39775. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  39776. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  39777. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  39778. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  39779. // Ensure depth buffer writing is enabled so it can be cleared on next render
  39780. state.buffers.depth.setTest( true );
  39781. state.buffers.depth.setMask( true );
  39782. state.buffers.color.setMask( true );
  39783. state.setPolygonOffset( false );
  39784. }
  39785. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  39786. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  39787. if ( overrideMaterial !== null ) {
  39788. return;
  39789. }
  39790. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  39791. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  39792. generateMipmaps: true,
  39793. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  39794. minFilter: LinearMipmapLinearFilter,
  39795. samples: 4,
  39796. stencilBuffer: stencil,
  39797. resolveDepthBuffer: false,
  39798. resolveStencilBuffer: false,
  39799. colorSpace: ColorManagement.workingColorSpace,
  39800. } );
  39801. // debug
  39802. /*
  39803. const geometry = new PlaneGeometry();
  39804. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  39805. const mesh = new Mesh( geometry, material );
  39806. scene.add( mesh );
  39807. */
  39808. }
  39809. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  39810. const activeViewport = camera.viewport || _currentViewport;
  39811. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  39812. //
  39813. const currentRenderTarget = _this.getRenderTarget();
  39814. _this.setRenderTarget( transmissionRenderTarget );
  39815. _this.getClearColor( _currentClearColor );
  39816. _currentClearAlpha = _this.getClearAlpha();
  39817. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  39818. _this.clear();
  39819. if ( _renderBackground ) background.render( scene );
  39820. // Turn off the features which can affect the frag color for opaque objects pass.
  39821. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  39822. const currentToneMapping = _this.toneMapping;
  39823. _this.toneMapping = NoToneMapping;
  39824. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  39825. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  39826. const currentCameraViewport = camera.viewport;
  39827. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  39828. currentRenderState.setupLightsView( camera );
  39829. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  39830. renderObjects( opaqueObjects, scene, camera );
  39831. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  39832. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  39833. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  39834. let renderTargetNeedsUpdate = false;
  39835. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  39836. const renderItem = transmissiveObjects[ i ];
  39837. const object = renderItem.object;
  39838. const geometry = renderItem.geometry;
  39839. const material = renderItem.material;
  39840. const group = renderItem.group;
  39841. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  39842. const currentSide = material.side;
  39843. material.side = BackSide;
  39844. material.needsUpdate = true;
  39845. renderObject( object, scene, camera, geometry, material, group );
  39846. material.side = currentSide;
  39847. material.needsUpdate = true;
  39848. renderTargetNeedsUpdate = true;
  39849. }
  39850. }
  39851. if ( renderTargetNeedsUpdate === true ) {
  39852. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  39853. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  39854. }
  39855. }
  39856. _this.setRenderTarget( currentRenderTarget );
  39857. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  39858. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  39859. _this.toneMapping = currentToneMapping;
  39860. }
  39861. function renderObjects( renderList, scene, camera ) {
  39862. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  39863. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  39864. const renderItem = renderList[ i ];
  39865. const object = renderItem.object;
  39866. const geometry = renderItem.geometry;
  39867. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  39868. const group = renderItem.group;
  39869. if ( object.layers.test( camera.layers ) ) {
  39870. renderObject( object, scene, camera, geometry, material, group );
  39871. }
  39872. }
  39873. }
  39874. function renderObject( object, scene, camera, geometry, material, group ) {
  39875. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  39876. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  39877. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  39878. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  39879. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39880. material.side = BackSide;
  39881. material.needsUpdate = true;
  39882. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  39883. material.side = FrontSide;
  39884. material.needsUpdate = true;
  39885. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  39886. material.side = DoubleSide;
  39887. } else {
  39888. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  39889. }
  39890. object.onAfterRender( _this, scene, camera, geometry, material, group );
  39891. }
  39892. function getProgram( material, scene, object ) {
  39893. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  39894. const materialProperties = properties.get( material );
  39895. const lights = currentRenderState.state.lights;
  39896. const shadowsArray = currentRenderState.state.shadowsArray;
  39897. const lightsStateVersion = lights.state.version;
  39898. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  39899. const programCacheKey = programCache.getProgramCacheKey( parameters );
  39900. let programs = materialProperties.programs;
  39901. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  39902. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  39903. materialProperties.fog = scene.fog;
  39904. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  39905. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  39906. if ( programs === undefined ) {
  39907. // new material
  39908. material.addEventListener( 'dispose', onMaterialDispose );
  39909. programs = new Map();
  39910. materialProperties.programs = programs;
  39911. }
  39912. let program = programs.get( programCacheKey );
  39913. if ( program !== undefined ) {
  39914. // early out if program and light state is identical
  39915. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  39916. updateCommonMaterialProperties( material, parameters );
  39917. return program;
  39918. }
  39919. } else {
  39920. parameters.uniforms = programCache.getUniforms( material );
  39921. material.onBeforeCompile( parameters, _this );
  39922. program = programCache.acquireProgram( parameters, programCacheKey );
  39923. programs.set( programCacheKey, program );
  39924. materialProperties.uniforms = parameters.uniforms;
  39925. }
  39926. const uniforms = materialProperties.uniforms;
  39927. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  39928. uniforms.clippingPlanes = clipping.uniform;
  39929. }
  39930. updateCommonMaterialProperties( material, parameters );
  39931. // store the light setup it was created for
  39932. materialProperties.needsLights = materialNeedsLights( material );
  39933. materialProperties.lightsStateVersion = lightsStateVersion;
  39934. if ( materialProperties.needsLights ) {
  39935. // wire up the material to this renderer's lighting state
  39936. uniforms.ambientLightColor.value = lights.state.ambient;
  39937. uniforms.lightProbe.value = lights.state.probe;
  39938. uniforms.directionalLights.value = lights.state.directional;
  39939. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  39940. uniforms.spotLights.value = lights.state.spot;
  39941. uniforms.spotLightShadows.value = lights.state.spotShadow;
  39942. uniforms.rectAreaLights.value = lights.state.rectArea;
  39943. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  39944. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  39945. uniforms.pointLights.value = lights.state.point;
  39946. uniforms.pointLightShadows.value = lights.state.pointShadow;
  39947. uniforms.hemisphereLights.value = lights.state.hemi;
  39948. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  39949. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  39950. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  39951. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  39952. uniforms.spotLightMap.value = lights.state.spotLightMap;
  39953. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  39954. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  39955. // TODO (abelnation): add area lights shadow info to uniforms
  39956. }
  39957. materialProperties.currentProgram = program;
  39958. materialProperties.uniformsList = null;
  39959. return program;
  39960. }
  39961. function getUniformList( materialProperties ) {
  39962. if ( materialProperties.uniformsList === null ) {
  39963. const progUniforms = materialProperties.currentProgram.getUniforms();
  39964. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  39965. }
  39966. return materialProperties.uniformsList;
  39967. }
  39968. function updateCommonMaterialProperties( material, parameters ) {
  39969. const materialProperties = properties.get( material );
  39970. materialProperties.outputColorSpace = parameters.outputColorSpace;
  39971. materialProperties.batching = parameters.batching;
  39972. materialProperties.batchingColor = parameters.batchingColor;
  39973. materialProperties.instancing = parameters.instancing;
  39974. materialProperties.instancingColor = parameters.instancingColor;
  39975. materialProperties.instancingMorph = parameters.instancingMorph;
  39976. materialProperties.skinning = parameters.skinning;
  39977. materialProperties.morphTargets = parameters.morphTargets;
  39978. materialProperties.morphNormals = parameters.morphNormals;
  39979. materialProperties.morphColors = parameters.morphColors;
  39980. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  39981. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  39982. materialProperties.numIntersection = parameters.numClipIntersection;
  39983. materialProperties.vertexAlphas = parameters.vertexAlphas;
  39984. materialProperties.vertexTangents = parameters.vertexTangents;
  39985. materialProperties.toneMapping = parameters.toneMapping;
  39986. }
  39987. function setProgram( camera, scene, geometry, material, object ) {
  39988. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  39989. textures.resetTextureUnits();
  39990. const fog = scene.fog;
  39991. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  39992. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  39993. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  39994. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  39995. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  39996. const morphTargets = !! geometry.morphAttributes.position;
  39997. const morphNormals = !! geometry.morphAttributes.normal;
  39998. const morphColors = !! geometry.morphAttributes.color;
  39999. let toneMapping = NoToneMapping;
  40000. if ( material.toneMapped ) {
  40001. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  40002. toneMapping = _this.toneMapping;
  40003. }
  40004. }
  40005. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  40006. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  40007. const materialProperties = properties.get( material );
  40008. const lights = currentRenderState.state.lights;
  40009. if ( _clippingEnabled === true ) {
  40010. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  40011. const useCache =
  40012. camera === _currentCamera &&
  40013. material.id === _currentMaterialId;
  40014. // we might want to call this function with some ClippingGroup
  40015. // object instead of the material, once it becomes feasible
  40016. // (#8465, #8379)
  40017. clipping.setState( material, camera, useCache );
  40018. }
  40019. }
  40020. //
  40021. let needsProgramChange = false;
  40022. if ( material.version === materialProperties.__version ) {
  40023. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  40024. needsProgramChange = true;
  40025. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  40026. needsProgramChange = true;
  40027. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  40028. needsProgramChange = true;
  40029. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  40030. needsProgramChange = true;
  40031. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  40032. needsProgramChange = true;
  40033. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  40034. needsProgramChange = true;
  40035. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  40036. needsProgramChange = true;
  40037. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  40038. needsProgramChange = true;
  40039. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  40040. needsProgramChange = true;
  40041. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  40042. needsProgramChange = true;
  40043. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  40044. needsProgramChange = true;
  40045. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  40046. needsProgramChange = true;
  40047. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  40048. needsProgramChange = true;
  40049. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  40050. needsProgramChange = true;
  40051. } else if ( materialProperties.envMap !== envMap ) {
  40052. needsProgramChange = true;
  40053. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  40054. needsProgramChange = true;
  40055. } else if ( materialProperties.numClippingPlanes !== undefined &&
  40056. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  40057. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  40058. needsProgramChange = true;
  40059. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  40060. needsProgramChange = true;
  40061. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  40062. needsProgramChange = true;
  40063. } else if ( materialProperties.morphTargets !== morphTargets ) {
  40064. needsProgramChange = true;
  40065. } else if ( materialProperties.morphNormals !== morphNormals ) {
  40066. needsProgramChange = true;
  40067. } else if ( materialProperties.morphColors !== morphColors ) {
  40068. needsProgramChange = true;
  40069. } else if ( materialProperties.toneMapping !== toneMapping ) {
  40070. needsProgramChange = true;
  40071. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  40072. needsProgramChange = true;
  40073. }
  40074. } else {
  40075. needsProgramChange = true;
  40076. materialProperties.__version = material.version;
  40077. }
  40078. //
  40079. let program = materialProperties.currentProgram;
  40080. if ( needsProgramChange === true ) {
  40081. program = getProgram( material, scene, object );
  40082. }
  40083. let refreshProgram = false;
  40084. let refreshMaterial = false;
  40085. let refreshLights = false;
  40086. const p_uniforms = program.getUniforms(),
  40087. m_uniforms = materialProperties.uniforms;
  40088. if ( state.useProgram( program.program ) ) {
  40089. refreshProgram = true;
  40090. refreshMaterial = true;
  40091. refreshLights = true;
  40092. }
  40093. if ( material.id !== _currentMaterialId ) {
  40094. _currentMaterialId = material.id;
  40095. refreshMaterial = true;
  40096. }
  40097. if ( refreshProgram || _currentCamera !== camera ) {
  40098. // common camera uniforms
  40099. const reverseDepthBuffer = state.buffers.depth.getReversed();
  40100. if ( reverseDepthBuffer ) {
  40101. _currentProjectionMatrix.copy( camera.projectionMatrix );
  40102. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  40103. toReversedProjectionMatrix( _currentProjectionMatrix );
  40104. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  40105. } else {
  40106. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  40107. }
  40108. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  40109. const uCamPos = p_uniforms.map.cameraPosition;
  40110. if ( uCamPos !== undefined ) {
  40111. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  40112. }
  40113. if ( capabilities.logarithmicDepthBuffer ) {
  40114. p_uniforms.setValue( _gl, 'logDepthBufFC',
  40115. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  40116. }
  40117. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  40118. if ( material.isMeshPhongMaterial ||
  40119. material.isMeshToonMaterial ||
  40120. material.isMeshLambertMaterial ||
  40121. material.isMeshBasicMaterial ||
  40122. material.isMeshStandardMaterial ||
  40123. material.isShaderMaterial ) {
  40124. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  40125. }
  40126. if ( _currentCamera !== camera ) {
  40127. _currentCamera = camera;
  40128. // lighting uniforms depend on the camera so enforce an update
  40129. // now, in case this material supports lights - or later, when
  40130. // the next material that does gets activated:
  40131. refreshMaterial = true; // set to true on material change
  40132. refreshLights = true; // remains set until update done
  40133. }
  40134. }
  40135. // skinning and morph target uniforms must be set even if material didn't change
  40136. // auto-setting of texture unit for bone and morph texture must go before other textures
  40137. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  40138. if ( object.isSkinnedMesh ) {
  40139. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  40140. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  40141. const skeleton = object.skeleton;
  40142. if ( skeleton ) {
  40143. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  40144. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  40145. }
  40146. }
  40147. if ( object.isBatchedMesh ) {
  40148. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  40149. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  40150. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  40151. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  40152. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  40153. if ( object._colorsTexture !== null ) {
  40154. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  40155. }
  40156. }
  40157. const morphAttributes = geometry.morphAttributes;
  40158. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  40159. morphtargets.update( object, geometry, program );
  40160. }
  40161. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  40162. materialProperties.receiveShadow = object.receiveShadow;
  40163. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  40164. }
  40165. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  40166. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  40167. m_uniforms.envMap.value = envMap;
  40168. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  40169. }
  40170. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  40171. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  40172. }
  40173. if ( refreshMaterial ) {
  40174. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  40175. if ( materialProperties.needsLights ) {
  40176. // the current material requires lighting info
  40177. // note: all lighting uniforms are always set correctly
  40178. // they simply reference the renderer's state for their
  40179. // values
  40180. //
  40181. // use the current material's .needsUpdate flags to set
  40182. // the GL state when required
  40183. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  40184. }
  40185. // refresh uniforms common to several materials
  40186. if ( fog && material.fog === true ) {
  40187. materials.refreshFogUniforms( m_uniforms, fog );
  40188. }
  40189. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  40190. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  40191. }
  40192. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  40193. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  40194. material.uniformsNeedUpdate = false;
  40195. }
  40196. if ( material.isSpriteMaterial ) {
  40197. p_uniforms.setValue( _gl, 'center', object.center );
  40198. }
  40199. // common matrices
  40200. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  40201. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  40202. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  40203. // UBOs
  40204. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  40205. const groups = material.uniformsGroups;
  40206. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  40207. const group = groups[ i ];
  40208. uniformsGroups.update( group, program );
  40209. uniformsGroups.bind( group, program );
  40210. }
  40211. }
  40212. return program;
  40213. }
  40214. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  40215. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  40216. uniforms.ambientLightColor.needsUpdate = value;
  40217. uniforms.lightProbe.needsUpdate = value;
  40218. uniforms.directionalLights.needsUpdate = value;
  40219. uniforms.directionalLightShadows.needsUpdate = value;
  40220. uniforms.pointLights.needsUpdate = value;
  40221. uniforms.pointLightShadows.needsUpdate = value;
  40222. uniforms.spotLights.needsUpdate = value;
  40223. uniforms.spotLightShadows.needsUpdate = value;
  40224. uniforms.rectAreaLights.needsUpdate = value;
  40225. uniforms.hemisphereLights.needsUpdate = value;
  40226. }
  40227. function materialNeedsLights( material ) {
  40228. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  40229. material.isMeshStandardMaterial || material.isShadowMaterial ||
  40230. ( material.isShaderMaterial && material.lights === true );
  40231. }
  40232. this.getActiveCubeFace = function () {
  40233. return _currentActiveCubeFace;
  40234. };
  40235. this.getActiveMipmapLevel = function () {
  40236. return _currentActiveMipmapLevel;
  40237. };
  40238. this.getRenderTarget = function () {
  40239. return _currentRenderTarget;
  40240. };
  40241. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  40242. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  40243. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  40244. const renderTargetProperties = properties.get( renderTarget );
  40245. renderTargetProperties.__hasExternalTextures = true;
  40246. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  40247. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  40248. // The multisample_render_to_texture extension doesn't work properly if there
  40249. // are midframe flushes and an external depth buffer. Disable use of the extension.
  40250. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  40251. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  40252. renderTargetProperties.__useRenderToTexture = false;
  40253. }
  40254. }
  40255. };
  40256. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  40257. const renderTargetProperties = properties.get( renderTarget );
  40258. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  40259. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  40260. };
  40261. const _scratchFrameBuffer = _gl.createFramebuffer();
  40262. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  40263. _currentRenderTarget = renderTarget;
  40264. _currentActiveCubeFace = activeCubeFace;
  40265. _currentActiveMipmapLevel = activeMipmapLevel;
  40266. let useDefaultFramebuffer = true;
  40267. let framebuffer = null;
  40268. let isCube = false;
  40269. let isRenderTarget3D = false;
  40270. if ( renderTarget ) {
  40271. const renderTargetProperties = properties.get( renderTarget );
  40272. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  40273. // We need to make sure to rebind the framebuffer.
  40274. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  40275. useDefaultFramebuffer = false;
  40276. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  40277. textures.setupRenderTarget( renderTarget );
  40278. } else if ( renderTargetProperties.__hasExternalTextures ) {
  40279. // Color and depth texture must be rebound in order for the swapchain to update.
  40280. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  40281. } else if ( renderTarget.depthBuffer ) {
  40282. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  40283. const depthTexture = renderTarget.depthTexture;
  40284. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  40285. // check if the depth texture is compatible
  40286. if (
  40287. depthTexture !== null &&
  40288. properties.has( depthTexture ) &&
  40289. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  40290. ) {
  40291. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  40292. }
  40293. // Swap the depth buffer to the currently attached one
  40294. textures.setupDepthRenderbuffer( renderTarget );
  40295. }
  40296. }
  40297. const texture = renderTarget.texture;
  40298. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40299. isRenderTarget3D = true;
  40300. }
  40301. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  40302. if ( renderTarget.isWebGLCubeRenderTarget ) {
  40303. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  40304. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  40305. } else {
  40306. framebuffer = __webglFramebuffer[ activeCubeFace ];
  40307. }
  40308. isCube = true;
  40309. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  40310. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  40311. } else {
  40312. if ( Array.isArray( __webglFramebuffer ) ) {
  40313. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  40314. } else {
  40315. framebuffer = __webglFramebuffer;
  40316. }
  40317. }
  40318. _currentViewport.copy( renderTarget.viewport );
  40319. _currentScissor.copy( renderTarget.scissor );
  40320. _currentScissorTest = renderTarget.scissorTest;
  40321. } else {
  40322. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  40323. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  40324. _currentScissorTest = _scissorTest;
  40325. }
  40326. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  40327. // being bound that are different sizes.
  40328. if ( activeMipmapLevel !== 0 ) {
  40329. framebuffer = _scratchFrameBuffer;
  40330. }
  40331. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  40332. if ( framebufferBound && useDefaultFramebuffer ) {
  40333. state.drawBuffers( renderTarget, framebuffer );
  40334. }
  40335. state.viewport( _currentViewport );
  40336. state.scissor( _currentScissor );
  40337. state.setScissorTest( _currentScissorTest );
  40338. if ( isCube ) {
  40339. const textureProperties = properties.get( renderTarget.texture );
  40340. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  40341. } else if ( isRenderTarget3D ) {
  40342. const textureProperties = properties.get( renderTarget.texture );
  40343. const layer = activeCubeFace;
  40344. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer );
  40345. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  40346. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  40347. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  40348. const textureProperties = properties.get( renderTarget.texture );
  40349. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  40350. }
  40351. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  40352. };
  40353. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  40354. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  40355. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  40356. return;
  40357. }
  40358. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  40359. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  40360. framebuffer = framebuffer[ activeCubeFaceIndex ];
  40361. }
  40362. if ( framebuffer ) {
  40363. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  40364. try {
  40365. const texture = renderTarget.texture;
  40366. const textureFormat = texture.format;
  40367. const textureType = texture.type;
  40368. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  40369. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  40370. return;
  40371. }
  40372. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  40373. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  40374. return;
  40375. }
  40376. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  40377. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  40378. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  40379. }
  40380. } finally {
  40381. // restore framebuffer of current render target if necessary
  40382. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  40383. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  40384. }
  40385. }
  40386. };
  40387. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  40388. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  40389. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  40390. }
  40391. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  40392. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  40393. framebuffer = framebuffer[ activeCubeFaceIndex ];
  40394. }
  40395. if ( framebuffer ) {
  40396. const texture = renderTarget.texture;
  40397. const textureFormat = texture.format;
  40398. const textureType = texture.type;
  40399. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  40400. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  40401. }
  40402. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  40403. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  40404. }
  40405. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  40406. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  40407. // set the active frame buffer to the one we want to read
  40408. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  40409. const glBuffer = _gl.createBuffer();
  40410. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  40411. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  40412. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  40413. // reset the frame buffer to the currently set buffer before waiting
  40414. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  40415. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  40416. // check if the commands have finished every 8 ms
  40417. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40418. _gl.flush();
  40419. await probeAsync( _gl, sync, 4 );
  40420. // read the data and delete the buffer
  40421. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  40422. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  40423. _gl.deleteBuffer( glBuffer );
  40424. _gl.deleteSync( sync );
  40425. return buffer;
  40426. } else {
  40427. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  40428. }
  40429. }
  40430. };
  40431. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  40432. // support previous signature with position first
  40433. if ( texture.isTexture !== true ) {
  40434. // @deprecated, r165
  40435. warnOnce( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  40436. position = arguments[ 0 ] || null;
  40437. texture = arguments[ 1 ];
  40438. }
  40439. const levelScale = Math.pow( 2, - level );
  40440. const width = Math.floor( texture.image.width * levelScale );
  40441. const height = Math.floor( texture.image.height * levelScale );
  40442. const x = position !== null ? position.x : 0;
  40443. const y = position !== null ? position.y : 0;
  40444. textures.setTexture2D( texture, 0 );
  40445. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  40446. state.unbindTexture();
  40447. };
  40448. const _srcFramebuffer = _gl.createFramebuffer();
  40449. const _dstFramebuffer = _gl.createFramebuffer();
  40450. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  40451. // support previous signature with dstPosition first
  40452. if ( srcTexture.isTexture !== true ) {
  40453. // @deprecated, r165
  40454. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  40455. dstPosition = arguments[ 0 ] || null;
  40456. srcTexture = arguments[ 1 ];
  40457. dstTexture = arguments[ 2 ];
  40458. dstLevel = arguments[ 3 ] || 0;
  40459. srcRegion = null;
  40460. }
  40461. // support the previous signature with just a single dst mipmap level
  40462. if ( dstLevel === null ) {
  40463. if ( srcLevel !== 0 ) {
  40464. // @deprecated, r171
  40465. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  40466. dstLevel = srcLevel;
  40467. srcLevel = 0;
  40468. } else {
  40469. dstLevel = 0;
  40470. }
  40471. }
  40472. // gather the necessary dimensions to copy
  40473. let width, height, depth, minX, minY, minZ;
  40474. let dstX, dstY, dstZ;
  40475. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  40476. if ( srcRegion !== null ) {
  40477. width = srcRegion.max.x - srcRegion.min.x;
  40478. height = srcRegion.max.y - srcRegion.min.y;
  40479. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  40480. minX = srcRegion.min.x;
  40481. minY = srcRegion.min.y;
  40482. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  40483. } else {
  40484. const levelScale = Math.pow( 2, - srcLevel );
  40485. width = Math.floor( image.width * levelScale );
  40486. height = Math.floor( image.height * levelScale );
  40487. if ( srcTexture.isDataArrayTexture ) {
  40488. depth = image.depth;
  40489. } else if ( srcTexture.isData3DTexture ) {
  40490. depth = Math.floor( image.depth * levelScale );
  40491. } else {
  40492. depth = 1;
  40493. }
  40494. minX = 0;
  40495. minY = 0;
  40496. minZ = 0;
  40497. }
  40498. if ( dstPosition !== null ) {
  40499. dstX = dstPosition.x;
  40500. dstY = dstPosition.y;
  40501. dstZ = dstPosition.z;
  40502. } else {
  40503. dstX = 0;
  40504. dstY = 0;
  40505. dstZ = 0;
  40506. }
  40507. // Set up the destination target
  40508. const glFormat = utils.convert( dstTexture.format );
  40509. const glType = utils.convert( dstTexture.type );
  40510. let glTarget;
  40511. if ( dstTexture.isData3DTexture ) {
  40512. textures.setTexture3D( dstTexture, 0 );
  40513. glTarget = _gl.TEXTURE_3D;
  40514. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  40515. textures.setTexture2DArray( dstTexture, 0 );
  40516. glTarget = _gl.TEXTURE_2D_ARRAY;
  40517. } else {
  40518. textures.setTexture2D( dstTexture, 0 );
  40519. glTarget = _gl.TEXTURE_2D;
  40520. }
  40521. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40522. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40523. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40524. // used for copying data from cpu
  40525. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  40526. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  40527. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  40528. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  40529. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  40530. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  40531. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  40532. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  40533. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  40534. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  40535. // set up the src texture
  40536. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  40537. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  40538. if ( srcTexture.isDepthTexture ) {
  40539. const srcTextureProperties = properties.get( srcTexture );
  40540. const dstTextureProperties = properties.get( dstTexture );
  40541. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  40542. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  40543. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  40544. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  40545. for ( let i = 0; i < depth; i ++ ) {
  40546. // if the source or destination are a 3d target then a layer needs to be bound
  40547. if ( isSrc3D ) {
  40548. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  40549. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  40550. }
  40551. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  40552. }
  40553. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  40554. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  40555. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  40556. // get the appropriate frame buffers
  40557. const srcTextureProperties = properties.get( srcTexture );
  40558. const dstTextureProperties = properties.get( dstTexture );
  40559. // bind the frame buffer targets
  40560. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  40561. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  40562. for ( let i = 0; i < depth; i ++ ) {
  40563. // assign the correct layers and mip maps to the frame buffers
  40564. if ( isSrc3D ) {
  40565. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  40566. } else {
  40567. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  40568. }
  40569. if ( isDst3D ) {
  40570. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  40571. } else {
  40572. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  40573. }
  40574. // copy the data using the fastest function that can achieve the copy
  40575. if ( srcLevel !== 0 ) {
  40576. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  40577. } else if ( isDst3D ) {
  40578. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  40579. } else {
  40580. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  40581. }
  40582. }
  40583. // unbind read, draw buffers
  40584. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  40585. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  40586. } else {
  40587. if ( isDst3D ) {
  40588. // copy data into the 3d texture
  40589. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  40590. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  40591. } else if ( dstTexture.isCompressedArrayTexture ) {
  40592. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  40593. } else {
  40594. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  40595. }
  40596. } else {
  40597. // copy data into the 2d texture
  40598. if ( srcTexture.isDataTexture ) {
  40599. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  40600. } else if ( srcTexture.isCompressedTexture ) {
  40601. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  40602. } else {
  40603. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  40604. }
  40605. }
  40606. }
  40607. // reset values
  40608. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40609. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40610. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40611. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40612. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40613. // Generate mipmaps only when copying level 0
  40614. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  40615. _gl.generateMipmap( glTarget );
  40616. }
  40617. state.unbindTexture();
  40618. };
  40619. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40620. // support previous signature with source box first
  40621. if ( srcTexture.isTexture !== true ) {
  40622. // @deprecated, r165
  40623. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  40624. srcRegion = arguments[ 0 ] || null;
  40625. dstPosition = arguments[ 1 ] || null;
  40626. srcTexture = arguments[ 2 ];
  40627. dstTexture = arguments[ 3 ];
  40628. level = arguments[ 4 ] || 0;
  40629. }
  40630. // @deprecated, r170
  40631. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  40632. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  40633. };
  40634. this.initRenderTarget = function ( target ) {
  40635. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  40636. textures.setupRenderTarget( target );
  40637. }
  40638. };
  40639. this.initTexture = function ( texture ) {
  40640. if ( texture.isCubeTexture ) {
  40641. textures.setTextureCube( texture, 0 );
  40642. } else if ( texture.isData3DTexture ) {
  40643. textures.setTexture3D( texture, 0 );
  40644. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40645. textures.setTexture2DArray( texture, 0 );
  40646. } else {
  40647. textures.setTexture2D( texture, 0 );
  40648. }
  40649. state.unbindTexture();
  40650. };
  40651. this.resetState = function () {
  40652. _currentActiveCubeFace = 0;
  40653. _currentActiveMipmapLevel = 0;
  40654. _currentRenderTarget = null;
  40655. state.reset();
  40656. bindingStates.reset();
  40657. };
  40658. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  40659. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  40660. }
  40661. }
  40662. get coordinateSystem() {
  40663. return WebGLCoordinateSystem;
  40664. }
  40665. get outputColorSpace() {
  40666. return this._outputColorSpace;
  40667. }
  40668. set outputColorSpace( colorSpace ) {
  40669. this._outputColorSpace = colorSpace;
  40670. const gl = this.getContext();
  40671. gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  40672. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  40673. }
  40674. }
  40675. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  40676. exports.AddEquation = AddEquation;
  40677. exports.AddOperation = AddOperation;
  40678. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  40679. exports.AdditiveBlending = AdditiveBlending;
  40680. exports.AgXToneMapping = AgXToneMapping;
  40681. exports.AlphaFormat = AlphaFormat;
  40682. exports.AlwaysCompare = AlwaysCompare;
  40683. exports.AlwaysDepth = AlwaysDepth;
  40684. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  40685. exports.AmbientLight = AmbientLight;
  40686. exports.AnimationAction = AnimationAction;
  40687. exports.AnimationClip = AnimationClip;
  40688. exports.AnimationLoader = AnimationLoader;
  40689. exports.AnimationMixer = AnimationMixer;
  40690. exports.AnimationObjectGroup = AnimationObjectGroup;
  40691. exports.AnimationUtils = AnimationUtils;
  40692. exports.ArcCurve = ArcCurve;
  40693. exports.ArrayCamera = ArrayCamera;
  40694. exports.ArrowHelper = ArrowHelper;
  40695. exports.AttachedBindMode = AttachedBindMode;
  40696. exports.Audio = Audio;
  40697. exports.AudioAnalyser = AudioAnalyser;
  40698. exports.AudioContext = AudioContext;
  40699. exports.AudioListener = AudioListener;
  40700. exports.AudioLoader = AudioLoader;
  40701. exports.AxesHelper = AxesHelper;
  40702. exports.BackSide = BackSide;
  40703. exports.BasicDepthPacking = BasicDepthPacking;
  40704. exports.BasicShadowMap = BasicShadowMap;
  40705. exports.BatchedMesh = BatchedMesh;
  40706. exports.Bone = Bone;
  40707. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  40708. exports.Box2 = Box2;
  40709. exports.Box3 = Box3;
  40710. exports.Box3Helper = Box3Helper;
  40711. exports.BoxGeometry = BoxGeometry;
  40712. exports.BoxHelper = BoxHelper;
  40713. exports.BufferAttribute = BufferAttribute;
  40714. exports.BufferGeometry = BufferGeometry;
  40715. exports.BufferGeometryLoader = BufferGeometryLoader;
  40716. exports.ByteType = ByteType;
  40717. exports.Cache = Cache;
  40718. exports.Camera = Camera;
  40719. exports.CameraHelper = CameraHelper;
  40720. exports.CanvasTexture = CanvasTexture;
  40721. exports.CapsuleGeometry = CapsuleGeometry;
  40722. exports.CatmullRomCurve3 = CatmullRomCurve3;
  40723. exports.CineonToneMapping = CineonToneMapping;
  40724. exports.CircleGeometry = CircleGeometry;
  40725. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  40726. exports.Clock = Clock;
  40727. exports.Color = Color;
  40728. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  40729. exports.ColorManagement = ColorManagement;
  40730. exports.CompressedArrayTexture = CompressedArrayTexture;
  40731. exports.CompressedCubeTexture = CompressedCubeTexture;
  40732. exports.CompressedTexture = CompressedTexture;
  40733. exports.CompressedTextureLoader = CompressedTextureLoader;
  40734. exports.ConeGeometry = ConeGeometry;
  40735. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  40736. exports.ConstantColorFactor = ConstantColorFactor;
  40737. exports.Controls = Controls;
  40738. exports.CubeCamera = CubeCamera;
  40739. exports.CubeReflectionMapping = CubeReflectionMapping;
  40740. exports.CubeRefractionMapping = CubeRefractionMapping;
  40741. exports.CubeTexture = CubeTexture;
  40742. exports.CubeTextureLoader = CubeTextureLoader;
  40743. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  40744. exports.CubicBezierCurve = CubicBezierCurve;
  40745. exports.CubicBezierCurve3 = CubicBezierCurve3;
  40746. exports.CubicInterpolant = CubicInterpolant;
  40747. exports.CullFaceBack = CullFaceBack;
  40748. exports.CullFaceFront = CullFaceFront;
  40749. exports.CullFaceFrontBack = CullFaceFrontBack;
  40750. exports.CullFaceNone = CullFaceNone;
  40751. exports.Curve = Curve;
  40752. exports.CurvePath = CurvePath;
  40753. exports.CustomBlending = CustomBlending;
  40754. exports.CustomToneMapping = CustomToneMapping;
  40755. exports.CylinderGeometry = CylinderGeometry;
  40756. exports.Cylindrical = Cylindrical;
  40757. exports.Data3DTexture = Data3DTexture;
  40758. exports.DataArrayTexture = DataArrayTexture;
  40759. exports.DataTexture = DataTexture;
  40760. exports.DataTextureLoader = DataTextureLoader;
  40761. exports.DataUtils = DataUtils;
  40762. exports.DecrementStencilOp = DecrementStencilOp;
  40763. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  40764. exports.DefaultLoadingManager = DefaultLoadingManager;
  40765. exports.DepthFormat = DepthFormat;
  40766. exports.DepthStencilFormat = DepthStencilFormat;
  40767. exports.DepthTexture = DepthTexture;
  40768. exports.DetachedBindMode = DetachedBindMode;
  40769. exports.DirectionalLight = DirectionalLight;
  40770. exports.DirectionalLightHelper = DirectionalLightHelper;
  40771. exports.DiscreteInterpolant = DiscreteInterpolant;
  40772. exports.DodecahedronGeometry = DodecahedronGeometry;
  40773. exports.DoubleSide = DoubleSide;
  40774. exports.DstAlphaFactor = DstAlphaFactor;
  40775. exports.DstColorFactor = DstColorFactor;
  40776. exports.DynamicCopyUsage = DynamicCopyUsage;
  40777. exports.DynamicDrawUsage = DynamicDrawUsage;
  40778. exports.DynamicReadUsage = DynamicReadUsage;
  40779. exports.EdgesGeometry = EdgesGeometry;
  40780. exports.EllipseCurve = EllipseCurve;
  40781. exports.EqualCompare = EqualCompare;
  40782. exports.EqualDepth = EqualDepth;
  40783. exports.EqualStencilFunc = EqualStencilFunc;
  40784. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  40785. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  40786. exports.Euler = Euler;
  40787. exports.EventDispatcher = EventDispatcher;
  40788. exports.ExtrudeGeometry = ExtrudeGeometry;
  40789. exports.FileLoader = FileLoader;
  40790. exports.Float16BufferAttribute = Float16BufferAttribute;
  40791. exports.Float32BufferAttribute = Float32BufferAttribute;
  40792. exports.FloatType = FloatType;
  40793. exports.Fog = Fog;
  40794. exports.FogExp2 = FogExp2;
  40795. exports.FramebufferTexture = FramebufferTexture;
  40796. exports.FrontSide = FrontSide;
  40797. exports.Frustum = Frustum;
  40798. exports.GLBufferAttribute = GLBufferAttribute;
  40799. exports.GLSL1 = GLSL1;
  40800. exports.GLSL3 = GLSL3;
  40801. exports.GreaterCompare = GreaterCompare;
  40802. exports.GreaterDepth = GreaterDepth;
  40803. exports.GreaterEqualCompare = GreaterEqualCompare;
  40804. exports.GreaterEqualDepth = GreaterEqualDepth;
  40805. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  40806. exports.GreaterStencilFunc = GreaterStencilFunc;
  40807. exports.GridHelper = GridHelper;
  40808. exports.Group = Group;
  40809. exports.HalfFloatType = HalfFloatType;
  40810. exports.HemisphereLight = HemisphereLight;
  40811. exports.HemisphereLightHelper = HemisphereLightHelper;
  40812. exports.IcosahedronGeometry = IcosahedronGeometry;
  40813. exports.ImageBitmapLoader = ImageBitmapLoader;
  40814. exports.ImageLoader = ImageLoader;
  40815. exports.ImageUtils = ImageUtils;
  40816. exports.IncrementStencilOp = IncrementStencilOp;
  40817. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  40818. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  40819. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  40820. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  40821. exports.InstancedMesh = InstancedMesh;
  40822. exports.Int16BufferAttribute = Int16BufferAttribute;
  40823. exports.Int32BufferAttribute = Int32BufferAttribute;
  40824. exports.Int8BufferAttribute = Int8BufferAttribute;
  40825. exports.IntType = IntType;
  40826. exports.InterleavedBuffer = InterleavedBuffer;
  40827. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  40828. exports.Interpolant = Interpolant;
  40829. exports.InterpolateDiscrete = InterpolateDiscrete;
  40830. exports.InterpolateLinear = InterpolateLinear;
  40831. exports.InterpolateSmooth = InterpolateSmooth;
  40832. exports.InvertStencilOp = InvertStencilOp;
  40833. exports.KeepStencilOp = KeepStencilOp;
  40834. exports.KeyframeTrack = KeyframeTrack;
  40835. exports.LOD = LOD;
  40836. exports.LatheGeometry = LatheGeometry;
  40837. exports.Layers = Layers;
  40838. exports.LessCompare = LessCompare;
  40839. exports.LessDepth = LessDepth;
  40840. exports.LessEqualCompare = LessEqualCompare;
  40841. exports.LessEqualDepth = LessEqualDepth;
  40842. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  40843. exports.LessStencilFunc = LessStencilFunc;
  40844. exports.Light = Light;
  40845. exports.LightProbe = LightProbe;
  40846. exports.Line = Line;
  40847. exports.Line3 = Line3;
  40848. exports.LineBasicMaterial = LineBasicMaterial;
  40849. exports.LineCurve = LineCurve;
  40850. exports.LineCurve3 = LineCurve3;
  40851. exports.LineDashedMaterial = LineDashedMaterial;
  40852. exports.LineLoop = LineLoop;
  40853. exports.LineSegments = LineSegments;
  40854. exports.LinearFilter = LinearFilter;
  40855. exports.LinearInterpolant = LinearInterpolant;
  40856. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  40857. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  40858. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  40859. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  40860. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  40861. exports.LinearToneMapping = LinearToneMapping;
  40862. exports.LinearTransfer = LinearTransfer;
  40863. exports.Loader = Loader;
  40864. exports.LoaderUtils = LoaderUtils;
  40865. exports.LoadingManager = LoadingManager;
  40866. exports.LoopOnce = LoopOnce;
  40867. exports.LoopPingPong = LoopPingPong;
  40868. exports.LoopRepeat = LoopRepeat;
  40869. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  40870. exports.LuminanceFormat = LuminanceFormat;
  40871. exports.MOUSE = MOUSE;
  40872. exports.Material = Material;
  40873. exports.MaterialLoader = MaterialLoader;
  40874. exports.MathUtils = MathUtils;
  40875. exports.Matrix2 = Matrix2;
  40876. exports.Matrix3 = Matrix3;
  40877. exports.Matrix4 = Matrix4;
  40878. exports.MaxEquation = MaxEquation;
  40879. exports.Mesh = Mesh;
  40880. exports.MeshBasicMaterial = MeshBasicMaterial;
  40881. exports.MeshDepthMaterial = MeshDepthMaterial;
  40882. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  40883. exports.MeshLambertMaterial = MeshLambertMaterial;
  40884. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  40885. exports.MeshNormalMaterial = MeshNormalMaterial;
  40886. exports.MeshPhongMaterial = MeshPhongMaterial;
  40887. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  40888. exports.MeshStandardMaterial = MeshStandardMaterial;
  40889. exports.MeshToonMaterial = MeshToonMaterial;
  40890. exports.MinEquation = MinEquation;
  40891. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  40892. exports.MixOperation = MixOperation;
  40893. exports.MultiplyBlending = MultiplyBlending;
  40894. exports.MultiplyOperation = MultiplyOperation;
  40895. exports.NearestFilter = NearestFilter;
  40896. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  40897. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  40898. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  40899. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  40900. exports.NeutralToneMapping = NeutralToneMapping;
  40901. exports.NeverCompare = NeverCompare;
  40902. exports.NeverDepth = NeverDepth;
  40903. exports.NeverStencilFunc = NeverStencilFunc;
  40904. exports.NoBlending = NoBlending;
  40905. exports.NoColorSpace = NoColorSpace;
  40906. exports.NoToneMapping = NoToneMapping;
  40907. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  40908. exports.NormalBlending = NormalBlending;
  40909. exports.NotEqualCompare = NotEqualCompare;
  40910. exports.NotEqualDepth = NotEqualDepth;
  40911. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  40912. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  40913. exports.Object3D = Object3D;
  40914. exports.ObjectLoader = ObjectLoader;
  40915. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  40916. exports.OctahedronGeometry = OctahedronGeometry;
  40917. exports.OneFactor = OneFactor;
  40918. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  40919. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  40920. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  40921. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  40922. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  40923. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  40924. exports.OrthographicCamera = OrthographicCamera;
  40925. exports.PCFShadowMap = PCFShadowMap;
  40926. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  40927. exports.PMREMGenerator = PMREMGenerator;
  40928. exports.Path = Path;
  40929. exports.PerspectiveCamera = PerspectiveCamera;
  40930. exports.Plane = Plane;
  40931. exports.PlaneGeometry = PlaneGeometry;
  40932. exports.PlaneHelper = PlaneHelper;
  40933. exports.PointLight = PointLight;
  40934. exports.PointLightHelper = PointLightHelper;
  40935. exports.Points = Points;
  40936. exports.PointsMaterial = PointsMaterial;
  40937. exports.PolarGridHelper = PolarGridHelper;
  40938. exports.PolyhedronGeometry = PolyhedronGeometry;
  40939. exports.PositionalAudio = PositionalAudio;
  40940. exports.PropertyBinding = PropertyBinding;
  40941. exports.PropertyMixer = PropertyMixer;
  40942. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  40943. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  40944. exports.Quaternion = Quaternion;
  40945. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  40946. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  40947. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  40948. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  40949. exports.REVISION = REVISION;
  40950. exports.RGBADepthPacking = RGBADepthPacking;
  40951. exports.RGBAFormat = RGBAFormat;
  40952. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  40953. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  40954. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  40955. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  40956. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  40957. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  40958. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  40959. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  40960. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  40961. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  40962. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  40963. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  40964. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  40965. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  40966. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  40967. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  40968. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  40969. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  40970. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  40971. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  40972. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  40973. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  40974. exports.RGBDepthPacking = RGBDepthPacking;
  40975. exports.RGBFormat = RGBFormat;
  40976. exports.RGBIntegerFormat = RGBIntegerFormat;
  40977. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  40978. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  40979. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  40980. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  40981. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  40982. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  40983. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  40984. exports.RGDepthPacking = RGDepthPacking;
  40985. exports.RGFormat = RGFormat;
  40986. exports.RGIntegerFormat = RGIntegerFormat;
  40987. exports.RawShaderMaterial = RawShaderMaterial;
  40988. exports.Ray = Ray;
  40989. exports.Raycaster = Raycaster;
  40990. exports.RectAreaLight = RectAreaLight;
  40991. exports.RedFormat = RedFormat;
  40992. exports.RedIntegerFormat = RedIntegerFormat;
  40993. exports.ReinhardToneMapping = ReinhardToneMapping;
  40994. exports.RenderTarget = RenderTarget;
  40995. exports.RenderTarget3D = RenderTarget3D;
  40996. exports.RenderTargetArray = RenderTargetArray;
  40997. exports.RepeatWrapping = RepeatWrapping;
  40998. exports.ReplaceStencilOp = ReplaceStencilOp;
  40999. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  41000. exports.RingGeometry = RingGeometry;
  41001. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  41002. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  41003. exports.SRGBColorSpace = SRGBColorSpace;
  41004. exports.SRGBTransfer = SRGBTransfer;
  41005. exports.Scene = Scene;
  41006. exports.ShaderChunk = ShaderChunk;
  41007. exports.ShaderLib = ShaderLib;
  41008. exports.ShaderMaterial = ShaderMaterial;
  41009. exports.ShadowMaterial = ShadowMaterial;
  41010. exports.Shape = Shape;
  41011. exports.ShapeGeometry = ShapeGeometry;
  41012. exports.ShapePath = ShapePath;
  41013. exports.ShapeUtils = ShapeUtils;
  41014. exports.ShortType = ShortType;
  41015. exports.Skeleton = Skeleton;
  41016. exports.SkeletonHelper = SkeletonHelper;
  41017. exports.SkinnedMesh = SkinnedMesh;
  41018. exports.Source = Source;
  41019. exports.Sphere = Sphere;
  41020. exports.SphereGeometry = SphereGeometry;
  41021. exports.Spherical = Spherical;
  41022. exports.SphericalHarmonics3 = SphericalHarmonics3;
  41023. exports.SplineCurve = SplineCurve;
  41024. exports.SpotLight = SpotLight;
  41025. exports.SpotLightHelper = SpotLightHelper;
  41026. exports.Sprite = Sprite;
  41027. exports.SpriteMaterial = SpriteMaterial;
  41028. exports.SrcAlphaFactor = SrcAlphaFactor;
  41029. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  41030. exports.SrcColorFactor = SrcColorFactor;
  41031. exports.StaticCopyUsage = StaticCopyUsage;
  41032. exports.StaticDrawUsage = StaticDrawUsage;
  41033. exports.StaticReadUsage = StaticReadUsage;
  41034. exports.StereoCamera = StereoCamera;
  41035. exports.StreamCopyUsage = StreamCopyUsage;
  41036. exports.StreamDrawUsage = StreamDrawUsage;
  41037. exports.StreamReadUsage = StreamReadUsage;
  41038. exports.StringKeyframeTrack = StringKeyframeTrack;
  41039. exports.SubtractEquation = SubtractEquation;
  41040. exports.SubtractiveBlending = SubtractiveBlending;
  41041. exports.TOUCH = TOUCH;
  41042. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  41043. exports.TetrahedronGeometry = TetrahedronGeometry;
  41044. exports.Texture = Texture;
  41045. exports.TextureLoader = TextureLoader;
  41046. exports.TextureUtils = TextureUtils;
  41047. exports.TimestampQuery = TimestampQuery;
  41048. exports.TorusGeometry = TorusGeometry;
  41049. exports.TorusKnotGeometry = TorusKnotGeometry;
  41050. exports.Triangle = Triangle;
  41051. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  41052. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  41053. exports.TrianglesDrawMode = TrianglesDrawMode;
  41054. exports.TubeGeometry = TubeGeometry;
  41055. exports.UVMapping = UVMapping;
  41056. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  41057. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  41058. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  41059. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  41060. exports.Uniform = Uniform;
  41061. exports.UniformsGroup = UniformsGroup;
  41062. exports.UniformsLib = UniformsLib;
  41063. exports.UniformsUtils = UniformsUtils;
  41064. exports.UnsignedByteType = UnsignedByteType;
  41065. exports.UnsignedInt248Type = UnsignedInt248Type;
  41066. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  41067. exports.UnsignedIntType = UnsignedIntType;
  41068. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  41069. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  41070. exports.UnsignedShortType = UnsignedShortType;
  41071. exports.VSMShadowMap = VSMShadowMap;
  41072. exports.Vector2 = Vector2;
  41073. exports.Vector3 = Vector3;
  41074. exports.Vector4 = Vector4;
  41075. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  41076. exports.VideoFrameTexture = VideoFrameTexture;
  41077. exports.VideoTexture = VideoTexture;
  41078. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  41079. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  41080. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  41081. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  41082. exports.WebGLRenderTarget = WebGLRenderTarget;
  41083. exports.WebGLRenderer = WebGLRenderer;
  41084. exports.WebGLUtils = WebGLUtils;
  41085. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  41086. exports.WebXRController = WebXRController;
  41087. exports.WireframeGeometry = WireframeGeometry;
  41088. exports.WrapAroundEnding = WrapAroundEnding;
  41089. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  41090. exports.ZeroFactor = ZeroFactor;
  41091. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  41092. exports.ZeroStencilOp = ZeroStencilOp;
  41093. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号