three.cjs 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. Object.defineProperty(exports, '__esModule', { value: true });
  8. const REVISION = '147';
  9. const MOUSE = {
  10. LEFT: 0,
  11. MIDDLE: 1,
  12. RIGHT: 2,
  13. ROTATE: 0,
  14. DOLLY: 1,
  15. PAN: 2
  16. };
  17. const TOUCH = {
  18. ROTATE: 0,
  19. PAN: 1,
  20. DOLLY_PAN: 2,
  21. DOLLY_ROTATE: 3
  22. };
  23. const CullFaceNone = 0;
  24. const CullFaceBack = 1;
  25. const CullFaceFront = 2;
  26. const CullFaceFrontBack = 3;
  27. const BasicShadowMap = 0;
  28. const PCFShadowMap = 1;
  29. const PCFSoftShadowMap = 2;
  30. const VSMShadowMap = 3;
  31. const FrontSide = 0;
  32. const BackSide = 1;
  33. const DoubleSide = 2;
  34. const NoBlending = 0;
  35. const NormalBlending = 1;
  36. const AdditiveBlending = 2;
  37. const SubtractiveBlending = 3;
  38. const MultiplyBlending = 4;
  39. const CustomBlending = 5;
  40. const AddEquation = 100;
  41. const SubtractEquation = 101;
  42. const ReverseSubtractEquation = 102;
  43. const MinEquation = 103;
  44. const MaxEquation = 104;
  45. const ZeroFactor = 200;
  46. const OneFactor = 201;
  47. const SrcColorFactor = 202;
  48. const OneMinusSrcColorFactor = 203;
  49. const SrcAlphaFactor = 204;
  50. const OneMinusSrcAlphaFactor = 205;
  51. const DstAlphaFactor = 206;
  52. const OneMinusDstAlphaFactor = 207;
  53. const DstColorFactor = 208;
  54. const OneMinusDstColorFactor = 209;
  55. const SrcAlphaSaturateFactor = 210;
  56. const NeverDepth = 0;
  57. const AlwaysDepth = 1;
  58. const LessDepth = 2;
  59. const LessEqualDepth = 3;
  60. const EqualDepth = 4;
  61. const GreaterEqualDepth = 5;
  62. const GreaterDepth = 6;
  63. const NotEqualDepth = 7;
  64. const MultiplyOperation = 0;
  65. const MixOperation = 1;
  66. const AddOperation = 2;
  67. const NoToneMapping = 0;
  68. const LinearToneMapping = 1;
  69. const ReinhardToneMapping = 2;
  70. const CineonToneMapping = 3;
  71. const ACESFilmicToneMapping = 4;
  72. const CustomToneMapping = 5;
  73. const UVMapping = 300;
  74. const CubeReflectionMapping = 301;
  75. const CubeRefractionMapping = 302;
  76. const EquirectangularReflectionMapping = 303;
  77. const EquirectangularRefractionMapping = 304;
  78. const CubeUVReflectionMapping = 306;
  79. const RepeatWrapping = 1000;
  80. const ClampToEdgeWrapping = 1001;
  81. const MirroredRepeatWrapping = 1002;
  82. const NearestFilter = 1003;
  83. const NearestMipmapNearestFilter = 1004;
  84. const NearestMipMapNearestFilter = 1004;
  85. const NearestMipmapLinearFilter = 1005;
  86. const NearestMipMapLinearFilter = 1005;
  87. const LinearFilter = 1006;
  88. const LinearMipmapNearestFilter = 1007;
  89. const LinearMipMapNearestFilter = 1007;
  90. const LinearMipmapLinearFilter = 1008;
  91. const LinearMipMapLinearFilter = 1008;
  92. const UnsignedByteType = 1009;
  93. const ByteType = 1010;
  94. const ShortType = 1011;
  95. const UnsignedShortType = 1012;
  96. const IntType = 1013;
  97. const UnsignedIntType = 1014;
  98. const FloatType = 1015;
  99. const HalfFloatType = 1016;
  100. const UnsignedShort4444Type = 1017;
  101. const UnsignedShort5551Type = 1018;
  102. const UnsignedInt248Type = 1020;
  103. const AlphaFormat = 1021;
  104. const RGBFormat = 1022; // @deprecated since r137
  105. const RGBAFormat = 1023;
  106. const LuminanceFormat = 1024;
  107. const LuminanceAlphaFormat = 1025;
  108. const DepthFormat = 1026;
  109. const DepthStencilFormat = 1027;
  110. const RedFormat = 1028;
  111. const RedIntegerFormat = 1029;
  112. const RGFormat = 1030;
  113. const RGIntegerFormat = 1031;
  114. const RGBAIntegerFormat = 1033;
  115. const RGB_S3TC_DXT1_Format = 33776;
  116. const RGBA_S3TC_DXT1_Format = 33777;
  117. const RGBA_S3TC_DXT3_Format = 33778;
  118. const RGBA_S3TC_DXT5_Format = 33779;
  119. const RGB_PVRTC_4BPPV1_Format = 35840;
  120. const RGB_PVRTC_2BPPV1_Format = 35841;
  121. const RGBA_PVRTC_4BPPV1_Format = 35842;
  122. const RGBA_PVRTC_2BPPV1_Format = 35843;
  123. const RGB_ETC1_Format = 36196;
  124. const RGB_ETC2_Format = 37492;
  125. const RGBA_ETC2_EAC_Format = 37496;
  126. const RGBA_ASTC_4x4_Format = 37808;
  127. const RGBA_ASTC_5x4_Format = 37809;
  128. const RGBA_ASTC_5x5_Format = 37810;
  129. const RGBA_ASTC_6x5_Format = 37811;
  130. const RGBA_ASTC_6x6_Format = 37812;
  131. const RGBA_ASTC_8x5_Format = 37813;
  132. const RGBA_ASTC_8x6_Format = 37814;
  133. const RGBA_ASTC_8x8_Format = 37815;
  134. const RGBA_ASTC_10x5_Format = 37816;
  135. const RGBA_ASTC_10x6_Format = 37817;
  136. const RGBA_ASTC_10x8_Format = 37818;
  137. const RGBA_ASTC_10x10_Format = 37819;
  138. const RGBA_ASTC_12x10_Format = 37820;
  139. const RGBA_ASTC_12x12_Format = 37821;
  140. const RGBA_BPTC_Format = 36492;
  141. const LoopOnce = 2200;
  142. const LoopRepeat = 2201;
  143. const LoopPingPong = 2202;
  144. const InterpolateDiscrete = 2300;
  145. const InterpolateLinear = 2301;
  146. const InterpolateSmooth = 2302;
  147. const ZeroCurvatureEnding = 2400;
  148. const ZeroSlopeEnding = 2401;
  149. const WrapAroundEnding = 2402;
  150. const NormalAnimationBlendMode = 2500;
  151. const AdditiveAnimationBlendMode = 2501;
  152. const TrianglesDrawMode = 0;
  153. const TriangleStripDrawMode = 1;
  154. const TriangleFanDrawMode = 2;
  155. const LinearEncoding = 3000;
  156. const sRGBEncoding = 3001;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const TangentSpaceNormalMap = 0;
  160. const ObjectSpaceNormalMap = 1;
  161. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  162. const NoColorSpace = '';
  163. const SRGBColorSpace = 'srgb';
  164. const LinearSRGBColorSpace = 'srgb-linear';
  165. const ZeroStencilOp = 0;
  166. const KeepStencilOp = 7680;
  167. const ReplaceStencilOp = 7681;
  168. const IncrementStencilOp = 7682;
  169. const DecrementStencilOp = 7683;
  170. const IncrementWrapStencilOp = 34055;
  171. const DecrementWrapStencilOp = 34056;
  172. const InvertStencilOp = 5386;
  173. const NeverStencilFunc = 512;
  174. const LessStencilFunc = 513;
  175. const EqualStencilFunc = 514;
  176. const LessEqualStencilFunc = 515;
  177. const GreaterStencilFunc = 516;
  178. const NotEqualStencilFunc = 517;
  179. const GreaterEqualStencilFunc = 518;
  180. const AlwaysStencilFunc = 519;
  181. const StaticDrawUsage = 35044;
  182. const DynamicDrawUsage = 35048;
  183. const StreamDrawUsage = 35040;
  184. const StaticReadUsage = 35045;
  185. const DynamicReadUsage = 35049;
  186. const StreamReadUsage = 35041;
  187. const StaticCopyUsage = 35046;
  188. const DynamicCopyUsage = 35050;
  189. const StreamCopyUsage = 35042;
  190. const GLSL1 = '100';
  191. const GLSL3 = '300 es';
  192. const _SRGBAFormat = 1035; // fallback for WebGL 1
  193. /**
  194. * https://github.com/mrdoob/eventdispatcher.js/
  195. */
  196. class EventDispatcher {
  197. addEventListener(type, listener) {
  198. if (this._listeners === undefined) this._listeners = {};
  199. const listeners = this._listeners;
  200. if (listeners[type] === undefined) {
  201. listeners[type] = [];
  202. }
  203. if (listeners[type].indexOf(listener) === -1) {
  204. listeners[type].push(listener);
  205. }
  206. }
  207. hasEventListener(type, listener) {
  208. if (this._listeners === undefined) return false;
  209. const listeners = this._listeners;
  210. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  211. }
  212. removeEventListener(type, listener) {
  213. if (this._listeners === undefined) return;
  214. const listeners = this._listeners;
  215. const listenerArray = listeners[type];
  216. if (listenerArray !== undefined) {
  217. const index = listenerArray.indexOf(listener);
  218. if (index !== -1) {
  219. listenerArray.splice(index, 1);
  220. }
  221. }
  222. }
  223. dispatchEvent(event) {
  224. if (this._listeners === undefined) return;
  225. const listeners = this._listeners;
  226. const listenerArray = listeners[event.type];
  227. if (listenerArray !== undefined) {
  228. event.target = this;
  229. // Make a copy, in case listeners are removed while iterating.
  230. const array = listenerArray.slice(0);
  231. for (let i = 0, l = array.length; i < l; i++) {
  232. array[i].call(this, event);
  233. }
  234. event.target = null;
  235. }
  236. }
  237. }
  238. 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'];
  239. let _seed = 1234567;
  240. const DEG2RAD = Math.PI / 180;
  241. const RAD2DEG = 180 / Math.PI;
  242. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  243. function generateUUID() {
  244. const d0 = Math.random() * 0xffffffff | 0;
  245. const d1 = Math.random() * 0xffffffff | 0;
  246. const d2 = Math.random() * 0xffffffff | 0;
  247. const d3 = Math.random() * 0xffffffff | 0;
  248. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff];
  249. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  250. return uuid.toLowerCase();
  251. }
  252. function clamp(value, min, max) {
  253. return Math.max(min, Math.min(max, value));
  254. }
  255. // compute euclidean modulo of m % n
  256. // https://en.wikipedia.org/wiki/Modulo_operation
  257. function euclideanModulo(n, m) {
  258. return (n % m + m) % m;
  259. }
  260. // Linear mapping from range <a1, a2> to range <b1, b2>
  261. function mapLinear(x, a1, a2, b1, b2) {
  262. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  263. }
  264. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  265. function inverseLerp(x, y, value) {
  266. if (x !== y) {
  267. return (value - x) / (y - x);
  268. } else {
  269. return 0;
  270. }
  271. }
  272. // https://en.wikipedia.org/wiki/Linear_interpolation
  273. function lerp(x, y, t) {
  274. return (1 - t) * x + t * y;
  275. }
  276. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  277. function damp(x, y, lambda, dt) {
  278. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  279. }
  280. // https://www.desmos.com/calculator/vcsjnyz7x4
  281. function pingpong(x, length = 1) {
  282. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  283. }
  284. // http://en.wikipedia.org/wiki/Smoothstep
  285. function smoothstep(x, min, max) {
  286. if (x <= min) return 0;
  287. if (x >= max) return 1;
  288. x = (x - min) / (max - min);
  289. return x * x * (3 - 2 * x);
  290. }
  291. function smootherstep(x, min, max) {
  292. if (x <= min) return 0;
  293. if (x >= max) return 1;
  294. x = (x - min) / (max - min);
  295. return x * x * x * (x * (x * 6 - 15) + 10);
  296. }
  297. // Random integer from <low, high> interval
  298. function randInt(low, high) {
  299. return low + Math.floor(Math.random() * (high - low + 1));
  300. }
  301. // Random float from <low, high> interval
  302. function randFloat(low, high) {
  303. return low + Math.random() * (high - low);
  304. }
  305. // Random float from <-range/2, range/2> interval
  306. function randFloatSpread(range) {
  307. return range * (0.5 - Math.random());
  308. }
  309. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  310. function seededRandom(s) {
  311. if (s !== undefined) _seed = s;
  312. // Mulberry32 generator
  313. let t = _seed += 0x6D2B79F5;
  314. t = Math.imul(t ^ t >>> 15, t | 1);
  315. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  316. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  317. }
  318. function degToRad(degrees) {
  319. return degrees * DEG2RAD;
  320. }
  321. function radToDeg(radians) {
  322. return radians * RAD2DEG;
  323. }
  324. function isPowerOfTwo(value) {
  325. return (value & value - 1) === 0 && value !== 0;
  326. }
  327. function ceilPowerOfTwo(value) {
  328. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  329. }
  330. function floorPowerOfTwo(value) {
  331. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  332. }
  333. function setQuaternionFromProperEuler(q, a, b, c, order) {
  334. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  335. // rotations are applied to the axes in the order specified by 'order'
  336. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  337. // angles are in radians
  338. const cos = Math.cos;
  339. const sin = Math.sin;
  340. const c2 = cos(b / 2);
  341. const s2 = sin(b / 2);
  342. const c13 = cos((a + c) / 2);
  343. const s13 = sin((a + c) / 2);
  344. const c1_3 = cos((a - c) / 2);
  345. const s1_3 = sin((a - c) / 2);
  346. const c3_1 = cos((c - a) / 2);
  347. const s3_1 = sin((c - a) / 2);
  348. switch (order) {
  349. case 'XYX':
  350. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  351. break;
  352. case 'YZY':
  353. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  354. break;
  355. case 'ZXZ':
  356. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  357. break;
  358. case 'XZX':
  359. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  360. break;
  361. case 'YXY':
  362. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  363. break;
  364. case 'ZYZ':
  365. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  366. break;
  367. default:
  368. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  369. }
  370. }
  371. function denormalize(value, array) {
  372. switch (array.constructor) {
  373. case Float32Array:
  374. return value;
  375. case Uint16Array:
  376. return value / 65535.0;
  377. case Uint8Array:
  378. return value / 255.0;
  379. case Int16Array:
  380. return Math.max(value / 32767.0, -1.0);
  381. case Int8Array:
  382. return Math.max(value / 127.0, -1.0);
  383. default:
  384. throw new Error('Invalid component type.');
  385. }
  386. }
  387. function normalize(value, array) {
  388. switch (array.constructor) {
  389. case Float32Array:
  390. return value;
  391. case Uint16Array:
  392. return Math.round(value * 65535.0);
  393. case Uint8Array:
  394. return Math.round(value * 255.0);
  395. case Int16Array:
  396. return Math.round(value * 32767.0);
  397. case Int8Array:
  398. return Math.round(value * 127.0);
  399. default:
  400. throw new Error('Invalid component type.');
  401. }
  402. }
  403. var MathUtils = /*#__PURE__*/Object.freeze({
  404. __proto__: null,
  405. DEG2RAD: DEG2RAD,
  406. RAD2DEG: RAD2DEG,
  407. generateUUID: generateUUID,
  408. clamp: clamp,
  409. euclideanModulo: euclideanModulo,
  410. mapLinear: mapLinear,
  411. inverseLerp: inverseLerp,
  412. lerp: lerp,
  413. damp: damp,
  414. pingpong: pingpong,
  415. smoothstep: smoothstep,
  416. smootherstep: smootherstep,
  417. randInt: randInt,
  418. randFloat: randFloat,
  419. randFloatSpread: randFloatSpread,
  420. seededRandom: seededRandom,
  421. degToRad: degToRad,
  422. radToDeg: radToDeg,
  423. isPowerOfTwo: isPowerOfTwo,
  424. ceilPowerOfTwo: ceilPowerOfTwo,
  425. floorPowerOfTwo: floorPowerOfTwo,
  426. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  427. normalize: normalize,
  428. denormalize: denormalize
  429. });
  430. class Vector2 {
  431. constructor(x = 0, y = 0) {
  432. Vector2.prototype.isVector2 = true;
  433. this.x = x;
  434. this.y = y;
  435. }
  436. get width() {
  437. return this.x;
  438. }
  439. set width(value) {
  440. this.x = value;
  441. }
  442. get height() {
  443. return this.y;
  444. }
  445. set height(value) {
  446. this.y = value;
  447. }
  448. set(x, y) {
  449. this.x = x;
  450. this.y = y;
  451. return this;
  452. }
  453. setScalar(scalar) {
  454. this.x = scalar;
  455. this.y = scalar;
  456. return this;
  457. }
  458. setX(x) {
  459. this.x = x;
  460. return this;
  461. }
  462. setY(y) {
  463. this.y = y;
  464. return this;
  465. }
  466. setComponent(index, value) {
  467. switch (index) {
  468. case 0:
  469. this.x = value;
  470. break;
  471. case 1:
  472. this.y = value;
  473. break;
  474. default:
  475. throw new Error('index is out of range: ' + index);
  476. }
  477. return this;
  478. }
  479. getComponent(index) {
  480. switch (index) {
  481. case 0:
  482. return this.x;
  483. case 1:
  484. return this.y;
  485. default:
  486. throw new Error('index is out of range: ' + index);
  487. }
  488. }
  489. clone() {
  490. return new this.constructor(this.x, this.y);
  491. }
  492. copy(v) {
  493. this.x = v.x;
  494. this.y = v.y;
  495. return this;
  496. }
  497. add(v) {
  498. this.x += v.x;
  499. this.y += v.y;
  500. return this;
  501. }
  502. addScalar(s) {
  503. this.x += s;
  504. this.y += s;
  505. return this;
  506. }
  507. addVectors(a, b) {
  508. this.x = a.x + b.x;
  509. this.y = a.y + b.y;
  510. return this;
  511. }
  512. addScaledVector(v, s) {
  513. this.x += v.x * s;
  514. this.y += v.y * s;
  515. return this;
  516. }
  517. sub(v) {
  518. this.x -= v.x;
  519. this.y -= v.y;
  520. return this;
  521. }
  522. subScalar(s) {
  523. this.x -= s;
  524. this.y -= s;
  525. return this;
  526. }
  527. subVectors(a, b) {
  528. this.x = a.x - b.x;
  529. this.y = a.y - b.y;
  530. return this;
  531. }
  532. multiply(v) {
  533. this.x *= v.x;
  534. this.y *= v.y;
  535. return this;
  536. }
  537. multiplyScalar(scalar) {
  538. this.x *= scalar;
  539. this.y *= scalar;
  540. return this;
  541. }
  542. divide(v) {
  543. this.x /= v.x;
  544. this.y /= v.y;
  545. return this;
  546. }
  547. divideScalar(scalar) {
  548. return this.multiplyScalar(1 / scalar);
  549. }
  550. applyMatrix3(m) {
  551. const x = this.x,
  552. y = this.y;
  553. const e = m.elements;
  554. this.x = e[0] * x + e[3] * y + e[6];
  555. this.y = e[1] * x + e[4] * y + e[7];
  556. return this;
  557. }
  558. min(v) {
  559. this.x = Math.min(this.x, v.x);
  560. this.y = Math.min(this.y, v.y);
  561. return this;
  562. }
  563. max(v) {
  564. this.x = Math.max(this.x, v.x);
  565. this.y = Math.max(this.y, v.y);
  566. return this;
  567. }
  568. clamp(min, max) {
  569. // assumes min < max, componentwise
  570. this.x = Math.max(min.x, Math.min(max.x, this.x));
  571. this.y = Math.max(min.y, Math.min(max.y, this.y));
  572. return this;
  573. }
  574. clampScalar(minVal, maxVal) {
  575. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  576. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  577. return this;
  578. }
  579. clampLength(min, max) {
  580. const length = this.length();
  581. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  582. }
  583. floor() {
  584. this.x = Math.floor(this.x);
  585. this.y = Math.floor(this.y);
  586. return this;
  587. }
  588. ceil() {
  589. this.x = Math.ceil(this.x);
  590. this.y = Math.ceil(this.y);
  591. return this;
  592. }
  593. round() {
  594. this.x = Math.round(this.x);
  595. this.y = Math.round(this.y);
  596. return this;
  597. }
  598. roundToZero() {
  599. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  600. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  601. return this;
  602. }
  603. negate() {
  604. this.x = -this.x;
  605. this.y = -this.y;
  606. return this;
  607. }
  608. dot(v) {
  609. return this.x * v.x + this.y * v.y;
  610. }
  611. cross(v) {
  612. return this.x * v.y - this.y * v.x;
  613. }
  614. lengthSq() {
  615. return this.x * this.x + this.y * this.y;
  616. }
  617. length() {
  618. return Math.sqrt(this.x * this.x + this.y * this.y);
  619. }
  620. manhattanLength() {
  621. return Math.abs(this.x) + Math.abs(this.y);
  622. }
  623. normalize() {
  624. return this.divideScalar(this.length() || 1);
  625. }
  626. angle() {
  627. // computes the angle in radians with respect to the positive x-axis
  628. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  629. return angle;
  630. }
  631. distanceTo(v) {
  632. return Math.sqrt(this.distanceToSquared(v));
  633. }
  634. distanceToSquared(v) {
  635. const dx = this.x - v.x,
  636. dy = this.y - v.y;
  637. return dx * dx + dy * dy;
  638. }
  639. manhattanDistanceTo(v) {
  640. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  641. }
  642. setLength(length) {
  643. return this.normalize().multiplyScalar(length);
  644. }
  645. lerp(v, alpha) {
  646. this.x += (v.x - this.x) * alpha;
  647. this.y += (v.y - this.y) * alpha;
  648. return this;
  649. }
  650. lerpVectors(v1, v2, alpha) {
  651. this.x = v1.x + (v2.x - v1.x) * alpha;
  652. this.y = v1.y + (v2.y - v1.y) * alpha;
  653. return this;
  654. }
  655. equals(v) {
  656. return v.x === this.x && v.y === this.y;
  657. }
  658. fromArray(array, offset = 0) {
  659. this.x = array[offset];
  660. this.y = array[offset + 1];
  661. return this;
  662. }
  663. toArray(array = [], offset = 0) {
  664. array[offset] = this.x;
  665. array[offset + 1] = this.y;
  666. return array;
  667. }
  668. fromBufferAttribute(attribute, index) {
  669. this.x = attribute.getX(index);
  670. this.y = attribute.getY(index);
  671. return this;
  672. }
  673. rotateAround(center, angle) {
  674. const c = Math.cos(angle),
  675. s = Math.sin(angle);
  676. const x = this.x - center.x;
  677. const y = this.y - center.y;
  678. this.x = x * c - y * s + center.x;
  679. this.y = x * s + y * c + center.y;
  680. return this;
  681. }
  682. random() {
  683. this.x = Math.random();
  684. this.y = Math.random();
  685. return this;
  686. }
  687. *[Symbol.iterator]() {
  688. yield this.x;
  689. yield this.y;
  690. }
  691. }
  692. class Matrix3 {
  693. constructor() {
  694. Matrix3.prototype.isMatrix3 = true;
  695. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  696. }
  697. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  698. const te = this.elements;
  699. te[0] = n11;
  700. te[1] = n21;
  701. te[2] = n31;
  702. te[3] = n12;
  703. te[4] = n22;
  704. te[5] = n32;
  705. te[6] = n13;
  706. te[7] = n23;
  707. te[8] = n33;
  708. return this;
  709. }
  710. identity() {
  711. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  712. return this;
  713. }
  714. copy(m) {
  715. const te = this.elements;
  716. const me = m.elements;
  717. te[0] = me[0];
  718. te[1] = me[1];
  719. te[2] = me[2];
  720. te[3] = me[3];
  721. te[4] = me[4];
  722. te[5] = me[5];
  723. te[6] = me[6];
  724. te[7] = me[7];
  725. te[8] = me[8];
  726. return this;
  727. }
  728. extractBasis(xAxis, yAxis, zAxis) {
  729. xAxis.setFromMatrix3Column(this, 0);
  730. yAxis.setFromMatrix3Column(this, 1);
  731. zAxis.setFromMatrix3Column(this, 2);
  732. return this;
  733. }
  734. setFromMatrix4(m) {
  735. const me = m.elements;
  736. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  737. return this;
  738. }
  739. multiply(m) {
  740. return this.multiplyMatrices(this, m);
  741. }
  742. premultiply(m) {
  743. return this.multiplyMatrices(m, this);
  744. }
  745. multiplyMatrices(a, b) {
  746. const ae = a.elements;
  747. const be = b.elements;
  748. const te = this.elements;
  749. const a11 = ae[0],
  750. a12 = ae[3],
  751. a13 = ae[6];
  752. const a21 = ae[1],
  753. a22 = ae[4],
  754. a23 = ae[7];
  755. const a31 = ae[2],
  756. a32 = ae[5],
  757. a33 = ae[8];
  758. const b11 = be[0],
  759. b12 = be[3],
  760. b13 = be[6];
  761. const b21 = be[1],
  762. b22 = be[4],
  763. b23 = be[7];
  764. const b31 = be[2],
  765. b32 = be[5],
  766. b33 = be[8];
  767. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  768. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  769. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  770. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  771. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  772. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  773. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  774. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  775. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  776. return this;
  777. }
  778. multiplyScalar(s) {
  779. const te = this.elements;
  780. te[0] *= s;
  781. te[3] *= s;
  782. te[6] *= s;
  783. te[1] *= s;
  784. te[4] *= s;
  785. te[7] *= s;
  786. te[2] *= s;
  787. te[5] *= s;
  788. te[8] *= s;
  789. return this;
  790. }
  791. determinant() {
  792. const te = this.elements;
  793. const a = te[0],
  794. b = te[1],
  795. c = te[2],
  796. d = te[3],
  797. e = te[4],
  798. f = te[5],
  799. g = te[6],
  800. h = te[7],
  801. i = te[8];
  802. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  803. }
  804. invert() {
  805. const te = this.elements,
  806. n11 = te[0],
  807. n21 = te[1],
  808. n31 = te[2],
  809. n12 = te[3],
  810. n22 = te[4],
  811. n32 = te[5],
  812. n13 = te[6],
  813. n23 = te[7],
  814. n33 = te[8],
  815. t11 = n33 * n22 - n32 * n23,
  816. t12 = n32 * n13 - n33 * n12,
  817. t13 = n23 * n12 - n22 * n13,
  818. det = n11 * t11 + n21 * t12 + n31 * t13;
  819. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  820. const detInv = 1 / det;
  821. te[0] = t11 * detInv;
  822. te[1] = (n31 * n23 - n33 * n21) * detInv;
  823. te[2] = (n32 * n21 - n31 * n22) * detInv;
  824. te[3] = t12 * detInv;
  825. te[4] = (n33 * n11 - n31 * n13) * detInv;
  826. te[5] = (n31 * n12 - n32 * n11) * detInv;
  827. te[6] = t13 * detInv;
  828. te[7] = (n21 * n13 - n23 * n11) * detInv;
  829. te[8] = (n22 * n11 - n21 * n12) * detInv;
  830. return this;
  831. }
  832. transpose() {
  833. let tmp;
  834. const m = this.elements;
  835. tmp = m[1];
  836. m[1] = m[3];
  837. m[3] = tmp;
  838. tmp = m[2];
  839. m[2] = m[6];
  840. m[6] = tmp;
  841. tmp = m[5];
  842. m[5] = m[7];
  843. m[7] = tmp;
  844. return this;
  845. }
  846. getNormalMatrix(matrix4) {
  847. return this.setFromMatrix4(matrix4).invert().transpose();
  848. }
  849. transposeIntoArray(r) {
  850. const m = this.elements;
  851. r[0] = m[0];
  852. r[1] = m[3];
  853. r[2] = m[6];
  854. r[3] = m[1];
  855. r[4] = m[4];
  856. r[5] = m[7];
  857. r[6] = m[2];
  858. r[7] = m[5];
  859. r[8] = m[8];
  860. return this;
  861. }
  862. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  863. const c = Math.cos(rotation);
  864. const s = Math.sin(rotation);
  865. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  866. return this;
  867. }
  868. //
  869. scale(sx, sy) {
  870. this.premultiply(_m3.makeScale(sx, sy));
  871. return this;
  872. }
  873. rotate(theta) {
  874. this.premultiply(_m3.makeRotation(-theta));
  875. return this;
  876. }
  877. translate(tx, ty) {
  878. this.premultiply(_m3.makeTranslation(tx, ty));
  879. return this;
  880. }
  881. // for 2D Transforms
  882. makeTranslation(x, y) {
  883. this.set(1, 0, x, 0, 1, y, 0, 0, 1);
  884. return this;
  885. }
  886. makeRotation(theta) {
  887. // counterclockwise
  888. const c = Math.cos(theta);
  889. const s = Math.sin(theta);
  890. this.set(c, -s, 0, s, c, 0, 0, 0, 1);
  891. return this;
  892. }
  893. makeScale(x, y) {
  894. this.set(x, 0, 0, 0, y, 0, 0, 0, 1);
  895. return this;
  896. }
  897. //
  898. equals(matrix) {
  899. const te = this.elements;
  900. const me = matrix.elements;
  901. for (let i = 0; i < 9; i++) {
  902. if (te[i] !== me[i]) return false;
  903. }
  904. return true;
  905. }
  906. fromArray(array, offset = 0) {
  907. for (let i = 0; i < 9; i++) {
  908. this.elements[i] = array[i + offset];
  909. }
  910. return this;
  911. }
  912. toArray(array = [], offset = 0) {
  913. const te = this.elements;
  914. array[offset] = te[0];
  915. array[offset + 1] = te[1];
  916. array[offset + 2] = te[2];
  917. array[offset + 3] = te[3];
  918. array[offset + 4] = te[4];
  919. array[offset + 5] = te[5];
  920. array[offset + 6] = te[6];
  921. array[offset + 7] = te[7];
  922. array[offset + 8] = te[8];
  923. return array;
  924. }
  925. clone() {
  926. return new this.constructor().fromArray(this.elements);
  927. }
  928. }
  929. const _m3 = /*@__PURE__*/new Matrix3();
  930. function arrayNeedsUint32(array) {
  931. // assumes larger values usually on last
  932. for (let i = array.length - 1; i >= 0; --i) {
  933. if (array[i] >= 65535) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  934. }
  935. return false;
  936. }
  937. const TYPED_ARRAYS = {
  938. Int8Array: Int8Array,
  939. Uint8Array: Uint8Array,
  940. Uint8ClampedArray: Uint8ClampedArray,
  941. Int16Array: Int16Array,
  942. Uint16Array: Uint16Array,
  943. Int32Array: Int32Array,
  944. Uint32Array: Uint32Array,
  945. Float32Array: Float32Array,
  946. Float64Array: Float64Array
  947. };
  948. function getTypedArray(type, buffer) {
  949. return new TYPED_ARRAYS[type](buffer);
  950. }
  951. function createElementNS(name) {
  952. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  953. }
  954. function SRGBToLinear(c) {
  955. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  956. }
  957. function LinearToSRGB(c) {
  958. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  959. }
  960. // JavaScript RGB-to-RGB transforms, defined as
  961. // FN[InputColorSpace][OutputColorSpace] callback functions.
  962. const FN = {
  963. [SRGBColorSpace]: {
  964. [LinearSRGBColorSpace]: SRGBToLinear
  965. },
  966. [LinearSRGBColorSpace]: {
  967. [SRGBColorSpace]: LinearToSRGB
  968. }
  969. };
  970. const ColorManagement = {
  971. legacyMode: true,
  972. get workingColorSpace() {
  973. return LinearSRGBColorSpace;
  974. },
  975. set workingColorSpace(colorSpace) {
  976. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  977. },
  978. convert: function (color, sourceColorSpace, targetColorSpace) {
  979. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  980. return color;
  981. }
  982. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  983. const fn = FN[sourceColorSpace][targetColorSpace];
  984. color.r = fn(color.r);
  985. color.g = fn(color.g);
  986. color.b = fn(color.b);
  987. return color;
  988. }
  989. throw new Error('Unsupported color space conversion.');
  990. },
  991. fromWorkingColorSpace: function (color, targetColorSpace) {
  992. return this.convert(color, this.workingColorSpace, targetColorSpace);
  993. },
  994. toWorkingColorSpace: function (color, sourceColorSpace) {
  995. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  996. }
  997. };
  998. const _colorKeywords = {
  999. 'aliceblue': 0xF0F8FF,
  1000. 'antiquewhite': 0xFAEBD7,
  1001. 'aqua': 0x00FFFF,
  1002. 'aquamarine': 0x7FFFD4,
  1003. 'azure': 0xF0FFFF,
  1004. 'beige': 0xF5F5DC,
  1005. 'bisque': 0xFFE4C4,
  1006. 'black': 0x000000,
  1007. 'blanchedalmond': 0xFFEBCD,
  1008. 'blue': 0x0000FF,
  1009. 'blueviolet': 0x8A2BE2,
  1010. 'brown': 0xA52A2A,
  1011. 'burlywood': 0xDEB887,
  1012. 'cadetblue': 0x5F9EA0,
  1013. 'chartreuse': 0x7FFF00,
  1014. 'chocolate': 0xD2691E,
  1015. 'coral': 0xFF7F50,
  1016. 'cornflowerblue': 0x6495ED,
  1017. 'cornsilk': 0xFFF8DC,
  1018. 'crimson': 0xDC143C,
  1019. 'cyan': 0x00FFFF,
  1020. 'darkblue': 0x00008B,
  1021. 'darkcyan': 0x008B8B,
  1022. 'darkgoldenrod': 0xB8860B,
  1023. 'darkgray': 0xA9A9A9,
  1024. 'darkgreen': 0x006400,
  1025. 'darkgrey': 0xA9A9A9,
  1026. 'darkkhaki': 0xBDB76B,
  1027. 'darkmagenta': 0x8B008B,
  1028. 'darkolivegreen': 0x556B2F,
  1029. 'darkorange': 0xFF8C00,
  1030. 'darkorchid': 0x9932CC,
  1031. 'darkred': 0x8B0000,
  1032. 'darksalmon': 0xE9967A,
  1033. 'darkseagreen': 0x8FBC8F,
  1034. 'darkslateblue': 0x483D8B,
  1035. 'darkslategray': 0x2F4F4F,
  1036. 'darkslategrey': 0x2F4F4F,
  1037. 'darkturquoise': 0x00CED1,
  1038. 'darkviolet': 0x9400D3,
  1039. 'deeppink': 0xFF1493,
  1040. 'deepskyblue': 0x00BFFF,
  1041. 'dimgray': 0x696969,
  1042. 'dimgrey': 0x696969,
  1043. 'dodgerblue': 0x1E90FF,
  1044. 'firebrick': 0xB22222,
  1045. 'floralwhite': 0xFFFAF0,
  1046. 'forestgreen': 0x228B22,
  1047. 'fuchsia': 0xFF00FF,
  1048. 'gainsboro': 0xDCDCDC,
  1049. 'ghostwhite': 0xF8F8FF,
  1050. 'gold': 0xFFD700,
  1051. 'goldenrod': 0xDAA520,
  1052. 'gray': 0x808080,
  1053. 'green': 0x008000,
  1054. 'greenyellow': 0xADFF2F,
  1055. 'grey': 0x808080,
  1056. 'honeydew': 0xF0FFF0,
  1057. 'hotpink': 0xFF69B4,
  1058. 'indianred': 0xCD5C5C,
  1059. 'indigo': 0x4B0082,
  1060. 'ivory': 0xFFFFF0,
  1061. 'khaki': 0xF0E68C,
  1062. 'lavender': 0xE6E6FA,
  1063. 'lavenderblush': 0xFFF0F5,
  1064. 'lawngreen': 0x7CFC00,
  1065. 'lemonchiffon': 0xFFFACD,
  1066. 'lightblue': 0xADD8E6,
  1067. 'lightcoral': 0xF08080,
  1068. 'lightcyan': 0xE0FFFF,
  1069. 'lightgoldenrodyellow': 0xFAFAD2,
  1070. 'lightgray': 0xD3D3D3,
  1071. 'lightgreen': 0x90EE90,
  1072. 'lightgrey': 0xD3D3D3,
  1073. 'lightpink': 0xFFB6C1,
  1074. 'lightsalmon': 0xFFA07A,
  1075. 'lightseagreen': 0x20B2AA,
  1076. 'lightskyblue': 0x87CEFA,
  1077. 'lightslategray': 0x778899,
  1078. 'lightslategrey': 0x778899,
  1079. 'lightsteelblue': 0xB0C4DE,
  1080. 'lightyellow': 0xFFFFE0,
  1081. 'lime': 0x00FF00,
  1082. 'limegreen': 0x32CD32,
  1083. 'linen': 0xFAF0E6,
  1084. 'magenta': 0xFF00FF,
  1085. 'maroon': 0x800000,
  1086. 'mediumaquamarine': 0x66CDAA,
  1087. 'mediumblue': 0x0000CD,
  1088. 'mediumorchid': 0xBA55D3,
  1089. 'mediumpurple': 0x9370DB,
  1090. 'mediumseagreen': 0x3CB371,
  1091. 'mediumslateblue': 0x7B68EE,
  1092. 'mediumspringgreen': 0x00FA9A,
  1093. 'mediumturquoise': 0x48D1CC,
  1094. 'mediumvioletred': 0xC71585,
  1095. 'midnightblue': 0x191970,
  1096. 'mintcream': 0xF5FFFA,
  1097. 'mistyrose': 0xFFE4E1,
  1098. 'moccasin': 0xFFE4B5,
  1099. 'navajowhite': 0xFFDEAD,
  1100. 'navy': 0x000080,
  1101. 'oldlace': 0xFDF5E6,
  1102. 'olive': 0x808000,
  1103. 'olivedrab': 0x6B8E23,
  1104. 'orange': 0xFFA500,
  1105. 'orangered': 0xFF4500,
  1106. 'orchid': 0xDA70D6,
  1107. 'palegoldenrod': 0xEEE8AA,
  1108. 'palegreen': 0x98FB98,
  1109. 'paleturquoise': 0xAFEEEE,
  1110. 'palevioletred': 0xDB7093,
  1111. 'papayawhip': 0xFFEFD5,
  1112. 'peachpuff': 0xFFDAB9,
  1113. 'peru': 0xCD853F,
  1114. 'pink': 0xFFC0CB,
  1115. 'plum': 0xDDA0DD,
  1116. 'powderblue': 0xB0E0E6,
  1117. 'purple': 0x800080,
  1118. 'rebeccapurple': 0x663399,
  1119. 'red': 0xFF0000,
  1120. 'rosybrown': 0xBC8F8F,
  1121. 'royalblue': 0x4169E1,
  1122. 'saddlebrown': 0x8B4513,
  1123. 'salmon': 0xFA8072,
  1124. 'sandybrown': 0xF4A460,
  1125. 'seagreen': 0x2E8B57,
  1126. 'seashell': 0xFFF5EE,
  1127. 'sienna': 0xA0522D,
  1128. 'silver': 0xC0C0C0,
  1129. 'skyblue': 0x87CEEB,
  1130. 'slateblue': 0x6A5ACD,
  1131. 'slategray': 0x708090,
  1132. 'slategrey': 0x708090,
  1133. 'snow': 0xFFFAFA,
  1134. 'springgreen': 0x00FF7F,
  1135. 'steelblue': 0x4682B4,
  1136. 'tan': 0xD2B48C,
  1137. 'teal': 0x008080,
  1138. 'thistle': 0xD8BFD8,
  1139. 'tomato': 0xFF6347,
  1140. 'turquoise': 0x40E0D0,
  1141. 'violet': 0xEE82EE,
  1142. 'wheat': 0xF5DEB3,
  1143. 'white': 0xFFFFFF,
  1144. 'whitesmoke': 0xF5F5F5,
  1145. 'yellow': 0xFFFF00,
  1146. 'yellowgreen': 0x9ACD32
  1147. };
  1148. const _rgb$1 = {
  1149. r: 0,
  1150. g: 0,
  1151. b: 0
  1152. };
  1153. const _hslA = {
  1154. h: 0,
  1155. s: 0,
  1156. l: 0
  1157. };
  1158. const _hslB = {
  1159. h: 0,
  1160. s: 0,
  1161. l: 0
  1162. };
  1163. function hue2rgb(p, q, t) {
  1164. if (t < 0) t += 1;
  1165. if (t > 1) t -= 1;
  1166. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1167. if (t < 1 / 2) return q;
  1168. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1169. return p;
  1170. }
  1171. function toComponents(source, target) {
  1172. target.r = source.r;
  1173. target.g = source.g;
  1174. target.b = source.b;
  1175. return target;
  1176. }
  1177. class Color {
  1178. constructor(r, g, b) {
  1179. this.isColor = true;
  1180. this.r = 1;
  1181. this.g = 1;
  1182. this.b = 1;
  1183. if (g === undefined && b === undefined) {
  1184. // r is THREE.Color, hex or string
  1185. return this.set(r);
  1186. }
  1187. return this.setRGB(r, g, b);
  1188. }
  1189. set(value) {
  1190. if (value && value.isColor) {
  1191. this.copy(value);
  1192. } else if (typeof value === 'number') {
  1193. this.setHex(value);
  1194. } else if (typeof value === 'string') {
  1195. this.setStyle(value);
  1196. }
  1197. return this;
  1198. }
  1199. setScalar(scalar) {
  1200. this.r = scalar;
  1201. this.g = scalar;
  1202. this.b = scalar;
  1203. return this;
  1204. }
  1205. setHex(hex, colorSpace = SRGBColorSpace) {
  1206. hex = Math.floor(hex);
  1207. this.r = (hex >> 16 & 255) / 255;
  1208. this.g = (hex >> 8 & 255) / 255;
  1209. this.b = (hex & 255) / 255;
  1210. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1211. return this;
  1212. }
  1213. setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) {
  1214. this.r = r;
  1215. this.g = g;
  1216. this.b = b;
  1217. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1218. return this;
  1219. }
  1220. setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) {
  1221. // h,s,l ranges are in 0.0 - 1.0
  1222. h = euclideanModulo(h, 1);
  1223. s = clamp(s, 0, 1);
  1224. l = clamp(l, 0, 1);
  1225. if (s === 0) {
  1226. this.r = this.g = this.b = l;
  1227. } else {
  1228. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1229. const q = 2 * l - p;
  1230. this.r = hue2rgb(q, p, h + 1 / 3);
  1231. this.g = hue2rgb(q, p, h);
  1232. this.b = hue2rgb(q, p, h - 1 / 3);
  1233. }
  1234. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1235. return this;
  1236. }
  1237. setStyle(style, colorSpace = SRGBColorSpace) {
  1238. function handleAlpha(string) {
  1239. if (string === undefined) return;
  1240. if (parseFloat(string) < 1) {
  1241. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1242. }
  1243. }
  1244. let m;
  1245. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1246. // rgb / hsl
  1247. let color;
  1248. const name = m[1];
  1249. const components = m[2];
  1250. switch (name) {
  1251. case 'rgb':
  1252. case 'rgba':
  1253. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1254. // rgb(255,0,0) rgba(255,0,0,0.5)
  1255. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1256. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1257. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1258. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1259. handleAlpha(color[4]);
  1260. return this;
  1261. }
  1262. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1263. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1264. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1265. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1266. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1267. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1268. handleAlpha(color[4]);
  1269. return this;
  1270. }
  1271. break;
  1272. case 'hsl':
  1273. case 'hsla':
  1274. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1275. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1276. const h = parseFloat(color[1]) / 360;
  1277. const s = parseFloat(color[2]) / 100;
  1278. const l = parseFloat(color[3]) / 100;
  1279. handleAlpha(color[4]);
  1280. return this.setHSL(h, s, l, colorSpace);
  1281. }
  1282. break;
  1283. }
  1284. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1285. // hex color
  1286. const hex = m[1];
  1287. const size = hex.length;
  1288. if (size === 3) {
  1289. // #ff0
  1290. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1291. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1292. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1293. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1294. return this;
  1295. } else if (size === 6) {
  1296. // #ff0000
  1297. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1298. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1299. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1300. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1301. return this;
  1302. }
  1303. }
  1304. if (style && style.length > 0) {
  1305. return this.setColorName(style, colorSpace);
  1306. }
  1307. return this;
  1308. }
  1309. setColorName(style, colorSpace = SRGBColorSpace) {
  1310. // color keywords
  1311. const hex = _colorKeywords[style.toLowerCase()];
  1312. if (hex !== undefined) {
  1313. // red
  1314. this.setHex(hex, colorSpace);
  1315. } else {
  1316. // unknown color
  1317. console.warn('THREE.Color: Unknown color ' + style);
  1318. }
  1319. return this;
  1320. }
  1321. clone() {
  1322. return new this.constructor(this.r, this.g, this.b);
  1323. }
  1324. copy(color) {
  1325. this.r = color.r;
  1326. this.g = color.g;
  1327. this.b = color.b;
  1328. return this;
  1329. }
  1330. copySRGBToLinear(color) {
  1331. this.r = SRGBToLinear(color.r);
  1332. this.g = SRGBToLinear(color.g);
  1333. this.b = SRGBToLinear(color.b);
  1334. return this;
  1335. }
  1336. copyLinearToSRGB(color) {
  1337. this.r = LinearToSRGB(color.r);
  1338. this.g = LinearToSRGB(color.g);
  1339. this.b = LinearToSRGB(color.b);
  1340. return this;
  1341. }
  1342. convertSRGBToLinear() {
  1343. this.copySRGBToLinear(this);
  1344. return this;
  1345. }
  1346. convertLinearToSRGB() {
  1347. this.copyLinearToSRGB(this);
  1348. return this;
  1349. }
  1350. getHex(colorSpace = SRGBColorSpace) {
  1351. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1352. return clamp(_rgb$1.r * 255, 0, 255) << 16 ^ clamp(_rgb$1.g * 255, 0, 255) << 8 ^ clamp(_rgb$1.b * 255, 0, 255) << 0;
  1353. }
  1354. getHexString(colorSpace = SRGBColorSpace) {
  1355. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1356. }
  1357. getHSL(target, colorSpace = ColorManagement.workingColorSpace) {
  1358. // h,s,l ranges are in 0.0 - 1.0
  1359. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1360. const r = _rgb$1.r,
  1361. g = _rgb$1.g,
  1362. b = _rgb$1.b;
  1363. const max = Math.max(r, g, b);
  1364. const min = Math.min(r, g, b);
  1365. let hue, saturation;
  1366. const lightness = (min + max) / 2.0;
  1367. if (min === max) {
  1368. hue = 0;
  1369. saturation = 0;
  1370. } else {
  1371. const delta = max - min;
  1372. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1373. switch (max) {
  1374. case r:
  1375. hue = (g - b) / delta + (g < b ? 6 : 0);
  1376. break;
  1377. case g:
  1378. hue = (b - r) / delta + 2;
  1379. break;
  1380. case b:
  1381. hue = (r - g) / delta + 4;
  1382. break;
  1383. }
  1384. hue /= 6;
  1385. }
  1386. target.h = hue;
  1387. target.s = saturation;
  1388. target.l = lightness;
  1389. return target;
  1390. }
  1391. getRGB(target, colorSpace = ColorManagement.workingColorSpace) {
  1392. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1393. target.r = _rgb$1.r;
  1394. target.g = _rgb$1.g;
  1395. target.b = _rgb$1.b;
  1396. return target;
  1397. }
  1398. getStyle(colorSpace = SRGBColorSpace) {
  1399. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1400. if (colorSpace !== SRGBColorSpace) {
  1401. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1402. return `color(${colorSpace} ${_rgb$1.r} ${_rgb$1.g} ${_rgb$1.b})`;
  1403. }
  1404. return `rgb(${_rgb$1.r * 255 | 0},${_rgb$1.g * 255 | 0},${_rgb$1.b * 255 | 0})`;
  1405. }
  1406. offsetHSL(h, s, l) {
  1407. this.getHSL(_hslA);
  1408. _hslA.h += h;
  1409. _hslA.s += s;
  1410. _hslA.l += l;
  1411. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1412. return this;
  1413. }
  1414. add(color) {
  1415. this.r += color.r;
  1416. this.g += color.g;
  1417. this.b += color.b;
  1418. return this;
  1419. }
  1420. addColors(color1, color2) {
  1421. this.r = color1.r + color2.r;
  1422. this.g = color1.g + color2.g;
  1423. this.b = color1.b + color2.b;
  1424. return this;
  1425. }
  1426. addScalar(s) {
  1427. this.r += s;
  1428. this.g += s;
  1429. this.b += s;
  1430. return this;
  1431. }
  1432. sub(color) {
  1433. this.r = Math.max(0, this.r - color.r);
  1434. this.g = Math.max(0, this.g - color.g);
  1435. this.b = Math.max(0, this.b - color.b);
  1436. return this;
  1437. }
  1438. multiply(color) {
  1439. this.r *= color.r;
  1440. this.g *= color.g;
  1441. this.b *= color.b;
  1442. return this;
  1443. }
  1444. multiplyScalar(s) {
  1445. this.r *= s;
  1446. this.g *= s;
  1447. this.b *= s;
  1448. return this;
  1449. }
  1450. lerp(color, alpha) {
  1451. this.r += (color.r - this.r) * alpha;
  1452. this.g += (color.g - this.g) * alpha;
  1453. this.b += (color.b - this.b) * alpha;
  1454. return this;
  1455. }
  1456. lerpColors(color1, color2, alpha) {
  1457. this.r = color1.r + (color2.r - color1.r) * alpha;
  1458. this.g = color1.g + (color2.g - color1.g) * alpha;
  1459. this.b = color1.b + (color2.b - color1.b) * alpha;
  1460. return this;
  1461. }
  1462. lerpHSL(color, alpha) {
  1463. this.getHSL(_hslA);
  1464. color.getHSL(_hslB);
  1465. const h = lerp(_hslA.h, _hslB.h, alpha);
  1466. const s = lerp(_hslA.s, _hslB.s, alpha);
  1467. const l = lerp(_hslA.l, _hslB.l, alpha);
  1468. this.setHSL(h, s, l);
  1469. return this;
  1470. }
  1471. equals(c) {
  1472. return c.r === this.r && c.g === this.g && c.b === this.b;
  1473. }
  1474. fromArray(array, offset = 0) {
  1475. this.r = array[offset];
  1476. this.g = array[offset + 1];
  1477. this.b = array[offset + 2];
  1478. return this;
  1479. }
  1480. toArray(array = [], offset = 0) {
  1481. array[offset] = this.r;
  1482. array[offset + 1] = this.g;
  1483. array[offset + 2] = this.b;
  1484. return array;
  1485. }
  1486. fromBufferAttribute(attribute, index) {
  1487. this.r = attribute.getX(index);
  1488. this.g = attribute.getY(index);
  1489. this.b = attribute.getZ(index);
  1490. return this;
  1491. }
  1492. toJSON() {
  1493. return this.getHex();
  1494. }
  1495. *[Symbol.iterator]() {
  1496. yield this.r;
  1497. yield this.g;
  1498. yield this.b;
  1499. }
  1500. }
  1501. Color.NAMES = _colorKeywords;
  1502. let _canvas;
  1503. class ImageUtils {
  1504. static getDataURL(image) {
  1505. if (/^data:/i.test(image.src)) {
  1506. return image.src;
  1507. }
  1508. if (typeof HTMLCanvasElement == 'undefined') {
  1509. return image.src;
  1510. }
  1511. let canvas;
  1512. if (image instanceof HTMLCanvasElement) {
  1513. canvas = image;
  1514. } else {
  1515. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1516. _canvas.width = image.width;
  1517. _canvas.height = image.height;
  1518. const context = _canvas.getContext('2d');
  1519. if (image instanceof ImageData) {
  1520. context.putImageData(image, 0, 0);
  1521. } else {
  1522. context.drawImage(image, 0, 0, image.width, image.height);
  1523. }
  1524. canvas = _canvas;
  1525. }
  1526. if (canvas.width > 2048 || canvas.height > 2048) {
  1527. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1528. return canvas.toDataURL('image/jpeg', 0.6);
  1529. } else {
  1530. return canvas.toDataURL('image/png');
  1531. }
  1532. }
  1533. static sRGBToLinear(image) {
  1534. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1535. const canvas = createElementNS('canvas');
  1536. canvas.width = image.width;
  1537. canvas.height = image.height;
  1538. const context = canvas.getContext('2d');
  1539. context.drawImage(image, 0, 0, image.width, image.height);
  1540. const imageData = context.getImageData(0, 0, image.width, image.height);
  1541. const data = imageData.data;
  1542. for (let i = 0; i < data.length; i++) {
  1543. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1544. }
  1545. context.putImageData(imageData, 0, 0);
  1546. return canvas;
  1547. } else if (image.data) {
  1548. const data = image.data.slice(0);
  1549. for (let i = 0; i < data.length; i++) {
  1550. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1551. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1552. } else {
  1553. // assuming float
  1554. data[i] = SRGBToLinear(data[i]);
  1555. }
  1556. }
  1557. return {
  1558. data: data,
  1559. width: image.width,
  1560. height: image.height
  1561. };
  1562. } else {
  1563. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1564. return image;
  1565. }
  1566. }
  1567. }
  1568. class Source {
  1569. constructor(data = null) {
  1570. this.isSource = true;
  1571. this.uuid = generateUUID();
  1572. this.data = data;
  1573. this.version = 0;
  1574. }
  1575. set needsUpdate(value) {
  1576. if (value === true) this.version++;
  1577. }
  1578. toJSON(meta) {
  1579. const isRootObject = meta === undefined || typeof meta === 'string';
  1580. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1581. return meta.images[this.uuid];
  1582. }
  1583. const output = {
  1584. uuid: this.uuid,
  1585. url: ''
  1586. };
  1587. const data = this.data;
  1588. if (data !== null) {
  1589. let url;
  1590. if (Array.isArray(data)) {
  1591. // cube texture
  1592. url = [];
  1593. for (let i = 0, l = data.length; i < l; i++) {
  1594. if (data[i].isDataTexture) {
  1595. url.push(serializeImage(data[i].image));
  1596. } else {
  1597. url.push(serializeImage(data[i]));
  1598. }
  1599. }
  1600. } else {
  1601. // texture
  1602. url = serializeImage(data);
  1603. }
  1604. output.url = url;
  1605. }
  1606. if (!isRootObject) {
  1607. meta.images[this.uuid] = output;
  1608. }
  1609. return output;
  1610. }
  1611. }
  1612. function serializeImage(image) {
  1613. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1614. // default images
  1615. return ImageUtils.getDataURL(image);
  1616. } else {
  1617. if (image.data) {
  1618. // images of DataTexture
  1619. return {
  1620. data: Array.from(image.data),
  1621. width: image.width,
  1622. height: image.height,
  1623. type: image.data.constructor.name
  1624. };
  1625. } else {
  1626. console.warn('THREE.Texture: Unable to serialize Texture.');
  1627. return {};
  1628. }
  1629. }
  1630. }
  1631. let textureId = 0;
  1632. class Texture extends EventDispatcher {
  1633. 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, encoding = LinearEncoding) {
  1634. super();
  1635. this.isTexture = true;
  1636. Object.defineProperty(this, 'id', {
  1637. value: textureId++
  1638. });
  1639. this.uuid = generateUUID();
  1640. this.name = '';
  1641. this.source = new Source(image);
  1642. this.mipmaps = [];
  1643. this.mapping = mapping;
  1644. this.wrapS = wrapS;
  1645. this.wrapT = wrapT;
  1646. this.magFilter = magFilter;
  1647. this.minFilter = minFilter;
  1648. this.anisotropy = anisotropy;
  1649. this.format = format;
  1650. this.internalFormat = null;
  1651. this.type = type;
  1652. this.offset = new Vector2(0, 0);
  1653. this.repeat = new Vector2(1, 1);
  1654. this.center = new Vector2(0, 0);
  1655. this.rotation = 0;
  1656. this.matrixAutoUpdate = true;
  1657. this.matrix = new Matrix3();
  1658. this.generateMipmaps = true;
  1659. this.premultiplyAlpha = false;
  1660. this.flipY = true;
  1661. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1662. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1663. //
  1664. // Also changing the encoding after already used by a Material will not automatically make the Material
  1665. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1666. this.encoding = encoding;
  1667. this.userData = {};
  1668. this.version = 0;
  1669. this.onUpdate = null;
  1670. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1671. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1672. }
  1673. get image() {
  1674. return this.source.data;
  1675. }
  1676. set image(value) {
  1677. this.source.data = value;
  1678. }
  1679. updateMatrix() {
  1680. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1681. }
  1682. clone() {
  1683. return new this.constructor().copy(this);
  1684. }
  1685. copy(source) {
  1686. this.name = source.name;
  1687. this.source = source.source;
  1688. this.mipmaps = source.mipmaps.slice(0);
  1689. this.mapping = source.mapping;
  1690. this.wrapS = source.wrapS;
  1691. this.wrapT = source.wrapT;
  1692. this.magFilter = source.magFilter;
  1693. this.minFilter = source.minFilter;
  1694. this.anisotropy = source.anisotropy;
  1695. this.format = source.format;
  1696. this.internalFormat = source.internalFormat;
  1697. this.type = source.type;
  1698. this.offset.copy(source.offset);
  1699. this.repeat.copy(source.repeat);
  1700. this.center.copy(source.center);
  1701. this.rotation = source.rotation;
  1702. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1703. this.matrix.copy(source.matrix);
  1704. this.generateMipmaps = source.generateMipmaps;
  1705. this.premultiplyAlpha = source.premultiplyAlpha;
  1706. this.flipY = source.flipY;
  1707. this.unpackAlignment = source.unpackAlignment;
  1708. this.encoding = source.encoding;
  1709. this.userData = JSON.parse(JSON.stringify(source.userData));
  1710. this.needsUpdate = true;
  1711. return this;
  1712. }
  1713. toJSON(meta) {
  1714. const isRootObject = meta === undefined || typeof meta === 'string';
  1715. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1716. return meta.textures[this.uuid];
  1717. }
  1718. const output = {
  1719. metadata: {
  1720. version: 4.5,
  1721. type: 'Texture',
  1722. generator: 'Texture.toJSON'
  1723. },
  1724. uuid: this.uuid,
  1725. name: this.name,
  1726. image: this.source.toJSON(meta).uuid,
  1727. mapping: this.mapping,
  1728. repeat: [this.repeat.x, this.repeat.y],
  1729. offset: [this.offset.x, this.offset.y],
  1730. center: [this.center.x, this.center.y],
  1731. rotation: this.rotation,
  1732. wrap: [this.wrapS, this.wrapT],
  1733. format: this.format,
  1734. type: this.type,
  1735. encoding: this.encoding,
  1736. minFilter: this.minFilter,
  1737. magFilter: this.magFilter,
  1738. anisotropy: this.anisotropy,
  1739. flipY: this.flipY,
  1740. premultiplyAlpha: this.premultiplyAlpha,
  1741. unpackAlignment: this.unpackAlignment
  1742. };
  1743. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1744. if (!isRootObject) {
  1745. meta.textures[this.uuid] = output;
  1746. }
  1747. return output;
  1748. }
  1749. dispose() {
  1750. this.dispatchEvent({
  1751. type: 'dispose'
  1752. });
  1753. }
  1754. transformUv(uv) {
  1755. if (this.mapping !== UVMapping) return uv;
  1756. uv.applyMatrix3(this.matrix);
  1757. if (uv.x < 0 || uv.x > 1) {
  1758. switch (this.wrapS) {
  1759. case RepeatWrapping:
  1760. uv.x = uv.x - Math.floor(uv.x);
  1761. break;
  1762. case ClampToEdgeWrapping:
  1763. uv.x = uv.x < 0 ? 0 : 1;
  1764. break;
  1765. case MirroredRepeatWrapping:
  1766. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1767. uv.x = Math.ceil(uv.x) - uv.x;
  1768. } else {
  1769. uv.x = uv.x - Math.floor(uv.x);
  1770. }
  1771. break;
  1772. }
  1773. }
  1774. if (uv.y < 0 || uv.y > 1) {
  1775. switch (this.wrapT) {
  1776. case RepeatWrapping:
  1777. uv.y = uv.y - Math.floor(uv.y);
  1778. break;
  1779. case ClampToEdgeWrapping:
  1780. uv.y = uv.y < 0 ? 0 : 1;
  1781. break;
  1782. case MirroredRepeatWrapping:
  1783. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1784. uv.y = Math.ceil(uv.y) - uv.y;
  1785. } else {
  1786. uv.y = uv.y - Math.floor(uv.y);
  1787. }
  1788. break;
  1789. }
  1790. }
  1791. if (this.flipY) {
  1792. uv.y = 1 - uv.y;
  1793. }
  1794. return uv;
  1795. }
  1796. set needsUpdate(value) {
  1797. if (value === true) {
  1798. this.version++;
  1799. this.source.needsUpdate = true;
  1800. }
  1801. }
  1802. }
  1803. Texture.DEFAULT_IMAGE = null;
  1804. Texture.DEFAULT_MAPPING = UVMapping;
  1805. Texture.DEFAULT_ANISOTROPY = 1;
  1806. class Vector4 {
  1807. constructor(x = 0, y = 0, z = 0, w = 1) {
  1808. Vector4.prototype.isVector4 = true;
  1809. this.x = x;
  1810. this.y = y;
  1811. this.z = z;
  1812. this.w = w;
  1813. }
  1814. get width() {
  1815. return this.z;
  1816. }
  1817. set width(value) {
  1818. this.z = value;
  1819. }
  1820. get height() {
  1821. return this.w;
  1822. }
  1823. set height(value) {
  1824. this.w = value;
  1825. }
  1826. set(x, y, z, w) {
  1827. this.x = x;
  1828. this.y = y;
  1829. this.z = z;
  1830. this.w = w;
  1831. return this;
  1832. }
  1833. setScalar(scalar) {
  1834. this.x = scalar;
  1835. this.y = scalar;
  1836. this.z = scalar;
  1837. this.w = scalar;
  1838. return this;
  1839. }
  1840. setX(x) {
  1841. this.x = x;
  1842. return this;
  1843. }
  1844. setY(y) {
  1845. this.y = y;
  1846. return this;
  1847. }
  1848. setZ(z) {
  1849. this.z = z;
  1850. return this;
  1851. }
  1852. setW(w) {
  1853. this.w = w;
  1854. return this;
  1855. }
  1856. setComponent(index, value) {
  1857. switch (index) {
  1858. case 0:
  1859. this.x = value;
  1860. break;
  1861. case 1:
  1862. this.y = value;
  1863. break;
  1864. case 2:
  1865. this.z = value;
  1866. break;
  1867. case 3:
  1868. this.w = value;
  1869. break;
  1870. default:
  1871. throw new Error('index is out of range: ' + index);
  1872. }
  1873. return this;
  1874. }
  1875. getComponent(index) {
  1876. switch (index) {
  1877. case 0:
  1878. return this.x;
  1879. case 1:
  1880. return this.y;
  1881. case 2:
  1882. return this.z;
  1883. case 3:
  1884. return this.w;
  1885. default:
  1886. throw new Error('index is out of range: ' + index);
  1887. }
  1888. }
  1889. clone() {
  1890. return new this.constructor(this.x, this.y, this.z, this.w);
  1891. }
  1892. copy(v) {
  1893. this.x = v.x;
  1894. this.y = v.y;
  1895. this.z = v.z;
  1896. this.w = v.w !== undefined ? v.w : 1;
  1897. return this;
  1898. }
  1899. add(v) {
  1900. this.x += v.x;
  1901. this.y += v.y;
  1902. this.z += v.z;
  1903. this.w += v.w;
  1904. return this;
  1905. }
  1906. addScalar(s) {
  1907. this.x += s;
  1908. this.y += s;
  1909. this.z += s;
  1910. this.w += s;
  1911. return this;
  1912. }
  1913. addVectors(a, b) {
  1914. this.x = a.x + b.x;
  1915. this.y = a.y + b.y;
  1916. this.z = a.z + b.z;
  1917. this.w = a.w + b.w;
  1918. return this;
  1919. }
  1920. addScaledVector(v, s) {
  1921. this.x += v.x * s;
  1922. this.y += v.y * s;
  1923. this.z += v.z * s;
  1924. this.w += v.w * s;
  1925. return this;
  1926. }
  1927. sub(v) {
  1928. this.x -= v.x;
  1929. this.y -= v.y;
  1930. this.z -= v.z;
  1931. this.w -= v.w;
  1932. return this;
  1933. }
  1934. subScalar(s) {
  1935. this.x -= s;
  1936. this.y -= s;
  1937. this.z -= s;
  1938. this.w -= s;
  1939. return this;
  1940. }
  1941. subVectors(a, b) {
  1942. this.x = a.x - b.x;
  1943. this.y = a.y - b.y;
  1944. this.z = a.z - b.z;
  1945. this.w = a.w - b.w;
  1946. return this;
  1947. }
  1948. multiply(v) {
  1949. this.x *= v.x;
  1950. this.y *= v.y;
  1951. this.z *= v.z;
  1952. this.w *= v.w;
  1953. return this;
  1954. }
  1955. multiplyScalar(scalar) {
  1956. this.x *= scalar;
  1957. this.y *= scalar;
  1958. this.z *= scalar;
  1959. this.w *= scalar;
  1960. return this;
  1961. }
  1962. applyMatrix4(m) {
  1963. const x = this.x,
  1964. y = this.y,
  1965. z = this.z,
  1966. w = this.w;
  1967. const e = m.elements;
  1968. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1969. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1970. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1971. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1972. return this;
  1973. }
  1974. divideScalar(scalar) {
  1975. return this.multiplyScalar(1 / scalar);
  1976. }
  1977. setAxisAngleFromQuaternion(q) {
  1978. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1979. // q is assumed to be normalized
  1980. this.w = 2 * Math.acos(q.w);
  1981. const s = Math.sqrt(1 - q.w * q.w);
  1982. if (s < 0.0001) {
  1983. this.x = 1;
  1984. this.y = 0;
  1985. this.z = 0;
  1986. } else {
  1987. this.x = q.x / s;
  1988. this.y = q.y / s;
  1989. this.z = q.z / s;
  1990. }
  1991. return this;
  1992. }
  1993. setAxisAngleFromRotationMatrix(m) {
  1994. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1995. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1996. let angle, x, y, z; // variables for result
  1997. const epsilon = 0.01,
  1998. // margin to allow for rounding errors
  1999. epsilon2 = 0.1,
  2000. // margin to distinguish between 0 and 180 degrees
  2001. te = m.elements,
  2002. m11 = te[0],
  2003. m12 = te[4],
  2004. m13 = te[8],
  2005. m21 = te[1],
  2006. m22 = te[5],
  2007. m23 = te[9],
  2008. m31 = te[2],
  2009. m32 = te[6],
  2010. m33 = te[10];
  2011. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2012. // singularity found
  2013. // first check for identity matrix which must have +1 for all terms
  2014. // in leading diagonal and zero in other terms
  2015. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2016. // this singularity is identity matrix so angle = 0
  2017. this.set(1, 0, 0, 0);
  2018. return this; // zero angle, arbitrary axis
  2019. }
  2020. // otherwise this singularity is angle = 180
  2021. angle = Math.PI;
  2022. const xx = (m11 + 1) / 2;
  2023. const yy = (m22 + 1) / 2;
  2024. const zz = (m33 + 1) / 2;
  2025. const xy = (m12 + m21) / 4;
  2026. const xz = (m13 + m31) / 4;
  2027. const yz = (m23 + m32) / 4;
  2028. if (xx > yy && xx > zz) {
  2029. // m11 is the largest diagonal term
  2030. if (xx < epsilon) {
  2031. x = 0;
  2032. y = 0.707106781;
  2033. z = 0.707106781;
  2034. } else {
  2035. x = Math.sqrt(xx);
  2036. y = xy / x;
  2037. z = xz / x;
  2038. }
  2039. } else if (yy > zz) {
  2040. // m22 is the largest diagonal term
  2041. if (yy < epsilon) {
  2042. x = 0.707106781;
  2043. y = 0;
  2044. z = 0.707106781;
  2045. } else {
  2046. y = Math.sqrt(yy);
  2047. x = xy / y;
  2048. z = yz / y;
  2049. }
  2050. } else {
  2051. // m33 is the largest diagonal term so base result on this
  2052. if (zz < epsilon) {
  2053. x = 0.707106781;
  2054. y = 0.707106781;
  2055. z = 0;
  2056. } else {
  2057. z = Math.sqrt(zz);
  2058. x = xz / z;
  2059. y = yz / z;
  2060. }
  2061. }
  2062. this.set(x, y, z, angle);
  2063. return this; // return 180 deg rotation
  2064. }
  2065. // as we have reached here there are no singularities so we can handle normally
  2066. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2067. if (Math.abs(s) < 0.001) s = 1;
  2068. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2069. // caught by singularity test above, but I've left it in just in case
  2070. this.x = (m32 - m23) / s;
  2071. this.y = (m13 - m31) / s;
  2072. this.z = (m21 - m12) / s;
  2073. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2074. return this;
  2075. }
  2076. min(v) {
  2077. this.x = Math.min(this.x, v.x);
  2078. this.y = Math.min(this.y, v.y);
  2079. this.z = Math.min(this.z, v.z);
  2080. this.w = Math.min(this.w, v.w);
  2081. return this;
  2082. }
  2083. max(v) {
  2084. this.x = Math.max(this.x, v.x);
  2085. this.y = Math.max(this.y, v.y);
  2086. this.z = Math.max(this.z, v.z);
  2087. this.w = Math.max(this.w, v.w);
  2088. return this;
  2089. }
  2090. clamp(min, max) {
  2091. // assumes min < max, componentwise
  2092. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2093. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2094. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2095. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2096. return this;
  2097. }
  2098. clampScalar(minVal, maxVal) {
  2099. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2100. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2101. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2102. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2103. return this;
  2104. }
  2105. clampLength(min, max) {
  2106. const length = this.length();
  2107. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2108. }
  2109. floor() {
  2110. this.x = Math.floor(this.x);
  2111. this.y = Math.floor(this.y);
  2112. this.z = Math.floor(this.z);
  2113. this.w = Math.floor(this.w);
  2114. return this;
  2115. }
  2116. ceil() {
  2117. this.x = Math.ceil(this.x);
  2118. this.y = Math.ceil(this.y);
  2119. this.z = Math.ceil(this.z);
  2120. this.w = Math.ceil(this.w);
  2121. return this;
  2122. }
  2123. round() {
  2124. this.x = Math.round(this.x);
  2125. this.y = Math.round(this.y);
  2126. this.z = Math.round(this.z);
  2127. this.w = Math.round(this.w);
  2128. return this;
  2129. }
  2130. roundToZero() {
  2131. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2132. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2133. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2134. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2135. return this;
  2136. }
  2137. negate() {
  2138. this.x = -this.x;
  2139. this.y = -this.y;
  2140. this.z = -this.z;
  2141. this.w = -this.w;
  2142. return this;
  2143. }
  2144. dot(v) {
  2145. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2146. }
  2147. lengthSq() {
  2148. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2149. }
  2150. length() {
  2151. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2152. }
  2153. manhattanLength() {
  2154. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2155. }
  2156. normalize() {
  2157. return this.divideScalar(this.length() || 1);
  2158. }
  2159. setLength(length) {
  2160. return this.normalize().multiplyScalar(length);
  2161. }
  2162. lerp(v, alpha) {
  2163. this.x += (v.x - this.x) * alpha;
  2164. this.y += (v.y - this.y) * alpha;
  2165. this.z += (v.z - this.z) * alpha;
  2166. this.w += (v.w - this.w) * alpha;
  2167. return this;
  2168. }
  2169. lerpVectors(v1, v2, alpha) {
  2170. this.x = v1.x + (v2.x - v1.x) * alpha;
  2171. this.y = v1.y + (v2.y - v1.y) * alpha;
  2172. this.z = v1.z + (v2.z - v1.z) * alpha;
  2173. this.w = v1.w + (v2.w - v1.w) * alpha;
  2174. return this;
  2175. }
  2176. equals(v) {
  2177. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2178. }
  2179. fromArray(array, offset = 0) {
  2180. this.x = array[offset];
  2181. this.y = array[offset + 1];
  2182. this.z = array[offset + 2];
  2183. this.w = array[offset + 3];
  2184. return this;
  2185. }
  2186. toArray(array = [], offset = 0) {
  2187. array[offset] = this.x;
  2188. array[offset + 1] = this.y;
  2189. array[offset + 2] = this.z;
  2190. array[offset + 3] = this.w;
  2191. return array;
  2192. }
  2193. fromBufferAttribute(attribute, index) {
  2194. this.x = attribute.getX(index);
  2195. this.y = attribute.getY(index);
  2196. this.z = attribute.getZ(index);
  2197. this.w = attribute.getW(index);
  2198. return this;
  2199. }
  2200. random() {
  2201. this.x = Math.random();
  2202. this.y = Math.random();
  2203. this.z = Math.random();
  2204. this.w = Math.random();
  2205. return this;
  2206. }
  2207. *[Symbol.iterator]() {
  2208. yield this.x;
  2209. yield this.y;
  2210. yield this.z;
  2211. yield this.w;
  2212. }
  2213. }
  2214. /*
  2215. In options, we can specify:
  2216. * Texture parameters for an auto-generated target texture
  2217. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2218. */
  2219. class WebGLRenderTarget extends EventDispatcher {
  2220. constructor(width = 1, height = 1, options = {}) {
  2221. super();
  2222. this.isWebGLRenderTarget = true;
  2223. this.width = width;
  2224. this.height = height;
  2225. this.depth = 1;
  2226. this.scissor = new Vector4(0, 0, width, height);
  2227. this.scissorTest = false;
  2228. this.viewport = new Vector4(0, 0, width, height);
  2229. const image = {
  2230. width: width,
  2231. height: height,
  2232. depth: 1
  2233. };
  2234. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2235. this.texture.isRenderTargetTexture = true;
  2236. this.texture.flipY = false;
  2237. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2238. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2239. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2240. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2241. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2242. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2243. this.samples = options.samples !== undefined ? options.samples : 0;
  2244. }
  2245. setSize(width, height, depth = 1) {
  2246. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2247. this.width = width;
  2248. this.height = height;
  2249. this.depth = depth;
  2250. this.texture.image.width = width;
  2251. this.texture.image.height = height;
  2252. this.texture.image.depth = depth;
  2253. this.dispose();
  2254. }
  2255. this.viewport.set(0, 0, width, height);
  2256. this.scissor.set(0, 0, width, height);
  2257. }
  2258. clone() {
  2259. return new this.constructor().copy(this);
  2260. }
  2261. copy(source) {
  2262. this.width = source.width;
  2263. this.height = source.height;
  2264. this.depth = source.depth;
  2265. this.viewport.copy(source.viewport);
  2266. this.texture = source.texture.clone();
  2267. this.texture.isRenderTargetTexture = true;
  2268. // ensure image object is not shared, see #20328
  2269. const image = Object.assign({}, source.texture.image);
  2270. this.texture.source = new Source(image);
  2271. this.depthBuffer = source.depthBuffer;
  2272. this.stencilBuffer = source.stencilBuffer;
  2273. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2274. this.samples = source.samples;
  2275. return this;
  2276. }
  2277. dispose() {
  2278. this.dispatchEvent({
  2279. type: 'dispose'
  2280. });
  2281. }
  2282. }
  2283. class DataArrayTexture extends Texture {
  2284. constructor(data = null, width = 1, height = 1, depth = 1) {
  2285. super(null);
  2286. this.isDataArrayTexture = true;
  2287. this.image = {
  2288. data,
  2289. width,
  2290. height,
  2291. depth
  2292. };
  2293. this.magFilter = NearestFilter;
  2294. this.minFilter = NearestFilter;
  2295. this.wrapR = ClampToEdgeWrapping;
  2296. this.generateMipmaps = false;
  2297. this.flipY = false;
  2298. this.unpackAlignment = 1;
  2299. }
  2300. }
  2301. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2302. constructor(width = 1, height = 1, depth = 1) {
  2303. super(width, height);
  2304. this.isWebGLArrayRenderTarget = true;
  2305. this.depth = depth;
  2306. this.texture = new DataArrayTexture(null, width, height, depth);
  2307. this.texture.isRenderTargetTexture = true;
  2308. }
  2309. }
  2310. class Data3DTexture extends Texture {
  2311. constructor(data = null, width = 1, height = 1, depth = 1) {
  2312. // We're going to add .setXXX() methods for setting properties later.
  2313. // Users can still set in DataTexture3D directly.
  2314. //
  2315. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2316. // texture.anisotropy = 16;
  2317. //
  2318. // See #14839
  2319. super(null);
  2320. this.isData3DTexture = true;
  2321. this.image = {
  2322. data,
  2323. width,
  2324. height,
  2325. depth
  2326. };
  2327. this.magFilter = NearestFilter;
  2328. this.minFilter = NearestFilter;
  2329. this.wrapR = ClampToEdgeWrapping;
  2330. this.generateMipmaps = false;
  2331. this.flipY = false;
  2332. this.unpackAlignment = 1;
  2333. }
  2334. }
  2335. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2336. constructor(width = 1, height = 1, depth = 1) {
  2337. super(width, height);
  2338. this.isWebGL3DRenderTarget = true;
  2339. this.depth = depth;
  2340. this.texture = new Data3DTexture(null, width, height, depth);
  2341. this.texture.isRenderTargetTexture = true;
  2342. }
  2343. }
  2344. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2345. constructor(width = 1, height = 1, count = 1, options = {}) {
  2346. super(width, height, options);
  2347. this.isWebGLMultipleRenderTargets = true;
  2348. const texture = this.texture;
  2349. this.texture = [];
  2350. for (let i = 0; i < count; i++) {
  2351. this.texture[i] = texture.clone();
  2352. this.texture[i].isRenderTargetTexture = true;
  2353. }
  2354. }
  2355. setSize(width, height, depth = 1) {
  2356. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2357. this.width = width;
  2358. this.height = height;
  2359. this.depth = depth;
  2360. for (let i = 0, il = this.texture.length; i < il; i++) {
  2361. this.texture[i].image.width = width;
  2362. this.texture[i].image.height = height;
  2363. this.texture[i].image.depth = depth;
  2364. }
  2365. this.dispose();
  2366. }
  2367. this.viewport.set(0, 0, width, height);
  2368. this.scissor.set(0, 0, width, height);
  2369. return this;
  2370. }
  2371. copy(source) {
  2372. this.dispose();
  2373. this.width = source.width;
  2374. this.height = source.height;
  2375. this.depth = source.depth;
  2376. this.viewport.set(0, 0, this.width, this.height);
  2377. this.scissor.set(0, 0, this.width, this.height);
  2378. this.depthBuffer = source.depthBuffer;
  2379. this.stencilBuffer = source.stencilBuffer;
  2380. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2381. this.texture.length = 0;
  2382. for (let i = 0, il = source.texture.length; i < il; i++) {
  2383. this.texture[i] = source.texture[i].clone();
  2384. this.texture[i].isRenderTargetTexture = true;
  2385. }
  2386. return this;
  2387. }
  2388. }
  2389. class Quaternion {
  2390. constructor(x = 0, y = 0, z = 0, w = 1) {
  2391. this.isQuaternion = true;
  2392. this._x = x;
  2393. this._y = y;
  2394. this._z = z;
  2395. this._w = w;
  2396. }
  2397. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2398. // fuzz-free, array-based Quaternion SLERP operation
  2399. let x0 = src0[srcOffset0 + 0],
  2400. y0 = src0[srcOffset0 + 1],
  2401. z0 = src0[srcOffset0 + 2],
  2402. w0 = src0[srcOffset0 + 3];
  2403. const x1 = src1[srcOffset1 + 0],
  2404. y1 = src1[srcOffset1 + 1],
  2405. z1 = src1[srcOffset1 + 2],
  2406. w1 = src1[srcOffset1 + 3];
  2407. if (t === 0) {
  2408. dst[dstOffset + 0] = x0;
  2409. dst[dstOffset + 1] = y0;
  2410. dst[dstOffset + 2] = z0;
  2411. dst[dstOffset + 3] = w0;
  2412. return;
  2413. }
  2414. if (t === 1) {
  2415. dst[dstOffset + 0] = x1;
  2416. dst[dstOffset + 1] = y1;
  2417. dst[dstOffset + 2] = z1;
  2418. dst[dstOffset + 3] = w1;
  2419. return;
  2420. }
  2421. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2422. let s = 1 - t;
  2423. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2424. dir = cos >= 0 ? 1 : -1,
  2425. sqrSin = 1 - cos * cos;
  2426. // Skip the Slerp for tiny steps to avoid numeric problems:
  2427. if (sqrSin > Number.EPSILON) {
  2428. const sin = Math.sqrt(sqrSin),
  2429. len = Math.atan2(sin, cos * dir);
  2430. s = Math.sin(s * len) / sin;
  2431. t = Math.sin(t * len) / sin;
  2432. }
  2433. const tDir = t * dir;
  2434. x0 = x0 * s + x1 * tDir;
  2435. y0 = y0 * s + y1 * tDir;
  2436. z0 = z0 * s + z1 * tDir;
  2437. w0 = w0 * s + w1 * tDir;
  2438. // Normalize in case we just did a lerp:
  2439. if (s === 1 - t) {
  2440. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2441. x0 *= f;
  2442. y0 *= f;
  2443. z0 *= f;
  2444. w0 *= f;
  2445. }
  2446. }
  2447. dst[dstOffset] = x0;
  2448. dst[dstOffset + 1] = y0;
  2449. dst[dstOffset + 2] = z0;
  2450. dst[dstOffset + 3] = w0;
  2451. }
  2452. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2453. const x0 = src0[srcOffset0];
  2454. const y0 = src0[srcOffset0 + 1];
  2455. const z0 = src0[srcOffset0 + 2];
  2456. const w0 = src0[srcOffset0 + 3];
  2457. const x1 = src1[srcOffset1];
  2458. const y1 = src1[srcOffset1 + 1];
  2459. const z1 = src1[srcOffset1 + 2];
  2460. const w1 = src1[srcOffset1 + 3];
  2461. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2462. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2463. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2464. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2465. return dst;
  2466. }
  2467. get x() {
  2468. return this._x;
  2469. }
  2470. set x(value) {
  2471. this._x = value;
  2472. this._onChangeCallback();
  2473. }
  2474. get y() {
  2475. return this._y;
  2476. }
  2477. set y(value) {
  2478. this._y = value;
  2479. this._onChangeCallback();
  2480. }
  2481. get z() {
  2482. return this._z;
  2483. }
  2484. set z(value) {
  2485. this._z = value;
  2486. this._onChangeCallback();
  2487. }
  2488. get w() {
  2489. return this._w;
  2490. }
  2491. set w(value) {
  2492. this._w = value;
  2493. this._onChangeCallback();
  2494. }
  2495. set(x, y, z, w) {
  2496. this._x = x;
  2497. this._y = y;
  2498. this._z = z;
  2499. this._w = w;
  2500. this._onChangeCallback();
  2501. return this;
  2502. }
  2503. clone() {
  2504. return new this.constructor(this._x, this._y, this._z, this._w);
  2505. }
  2506. copy(quaternion) {
  2507. this._x = quaternion.x;
  2508. this._y = quaternion.y;
  2509. this._z = quaternion.z;
  2510. this._w = quaternion.w;
  2511. this._onChangeCallback();
  2512. return this;
  2513. }
  2514. setFromEuler(euler, update) {
  2515. const x = euler._x,
  2516. y = euler._y,
  2517. z = euler._z,
  2518. order = euler._order;
  2519. // http://www.mathworks.com/matlabcentral/fileexchange/
  2520. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2521. // content/SpinCalc.m
  2522. const cos = Math.cos;
  2523. const sin = Math.sin;
  2524. const c1 = cos(x / 2);
  2525. const c2 = cos(y / 2);
  2526. const c3 = cos(z / 2);
  2527. const s1 = sin(x / 2);
  2528. const s2 = sin(y / 2);
  2529. const s3 = sin(z / 2);
  2530. switch (order) {
  2531. case 'XYZ':
  2532. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2533. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2534. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2535. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2536. break;
  2537. case 'YXZ':
  2538. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2539. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2540. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2541. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2542. break;
  2543. case 'ZXY':
  2544. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2545. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2546. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2547. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2548. break;
  2549. case 'ZYX':
  2550. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2551. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2552. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2553. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2554. break;
  2555. case 'YZX':
  2556. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2557. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2558. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2559. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2560. break;
  2561. case 'XZY':
  2562. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2563. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2564. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2565. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2566. break;
  2567. default:
  2568. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2569. }
  2570. if (update !== false) this._onChangeCallback();
  2571. return this;
  2572. }
  2573. setFromAxisAngle(axis, angle) {
  2574. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2575. // assumes axis is normalized
  2576. const halfAngle = angle / 2,
  2577. s = Math.sin(halfAngle);
  2578. this._x = axis.x * s;
  2579. this._y = axis.y * s;
  2580. this._z = axis.z * s;
  2581. this._w = Math.cos(halfAngle);
  2582. this._onChangeCallback();
  2583. return this;
  2584. }
  2585. setFromRotationMatrix(m) {
  2586. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2587. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2588. const te = m.elements,
  2589. m11 = te[0],
  2590. m12 = te[4],
  2591. m13 = te[8],
  2592. m21 = te[1],
  2593. m22 = te[5],
  2594. m23 = te[9],
  2595. m31 = te[2],
  2596. m32 = te[6],
  2597. m33 = te[10],
  2598. trace = m11 + m22 + m33;
  2599. if (trace > 0) {
  2600. const s = 0.5 / Math.sqrt(trace + 1.0);
  2601. this._w = 0.25 / s;
  2602. this._x = (m32 - m23) * s;
  2603. this._y = (m13 - m31) * s;
  2604. this._z = (m21 - m12) * s;
  2605. } else if (m11 > m22 && m11 > m33) {
  2606. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2607. this._w = (m32 - m23) / s;
  2608. this._x = 0.25 * s;
  2609. this._y = (m12 + m21) / s;
  2610. this._z = (m13 + m31) / s;
  2611. } else if (m22 > m33) {
  2612. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2613. this._w = (m13 - m31) / s;
  2614. this._x = (m12 + m21) / s;
  2615. this._y = 0.25 * s;
  2616. this._z = (m23 + m32) / s;
  2617. } else {
  2618. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2619. this._w = (m21 - m12) / s;
  2620. this._x = (m13 + m31) / s;
  2621. this._y = (m23 + m32) / s;
  2622. this._z = 0.25 * s;
  2623. }
  2624. this._onChangeCallback();
  2625. return this;
  2626. }
  2627. setFromUnitVectors(vFrom, vTo) {
  2628. // assumes direction vectors vFrom and vTo are normalized
  2629. let r = vFrom.dot(vTo) + 1;
  2630. if (r < Number.EPSILON) {
  2631. // vFrom and vTo point in opposite directions
  2632. r = 0;
  2633. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2634. this._x = -vFrom.y;
  2635. this._y = vFrom.x;
  2636. this._z = 0;
  2637. this._w = r;
  2638. } else {
  2639. this._x = 0;
  2640. this._y = -vFrom.z;
  2641. this._z = vFrom.y;
  2642. this._w = r;
  2643. }
  2644. } else {
  2645. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2646. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2647. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2648. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2649. this._w = r;
  2650. }
  2651. return this.normalize();
  2652. }
  2653. angleTo(q) {
  2654. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2655. }
  2656. rotateTowards(q, step) {
  2657. const angle = this.angleTo(q);
  2658. if (angle === 0) return this;
  2659. const t = Math.min(1, step / angle);
  2660. this.slerp(q, t);
  2661. return this;
  2662. }
  2663. identity() {
  2664. return this.set(0, 0, 0, 1);
  2665. }
  2666. invert() {
  2667. // quaternion is assumed to have unit length
  2668. return this.conjugate();
  2669. }
  2670. conjugate() {
  2671. this._x *= -1;
  2672. this._y *= -1;
  2673. this._z *= -1;
  2674. this._onChangeCallback();
  2675. return this;
  2676. }
  2677. dot(v) {
  2678. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2679. }
  2680. lengthSq() {
  2681. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2682. }
  2683. length() {
  2684. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2685. }
  2686. normalize() {
  2687. let l = this.length();
  2688. if (l === 0) {
  2689. this._x = 0;
  2690. this._y = 0;
  2691. this._z = 0;
  2692. this._w = 1;
  2693. } else {
  2694. l = 1 / l;
  2695. this._x = this._x * l;
  2696. this._y = this._y * l;
  2697. this._z = this._z * l;
  2698. this._w = this._w * l;
  2699. }
  2700. this._onChangeCallback();
  2701. return this;
  2702. }
  2703. multiply(q) {
  2704. return this.multiplyQuaternions(this, q);
  2705. }
  2706. premultiply(q) {
  2707. return this.multiplyQuaternions(q, this);
  2708. }
  2709. multiplyQuaternions(a, b) {
  2710. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2711. const qax = a._x,
  2712. qay = a._y,
  2713. qaz = a._z,
  2714. qaw = a._w;
  2715. const qbx = b._x,
  2716. qby = b._y,
  2717. qbz = b._z,
  2718. qbw = b._w;
  2719. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2720. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2721. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2722. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2723. this._onChangeCallback();
  2724. return this;
  2725. }
  2726. slerp(qb, t) {
  2727. if (t === 0) return this;
  2728. if (t === 1) return this.copy(qb);
  2729. const x = this._x,
  2730. y = this._y,
  2731. z = this._z,
  2732. w = this._w;
  2733. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2734. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2735. if (cosHalfTheta < 0) {
  2736. this._w = -qb._w;
  2737. this._x = -qb._x;
  2738. this._y = -qb._y;
  2739. this._z = -qb._z;
  2740. cosHalfTheta = -cosHalfTheta;
  2741. } else {
  2742. this.copy(qb);
  2743. }
  2744. if (cosHalfTheta >= 1.0) {
  2745. this._w = w;
  2746. this._x = x;
  2747. this._y = y;
  2748. this._z = z;
  2749. return this;
  2750. }
  2751. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2752. if (sqrSinHalfTheta <= Number.EPSILON) {
  2753. const s = 1 - t;
  2754. this._w = s * w + t * this._w;
  2755. this._x = s * x + t * this._x;
  2756. this._y = s * y + t * this._y;
  2757. this._z = s * z + t * this._z;
  2758. this.normalize();
  2759. this._onChangeCallback();
  2760. return this;
  2761. }
  2762. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2763. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2764. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2765. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2766. this._w = w * ratioA + this._w * ratioB;
  2767. this._x = x * ratioA + this._x * ratioB;
  2768. this._y = y * ratioA + this._y * ratioB;
  2769. this._z = z * ratioA + this._z * ratioB;
  2770. this._onChangeCallback();
  2771. return this;
  2772. }
  2773. slerpQuaternions(qa, qb, t) {
  2774. return this.copy(qa).slerp(qb, t);
  2775. }
  2776. random() {
  2777. // Derived from http://planning.cs.uiuc.edu/node198.html
  2778. // Note, this source uses w, x, y, z ordering,
  2779. // so we swap the order below.
  2780. const u1 = Math.random();
  2781. const sqrt1u1 = Math.sqrt(1 - u1);
  2782. const sqrtu1 = Math.sqrt(u1);
  2783. const u2 = 2 * Math.PI * Math.random();
  2784. const u3 = 2 * Math.PI * Math.random();
  2785. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2786. }
  2787. equals(quaternion) {
  2788. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2789. }
  2790. fromArray(array, offset = 0) {
  2791. this._x = array[offset];
  2792. this._y = array[offset + 1];
  2793. this._z = array[offset + 2];
  2794. this._w = array[offset + 3];
  2795. this._onChangeCallback();
  2796. return this;
  2797. }
  2798. toArray(array = [], offset = 0) {
  2799. array[offset] = this._x;
  2800. array[offset + 1] = this._y;
  2801. array[offset + 2] = this._z;
  2802. array[offset + 3] = this._w;
  2803. return array;
  2804. }
  2805. fromBufferAttribute(attribute, index) {
  2806. this._x = attribute.getX(index);
  2807. this._y = attribute.getY(index);
  2808. this._z = attribute.getZ(index);
  2809. this._w = attribute.getW(index);
  2810. return this;
  2811. }
  2812. _onChange(callback) {
  2813. this._onChangeCallback = callback;
  2814. return this;
  2815. }
  2816. _onChangeCallback() {}
  2817. *[Symbol.iterator]() {
  2818. yield this._x;
  2819. yield this._y;
  2820. yield this._z;
  2821. yield this._w;
  2822. }
  2823. }
  2824. class Vector3 {
  2825. constructor(x = 0, y = 0, z = 0) {
  2826. Vector3.prototype.isVector3 = true;
  2827. this.x = x;
  2828. this.y = y;
  2829. this.z = z;
  2830. }
  2831. set(x, y, z) {
  2832. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2833. this.x = x;
  2834. this.y = y;
  2835. this.z = z;
  2836. return this;
  2837. }
  2838. setScalar(scalar) {
  2839. this.x = scalar;
  2840. this.y = scalar;
  2841. this.z = scalar;
  2842. return this;
  2843. }
  2844. setX(x) {
  2845. this.x = x;
  2846. return this;
  2847. }
  2848. setY(y) {
  2849. this.y = y;
  2850. return this;
  2851. }
  2852. setZ(z) {
  2853. this.z = z;
  2854. return this;
  2855. }
  2856. setComponent(index, value) {
  2857. switch (index) {
  2858. case 0:
  2859. this.x = value;
  2860. break;
  2861. case 1:
  2862. this.y = value;
  2863. break;
  2864. case 2:
  2865. this.z = value;
  2866. break;
  2867. default:
  2868. throw new Error('index is out of range: ' + index);
  2869. }
  2870. return this;
  2871. }
  2872. getComponent(index) {
  2873. switch (index) {
  2874. case 0:
  2875. return this.x;
  2876. case 1:
  2877. return this.y;
  2878. case 2:
  2879. return this.z;
  2880. default:
  2881. throw new Error('index is out of range: ' + index);
  2882. }
  2883. }
  2884. clone() {
  2885. return new this.constructor(this.x, this.y, this.z);
  2886. }
  2887. copy(v) {
  2888. this.x = v.x;
  2889. this.y = v.y;
  2890. this.z = v.z;
  2891. return this;
  2892. }
  2893. add(v) {
  2894. this.x += v.x;
  2895. this.y += v.y;
  2896. this.z += v.z;
  2897. return this;
  2898. }
  2899. addScalar(s) {
  2900. this.x += s;
  2901. this.y += s;
  2902. this.z += s;
  2903. return this;
  2904. }
  2905. addVectors(a, b) {
  2906. this.x = a.x + b.x;
  2907. this.y = a.y + b.y;
  2908. this.z = a.z + b.z;
  2909. return this;
  2910. }
  2911. addScaledVector(v, s) {
  2912. this.x += v.x * s;
  2913. this.y += v.y * s;
  2914. this.z += v.z * s;
  2915. return this;
  2916. }
  2917. sub(v) {
  2918. this.x -= v.x;
  2919. this.y -= v.y;
  2920. this.z -= v.z;
  2921. return this;
  2922. }
  2923. subScalar(s) {
  2924. this.x -= s;
  2925. this.y -= s;
  2926. this.z -= s;
  2927. return this;
  2928. }
  2929. subVectors(a, b) {
  2930. this.x = a.x - b.x;
  2931. this.y = a.y - b.y;
  2932. this.z = a.z - b.z;
  2933. return this;
  2934. }
  2935. multiply(v) {
  2936. this.x *= v.x;
  2937. this.y *= v.y;
  2938. this.z *= v.z;
  2939. return this;
  2940. }
  2941. multiplyScalar(scalar) {
  2942. this.x *= scalar;
  2943. this.y *= scalar;
  2944. this.z *= scalar;
  2945. return this;
  2946. }
  2947. multiplyVectors(a, b) {
  2948. this.x = a.x * b.x;
  2949. this.y = a.y * b.y;
  2950. this.z = a.z * b.z;
  2951. return this;
  2952. }
  2953. applyEuler(euler) {
  2954. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2955. }
  2956. applyAxisAngle(axis, angle) {
  2957. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2958. }
  2959. applyMatrix3(m) {
  2960. const x = this.x,
  2961. y = this.y,
  2962. z = this.z;
  2963. const e = m.elements;
  2964. this.x = e[0] * x + e[3] * y + e[6] * z;
  2965. this.y = e[1] * x + e[4] * y + e[7] * z;
  2966. this.z = e[2] * x + e[5] * y + e[8] * z;
  2967. return this;
  2968. }
  2969. applyNormalMatrix(m) {
  2970. return this.applyMatrix3(m).normalize();
  2971. }
  2972. applyMatrix4(m) {
  2973. const x = this.x,
  2974. y = this.y,
  2975. z = this.z;
  2976. const e = m.elements;
  2977. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2978. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2979. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2980. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2981. return this;
  2982. }
  2983. applyQuaternion(q) {
  2984. const x = this.x,
  2985. y = this.y,
  2986. z = this.z;
  2987. const qx = q.x,
  2988. qy = q.y,
  2989. qz = q.z,
  2990. qw = q.w;
  2991. // calculate quat * vector
  2992. const ix = qw * x + qy * z - qz * y;
  2993. const iy = qw * y + qz * x - qx * z;
  2994. const iz = qw * z + qx * y - qy * x;
  2995. const iw = -qx * x - qy * y - qz * z;
  2996. // calculate result * inverse quat
  2997. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2998. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2999. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3000. return this;
  3001. }
  3002. project(camera) {
  3003. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  3004. }
  3005. unproject(camera) {
  3006. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  3007. }
  3008. transformDirection(m) {
  3009. // input: THREE.Matrix4 affine matrix
  3010. // vector interpreted as a direction
  3011. const x = this.x,
  3012. y = this.y,
  3013. z = this.z;
  3014. const e = m.elements;
  3015. this.x = e[0] * x + e[4] * y + e[8] * z;
  3016. this.y = e[1] * x + e[5] * y + e[9] * z;
  3017. this.z = e[2] * x + e[6] * y + e[10] * z;
  3018. return this.normalize();
  3019. }
  3020. divide(v) {
  3021. this.x /= v.x;
  3022. this.y /= v.y;
  3023. this.z /= v.z;
  3024. return this;
  3025. }
  3026. divideScalar(scalar) {
  3027. return this.multiplyScalar(1 / scalar);
  3028. }
  3029. min(v) {
  3030. this.x = Math.min(this.x, v.x);
  3031. this.y = Math.min(this.y, v.y);
  3032. this.z = Math.min(this.z, v.z);
  3033. return this;
  3034. }
  3035. max(v) {
  3036. this.x = Math.max(this.x, v.x);
  3037. this.y = Math.max(this.y, v.y);
  3038. this.z = Math.max(this.z, v.z);
  3039. return this;
  3040. }
  3041. clamp(min, max) {
  3042. // assumes min < max, componentwise
  3043. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3044. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3045. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3046. return this;
  3047. }
  3048. clampScalar(minVal, maxVal) {
  3049. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3050. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3051. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3052. return this;
  3053. }
  3054. clampLength(min, max) {
  3055. const length = this.length();
  3056. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3057. }
  3058. floor() {
  3059. this.x = Math.floor(this.x);
  3060. this.y = Math.floor(this.y);
  3061. this.z = Math.floor(this.z);
  3062. return this;
  3063. }
  3064. ceil() {
  3065. this.x = Math.ceil(this.x);
  3066. this.y = Math.ceil(this.y);
  3067. this.z = Math.ceil(this.z);
  3068. return this;
  3069. }
  3070. round() {
  3071. this.x = Math.round(this.x);
  3072. this.y = Math.round(this.y);
  3073. this.z = Math.round(this.z);
  3074. return this;
  3075. }
  3076. roundToZero() {
  3077. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3078. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3079. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3080. return this;
  3081. }
  3082. negate() {
  3083. this.x = -this.x;
  3084. this.y = -this.y;
  3085. this.z = -this.z;
  3086. return this;
  3087. }
  3088. dot(v) {
  3089. return this.x * v.x + this.y * v.y + this.z * v.z;
  3090. }
  3091. // TODO lengthSquared?
  3092. lengthSq() {
  3093. return this.x * this.x + this.y * this.y + this.z * this.z;
  3094. }
  3095. length() {
  3096. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3097. }
  3098. manhattanLength() {
  3099. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3100. }
  3101. normalize() {
  3102. return this.divideScalar(this.length() || 1);
  3103. }
  3104. setLength(length) {
  3105. return this.normalize().multiplyScalar(length);
  3106. }
  3107. lerp(v, alpha) {
  3108. this.x += (v.x - this.x) * alpha;
  3109. this.y += (v.y - this.y) * alpha;
  3110. this.z += (v.z - this.z) * alpha;
  3111. return this;
  3112. }
  3113. lerpVectors(v1, v2, alpha) {
  3114. this.x = v1.x + (v2.x - v1.x) * alpha;
  3115. this.y = v1.y + (v2.y - v1.y) * alpha;
  3116. this.z = v1.z + (v2.z - v1.z) * alpha;
  3117. return this;
  3118. }
  3119. cross(v) {
  3120. return this.crossVectors(this, v);
  3121. }
  3122. crossVectors(a, b) {
  3123. const ax = a.x,
  3124. ay = a.y,
  3125. az = a.z;
  3126. const bx = b.x,
  3127. by = b.y,
  3128. bz = b.z;
  3129. this.x = ay * bz - az * by;
  3130. this.y = az * bx - ax * bz;
  3131. this.z = ax * by - ay * bx;
  3132. return this;
  3133. }
  3134. projectOnVector(v) {
  3135. const denominator = v.lengthSq();
  3136. if (denominator === 0) return this.set(0, 0, 0);
  3137. const scalar = v.dot(this) / denominator;
  3138. return this.copy(v).multiplyScalar(scalar);
  3139. }
  3140. projectOnPlane(planeNormal) {
  3141. _vector$c.copy(this).projectOnVector(planeNormal);
  3142. return this.sub(_vector$c);
  3143. }
  3144. reflect(normal) {
  3145. // reflect incident vector off plane orthogonal to normal
  3146. // normal is assumed to have unit length
  3147. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3148. }
  3149. angleTo(v) {
  3150. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3151. if (denominator === 0) return Math.PI / 2;
  3152. const theta = this.dot(v) / denominator;
  3153. // clamp, to handle numerical problems
  3154. return Math.acos(clamp(theta, -1, 1));
  3155. }
  3156. distanceTo(v) {
  3157. return Math.sqrt(this.distanceToSquared(v));
  3158. }
  3159. distanceToSquared(v) {
  3160. const dx = this.x - v.x,
  3161. dy = this.y - v.y,
  3162. dz = this.z - v.z;
  3163. return dx * dx + dy * dy + dz * dz;
  3164. }
  3165. manhattanDistanceTo(v) {
  3166. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3167. }
  3168. setFromSpherical(s) {
  3169. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3170. }
  3171. setFromSphericalCoords(radius, phi, theta) {
  3172. const sinPhiRadius = Math.sin(phi) * radius;
  3173. this.x = sinPhiRadius * Math.sin(theta);
  3174. this.y = Math.cos(phi) * radius;
  3175. this.z = sinPhiRadius * Math.cos(theta);
  3176. return this;
  3177. }
  3178. setFromCylindrical(c) {
  3179. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3180. }
  3181. setFromCylindricalCoords(radius, theta, y) {
  3182. this.x = radius * Math.sin(theta);
  3183. this.y = y;
  3184. this.z = radius * Math.cos(theta);
  3185. return this;
  3186. }
  3187. setFromMatrixPosition(m) {
  3188. const e = m.elements;
  3189. this.x = e[12];
  3190. this.y = e[13];
  3191. this.z = e[14];
  3192. return this;
  3193. }
  3194. setFromMatrixScale(m) {
  3195. const sx = this.setFromMatrixColumn(m, 0).length();
  3196. const sy = this.setFromMatrixColumn(m, 1).length();
  3197. const sz = this.setFromMatrixColumn(m, 2).length();
  3198. this.x = sx;
  3199. this.y = sy;
  3200. this.z = sz;
  3201. return this;
  3202. }
  3203. setFromMatrixColumn(m, index) {
  3204. return this.fromArray(m.elements, index * 4);
  3205. }
  3206. setFromMatrix3Column(m, index) {
  3207. return this.fromArray(m.elements, index * 3);
  3208. }
  3209. setFromEuler(e) {
  3210. this.x = e._x;
  3211. this.y = e._y;
  3212. this.z = e._z;
  3213. return this;
  3214. }
  3215. equals(v) {
  3216. return v.x === this.x && v.y === this.y && v.z === this.z;
  3217. }
  3218. fromArray(array, offset = 0) {
  3219. this.x = array[offset];
  3220. this.y = array[offset + 1];
  3221. this.z = array[offset + 2];
  3222. return this;
  3223. }
  3224. toArray(array = [], offset = 0) {
  3225. array[offset] = this.x;
  3226. array[offset + 1] = this.y;
  3227. array[offset + 2] = this.z;
  3228. return array;
  3229. }
  3230. fromBufferAttribute(attribute, index) {
  3231. this.x = attribute.getX(index);
  3232. this.y = attribute.getY(index);
  3233. this.z = attribute.getZ(index);
  3234. return this;
  3235. }
  3236. random() {
  3237. this.x = Math.random();
  3238. this.y = Math.random();
  3239. this.z = Math.random();
  3240. return this;
  3241. }
  3242. randomDirection() {
  3243. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3244. const u = (Math.random() - 0.5) * 2;
  3245. const t = Math.random() * Math.PI * 2;
  3246. const f = Math.sqrt(1 - u ** 2);
  3247. this.x = f * Math.cos(t);
  3248. this.y = f * Math.sin(t);
  3249. this.z = u;
  3250. return this;
  3251. }
  3252. *[Symbol.iterator]() {
  3253. yield this.x;
  3254. yield this.y;
  3255. yield this.z;
  3256. }
  3257. }
  3258. const _vector$c = /*@__PURE__*/new Vector3();
  3259. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3260. class Box3 {
  3261. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3262. this.isBox3 = true;
  3263. this.min = min;
  3264. this.max = max;
  3265. }
  3266. set(min, max) {
  3267. this.min.copy(min);
  3268. this.max.copy(max);
  3269. return this;
  3270. }
  3271. setFromArray(array) {
  3272. let minX = +Infinity;
  3273. let minY = +Infinity;
  3274. let minZ = +Infinity;
  3275. let maxX = -Infinity;
  3276. let maxY = -Infinity;
  3277. let maxZ = -Infinity;
  3278. for (let i = 0, l = array.length; i < l; i += 3) {
  3279. const x = array[i];
  3280. const y = array[i + 1];
  3281. const z = array[i + 2];
  3282. if (x < minX) minX = x;
  3283. if (y < minY) minY = y;
  3284. if (z < minZ) minZ = z;
  3285. if (x > maxX) maxX = x;
  3286. if (y > maxY) maxY = y;
  3287. if (z > maxZ) maxZ = z;
  3288. }
  3289. this.min.set(minX, minY, minZ);
  3290. this.max.set(maxX, maxY, maxZ);
  3291. return this;
  3292. }
  3293. setFromBufferAttribute(attribute) {
  3294. let minX = +Infinity;
  3295. let minY = +Infinity;
  3296. let minZ = +Infinity;
  3297. let maxX = -Infinity;
  3298. let maxY = -Infinity;
  3299. let maxZ = -Infinity;
  3300. for (let i = 0, l = attribute.count; i < l; i++) {
  3301. const x = attribute.getX(i);
  3302. const y = attribute.getY(i);
  3303. const z = attribute.getZ(i);
  3304. if (x < minX) minX = x;
  3305. if (y < minY) minY = y;
  3306. if (z < minZ) minZ = z;
  3307. if (x > maxX) maxX = x;
  3308. if (y > maxY) maxY = y;
  3309. if (z > maxZ) maxZ = z;
  3310. }
  3311. this.min.set(minX, minY, minZ);
  3312. this.max.set(maxX, maxY, maxZ);
  3313. return this;
  3314. }
  3315. setFromPoints(points) {
  3316. this.makeEmpty();
  3317. for (let i = 0, il = points.length; i < il; i++) {
  3318. this.expandByPoint(points[i]);
  3319. }
  3320. return this;
  3321. }
  3322. setFromCenterAndSize(center, size) {
  3323. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3324. this.min.copy(center).sub(halfSize);
  3325. this.max.copy(center).add(halfSize);
  3326. return this;
  3327. }
  3328. setFromObject(object, precise = false) {
  3329. this.makeEmpty();
  3330. return this.expandByObject(object, precise);
  3331. }
  3332. clone() {
  3333. return new this.constructor().copy(this);
  3334. }
  3335. copy(box) {
  3336. this.min.copy(box.min);
  3337. this.max.copy(box.max);
  3338. return this;
  3339. }
  3340. makeEmpty() {
  3341. this.min.x = this.min.y = this.min.z = +Infinity;
  3342. this.max.x = this.max.y = this.max.z = -Infinity;
  3343. return this;
  3344. }
  3345. isEmpty() {
  3346. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3347. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3348. }
  3349. getCenter(target) {
  3350. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3351. }
  3352. getSize(target) {
  3353. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3354. }
  3355. expandByPoint(point) {
  3356. this.min.min(point);
  3357. this.max.max(point);
  3358. return this;
  3359. }
  3360. expandByVector(vector) {
  3361. this.min.sub(vector);
  3362. this.max.add(vector);
  3363. return this;
  3364. }
  3365. expandByScalar(scalar) {
  3366. this.min.addScalar(-scalar);
  3367. this.max.addScalar(scalar);
  3368. return this;
  3369. }
  3370. expandByObject(object, precise = false) {
  3371. // Computes the world-axis-aligned bounding box of an object (including its children),
  3372. // accounting for both the object's, and children's, world transforms
  3373. object.updateWorldMatrix(false, false);
  3374. const geometry = object.geometry;
  3375. if (geometry !== undefined) {
  3376. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3377. const position = geometry.attributes.position;
  3378. for (let i = 0, l = position.count; i < l; i++) {
  3379. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3380. this.expandByPoint(_vector$b);
  3381. }
  3382. } else {
  3383. if (geometry.boundingBox === null) {
  3384. geometry.computeBoundingBox();
  3385. }
  3386. _box$3.copy(geometry.boundingBox);
  3387. _box$3.applyMatrix4(object.matrixWorld);
  3388. this.union(_box$3);
  3389. }
  3390. }
  3391. const children = object.children;
  3392. for (let i = 0, l = children.length; i < l; i++) {
  3393. this.expandByObject(children[i], precise);
  3394. }
  3395. return this;
  3396. }
  3397. containsPoint(point) {
  3398. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  3399. }
  3400. containsBox(box) {
  3401. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  3402. }
  3403. getParameter(point, target) {
  3404. // This can potentially have a divide by zero if the box
  3405. // has a size dimension of 0.
  3406. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  3407. }
  3408. intersectsBox(box) {
  3409. // using 6 splitting planes to rule out intersections.
  3410. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3411. }
  3412. intersectsSphere(sphere) {
  3413. // Find the point on the AABB closest to the sphere center.
  3414. this.clampPoint(sphere.center, _vector$b);
  3415. // If that point is inside the sphere, the AABB and sphere intersect.
  3416. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3417. }
  3418. intersectsPlane(plane) {
  3419. // We compute the minimum and maximum dot product values. If those values
  3420. // are on the same side (back or front) of the plane, then there is no intersection.
  3421. let min, max;
  3422. if (plane.normal.x > 0) {
  3423. min = plane.normal.x * this.min.x;
  3424. max = plane.normal.x * this.max.x;
  3425. } else {
  3426. min = plane.normal.x * this.max.x;
  3427. max = plane.normal.x * this.min.x;
  3428. }
  3429. if (plane.normal.y > 0) {
  3430. min += plane.normal.y * this.min.y;
  3431. max += plane.normal.y * this.max.y;
  3432. } else {
  3433. min += plane.normal.y * this.max.y;
  3434. max += plane.normal.y * this.min.y;
  3435. }
  3436. if (plane.normal.z > 0) {
  3437. min += plane.normal.z * this.min.z;
  3438. max += plane.normal.z * this.max.z;
  3439. } else {
  3440. min += plane.normal.z * this.max.z;
  3441. max += plane.normal.z * this.min.z;
  3442. }
  3443. return min <= -plane.constant && max >= -plane.constant;
  3444. }
  3445. intersectsTriangle(triangle) {
  3446. if (this.isEmpty()) {
  3447. return false;
  3448. }
  3449. // compute box center and extents
  3450. this.getCenter(_center);
  3451. _extents.subVectors(this.max, _center);
  3452. // translate triangle to aabb origin
  3453. _v0$2.subVectors(triangle.a, _center);
  3454. _v1$7.subVectors(triangle.b, _center);
  3455. _v2$4.subVectors(triangle.c, _center);
  3456. // compute edge vectors for triangle
  3457. _f0.subVectors(_v1$7, _v0$2);
  3458. _f1.subVectors(_v2$4, _v1$7);
  3459. _f2.subVectors(_v0$2, _v2$4);
  3460. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3461. // 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
  3462. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3463. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  3464. if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
  3465. return false;
  3466. }
  3467. // test 3 face normals from the aabb
  3468. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3469. if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
  3470. return false;
  3471. }
  3472. // finally testing the face normal of the triangle
  3473. // use already existing triangle edge vectors here
  3474. _triangleNormal.crossVectors(_f0, _f1);
  3475. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3476. return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents);
  3477. }
  3478. clampPoint(point, target) {
  3479. return target.copy(point).clamp(this.min, this.max);
  3480. }
  3481. distanceToPoint(point) {
  3482. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3483. return clampedPoint.sub(point).length();
  3484. }
  3485. getBoundingSphere(target) {
  3486. this.getCenter(target.center);
  3487. target.radius = this.getSize(_vector$b).length() * 0.5;
  3488. return target;
  3489. }
  3490. intersect(box) {
  3491. this.min.max(box.min);
  3492. this.max.min(box.max);
  3493. // 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.
  3494. if (this.isEmpty()) this.makeEmpty();
  3495. return this;
  3496. }
  3497. union(box) {
  3498. this.min.min(box.min);
  3499. this.max.max(box.max);
  3500. return this;
  3501. }
  3502. applyMatrix4(matrix) {
  3503. // transform of empty box is an empty box.
  3504. if (this.isEmpty()) return this;
  3505. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3506. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3507. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3508. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3509. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3510. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3511. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3512. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3513. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3514. this.setFromPoints(_points);
  3515. return this;
  3516. }
  3517. translate(offset) {
  3518. this.min.add(offset);
  3519. this.max.add(offset);
  3520. return this;
  3521. }
  3522. equals(box) {
  3523. return box.min.equals(this.min) && box.max.equals(this.max);
  3524. }
  3525. }
  3526. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  3527. const _vector$b = /*@__PURE__*/new Vector3();
  3528. const _box$3 = /*@__PURE__*/new Box3();
  3529. // triangle centered vertices
  3530. const _v0$2 = /*@__PURE__*/new Vector3();
  3531. const _v1$7 = /*@__PURE__*/new Vector3();
  3532. const _v2$4 = /*@__PURE__*/new Vector3();
  3533. // triangle edge vectors
  3534. const _f0 = /*@__PURE__*/new Vector3();
  3535. const _f1 = /*@__PURE__*/new Vector3();
  3536. const _f2 = /*@__PURE__*/new Vector3();
  3537. const _center = /*@__PURE__*/new Vector3();
  3538. const _extents = /*@__PURE__*/new Vector3();
  3539. const _triangleNormal = /*@__PURE__*/new Vector3();
  3540. const _testAxis = /*@__PURE__*/new Vector3();
  3541. function satForAxes(axes, v0, v1, v2, extents) {
  3542. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3543. _testAxis.fromArray(axes, i);
  3544. // project the aabb onto the separating axis
  3545. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z);
  3546. // project all 3 vertices of the triangle onto the separating axis
  3547. const p0 = v0.dot(_testAxis);
  3548. const p1 = v1.dot(_testAxis);
  3549. const p2 = v2.dot(_testAxis);
  3550. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3551. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3552. // points of the projected triangle are outside the projected half-length of the aabb
  3553. // the axis is separating and we can exit
  3554. return false;
  3555. }
  3556. }
  3557. return true;
  3558. }
  3559. const _box$2 = /*@__PURE__*/new Box3();
  3560. const _v1$6 = /*@__PURE__*/new Vector3();
  3561. const _v2$3 = /*@__PURE__*/new Vector3();
  3562. class Sphere {
  3563. constructor(center = new Vector3(), radius = -1) {
  3564. this.center = center;
  3565. this.radius = radius;
  3566. }
  3567. set(center, radius) {
  3568. this.center.copy(center);
  3569. this.radius = radius;
  3570. return this;
  3571. }
  3572. setFromPoints(points, optionalCenter) {
  3573. const center = this.center;
  3574. if (optionalCenter !== undefined) {
  3575. center.copy(optionalCenter);
  3576. } else {
  3577. _box$2.setFromPoints(points).getCenter(center);
  3578. }
  3579. let maxRadiusSq = 0;
  3580. for (let i = 0, il = points.length; i < il; i++) {
  3581. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3582. }
  3583. this.radius = Math.sqrt(maxRadiusSq);
  3584. return this;
  3585. }
  3586. copy(sphere) {
  3587. this.center.copy(sphere.center);
  3588. this.radius = sphere.radius;
  3589. return this;
  3590. }
  3591. isEmpty() {
  3592. return this.radius < 0;
  3593. }
  3594. makeEmpty() {
  3595. this.center.set(0, 0, 0);
  3596. this.radius = -1;
  3597. return this;
  3598. }
  3599. containsPoint(point) {
  3600. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3601. }
  3602. distanceToPoint(point) {
  3603. return point.distanceTo(this.center) - this.radius;
  3604. }
  3605. intersectsSphere(sphere) {
  3606. const radiusSum = this.radius + sphere.radius;
  3607. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3608. }
  3609. intersectsBox(box) {
  3610. return box.intersectsSphere(this);
  3611. }
  3612. intersectsPlane(plane) {
  3613. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3614. }
  3615. clampPoint(point, target) {
  3616. const deltaLengthSq = this.center.distanceToSquared(point);
  3617. target.copy(point);
  3618. if (deltaLengthSq > this.radius * this.radius) {
  3619. target.sub(this.center).normalize();
  3620. target.multiplyScalar(this.radius).add(this.center);
  3621. }
  3622. return target;
  3623. }
  3624. getBoundingBox(target) {
  3625. if (this.isEmpty()) {
  3626. // Empty sphere produces empty bounding box
  3627. target.makeEmpty();
  3628. return target;
  3629. }
  3630. target.set(this.center, this.center);
  3631. target.expandByScalar(this.radius);
  3632. return target;
  3633. }
  3634. applyMatrix4(matrix) {
  3635. this.center.applyMatrix4(matrix);
  3636. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3637. return this;
  3638. }
  3639. translate(offset) {
  3640. this.center.add(offset);
  3641. return this;
  3642. }
  3643. expandByPoint(point) {
  3644. if (this.isEmpty()) {
  3645. this.center.copy(point);
  3646. this.radius = 0;
  3647. return this;
  3648. }
  3649. _v1$6.subVectors(point, this.center);
  3650. const lengthSq = _v1$6.lengthSq();
  3651. if (lengthSq > this.radius * this.radius) {
  3652. // calculate the minimal sphere
  3653. const length = Math.sqrt(lengthSq);
  3654. const delta = (length - this.radius) * 0.5;
  3655. this.center.addScaledVector(_v1$6, delta / length);
  3656. this.radius += delta;
  3657. }
  3658. return this;
  3659. }
  3660. union(sphere) {
  3661. if (sphere.isEmpty()) {
  3662. return this;
  3663. }
  3664. if (this.isEmpty()) {
  3665. this.copy(sphere);
  3666. return this;
  3667. }
  3668. if (this.center.equals(sphere.center) === true) {
  3669. this.radius = Math.max(this.radius, sphere.radius);
  3670. } else {
  3671. _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius);
  3672. this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3));
  3673. this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3));
  3674. }
  3675. return this;
  3676. }
  3677. equals(sphere) {
  3678. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3679. }
  3680. clone() {
  3681. return new this.constructor().copy(this);
  3682. }
  3683. }
  3684. const _vector$a = /*@__PURE__*/new Vector3();
  3685. const _segCenter = /*@__PURE__*/new Vector3();
  3686. const _segDir = /*@__PURE__*/new Vector3();
  3687. const _diff = /*@__PURE__*/new Vector3();
  3688. const _edge1 = /*@__PURE__*/new Vector3();
  3689. const _edge2 = /*@__PURE__*/new Vector3();
  3690. const _normal$1 = /*@__PURE__*/new Vector3();
  3691. class Ray {
  3692. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3693. this.origin = origin;
  3694. this.direction = direction;
  3695. }
  3696. set(origin, direction) {
  3697. this.origin.copy(origin);
  3698. this.direction.copy(direction);
  3699. return this;
  3700. }
  3701. copy(ray) {
  3702. this.origin.copy(ray.origin);
  3703. this.direction.copy(ray.direction);
  3704. return this;
  3705. }
  3706. at(t, target) {
  3707. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3708. }
  3709. lookAt(v) {
  3710. this.direction.copy(v).sub(this.origin).normalize();
  3711. return this;
  3712. }
  3713. recast(t) {
  3714. this.origin.copy(this.at(t, _vector$a));
  3715. return this;
  3716. }
  3717. closestPointToPoint(point, target) {
  3718. target.subVectors(point, this.origin);
  3719. const directionDistance = target.dot(this.direction);
  3720. if (directionDistance < 0) {
  3721. return target.copy(this.origin);
  3722. }
  3723. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3724. }
  3725. distanceToPoint(point) {
  3726. return Math.sqrt(this.distanceSqToPoint(point));
  3727. }
  3728. distanceSqToPoint(point) {
  3729. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction);
  3730. // point behind the ray
  3731. if (directionDistance < 0) {
  3732. return this.origin.distanceToSquared(point);
  3733. }
  3734. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3735. return _vector$a.distanceToSquared(point);
  3736. }
  3737. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3738. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3739. // It returns the min distance between the ray and the segment
  3740. // defined by v0 and v1
  3741. // It can also set two optional targets :
  3742. // - The closest point on the ray
  3743. // - The closest point on the segment
  3744. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3745. _segDir.copy(v1).sub(v0).normalize();
  3746. _diff.copy(this.origin).sub(_segCenter);
  3747. const segExtent = v0.distanceTo(v1) * 0.5;
  3748. const a01 = -this.direction.dot(_segDir);
  3749. const b0 = _diff.dot(this.direction);
  3750. const b1 = -_diff.dot(_segDir);
  3751. const c = _diff.lengthSq();
  3752. const det = Math.abs(1 - a01 * a01);
  3753. let s0, s1, sqrDist, extDet;
  3754. if (det > 0) {
  3755. // The ray and segment are not parallel.
  3756. s0 = a01 * b1 - b0;
  3757. s1 = a01 * b0 - b1;
  3758. extDet = segExtent * det;
  3759. if (s0 >= 0) {
  3760. if (s1 >= -extDet) {
  3761. if (s1 <= extDet) {
  3762. // region 0
  3763. // Minimum at interior points of ray and segment.
  3764. const invDet = 1 / det;
  3765. s0 *= invDet;
  3766. s1 *= invDet;
  3767. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3768. } else {
  3769. // region 1
  3770. s1 = segExtent;
  3771. s0 = Math.max(0, -(a01 * s1 + b0));
  3772. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3773. }
  3774. } else {
  3775. // region 5
  3776. s1 = -segExtent;
  3777. s0 = Math.max(0, -(a01 * s1 + b0));
  3778. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3779. }
  3780. } else {
  3781. if (s1 <= -extDet) {
  3782. // region 4
  3783. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3784. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3785. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3786. } else if (s1 <= extDet) {
  3787. // region 3
  3788. s0 = 0;
  3789. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3790. sqrDist = s1 * (s1 + 2 * b1) + c;
  3791. } else {
  3792. // region 2
  3793. s0 = Math.max(0, -(a01 * segExtent + b0));
  3794. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3795. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3796. }
  3797. }
  3798. } else {
  3799. // Ray and segment are parallel.
  3800. s1 = a01 > 0 ? -segExtent : segExtent;
  3801. s0 = Math.max(0, -(a01 * s1 + b0));
  3802. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3803. }
  3804. if (optionalPointOnRay) {
  3805. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3806. }
  3807. if (optionalPointOnSegment) {
  3808. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3809. }
  3810. return sqrDist;
  3811. }
  3812. intersectSphere(sphere, target) {
  3813. _vector$a.subVectors(sphere.center, this.origin);
  3814. const tca = _vector$a.dot(this.direction);
  3815. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3816. const radius2 = sphere.radius * sphere.radius;
  3817. if (d2 > radius2) return null;
  3818. const thc = Math.sqrt(radius2 - d2);
  3819. // t0 = first intersect point - entrance on front of sphere
  3820. const t0 = tca - thc;
  3821. // t1 = second intersect point - exit point on back of sphere
  3822. const t1 = tca + thc;
  3823. // test to see if both t0 and t1 are behind the ray - if so, return null
  3824. if (t0 < 0 && t1 < 0) return null;
  3825. // test to see if t0 is behind the ray:
  3826. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3827. // in order to always return an intersect point that is in front of the ray.
  3828. if (t0 < 0) return this.at(t1, target);
  3829. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3830. return this.at(t0, target);
  3831. }
  3832. intersectsSphere(sphere) {
  3833. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3834. }
  3835. distanceToPlane(plane) {
  3836. const denominator = plane.normal.dot(this.direction);
  3837. if (denominator === 0) {
  3838. // line is coplanar, return origin
  3839. if (plane.distanceToPoint(this.origin) === 0) {
  3840. return 0;
  3841. }
  3842. // Null is preferable to undefined since undefined means.... it is undefined
  3843. return null;
  3844. }
  3845. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  3846. // Return if the ray never intersects the plane
  3847. return t >= 0 ? t : null;
  3848. }
  3849. intersectPlane(plane, target) {
  3850. const t = this.distanceToPlane(plane);
  3851. if (t === null) {
  3852. return null;
  3853. }
  3854. return this.at(t, target);
  3855. }
  3856. intersectsPlane(plane) {
  3857. // check if the ray lies on the plane first
  3858. const distToPoint = plane.distanceToPoint(this.origin);
  3859. if (distToPoint === 0) {
  3860. return true;
  3861. }
  3862. const denominator = plane.normal.dot(this.direction);
  3863. if (denominator * distToPoint < 0) {
  3864. return true;
  3865. }
  3866. // ray origin is behind the plane (and is pointing behind it)
  3867. return false;
  3868. }
  3869. intersectBox(box, target) {
  3870. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3871. const invdirx = 1 / this.direction.x,
  3872. invdiry = 1 / this.direction.y,
  3873. invdirz = 1 / this.direction.z;
  3874. const origin = this.origin;
  3875. if (invdirx >= 0) {
  3876. tmin = (box.min.x - origin.x) * invdirx;
  3877. tmax = (box.max.x - origin.x) * invdirx;
  3878. } else {
  3879. tmin = (box.max.x - origin.x) * invdirx;
  3880. tmax = (box.min.x - origin.x) * invdirx;
  3881. }
  3882. if (invdiry >= 0) {
  3883. tymin = (box.min.y - origin.y) * invdiry;
  3884. tymax = (box.max.y - origin.y) * invdiry;
  3885. } else {
  3886. tymin = (box.max.y - origin.y) * invdiry;
  3887. tymax = (box.min.y - origin.y) * invdiry;
  3888. }
  3889. if (tmin > tymax || tymin > tmax) return null;
  3890. if (tymin > tmin || isNaN(tmin)) tmin = tymin;
  3891. if (tymax < tmax || isNaN(tmax)) tmax = tymax;
  3892. if (invdirz >= 0) {
  3893. tzmin = (box.min.z - origin.z) * invdirz;
  3894. tzmax = (box.max.z - origin.z) * invdirz;
  3895. } else {
  3896. tzmin = (box.max.z - origin.z) * invdirz;
  3897. tzmax = (box.min.z - origin.z) * invdirz;
  3898. }
  3899. if (tmin > tzmax || tzmin > tmax) return null;
  3900. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3901. if (tzmax < tmax || tmax !== tmax) tmax = tzmax;
  3902. //return point closest to the ray (positive side)
  3903. if (tmax < 0) return null;
  3904. return this.at(tmin >= 0 ? tmin : tmax, target);
  3905. }
  3906. intersectsBox(box) {
  3907. return this.intersectBox(box, _vector$a) !== null;
  3908. }
  3909. intersectTriangle(a, b, c, backfaceCulling, target) {
  3910. // Compute the offset origin, edges, and normal.
  3911. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3912. _edge1.subVectors(b, a);
  3913. _edge2.subVectors(c, a);
  3914. _normal$1.crossVectors(_edge1, _edge2);
  3915. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3916. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3917. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3918. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3919. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3920. let DdN = this.direction.dot(_normal$1);
  3921. let sign;
  3922. if (DdN > 0) {
  3923. if (backfaceCulling) return null;
  3924. sign = 1;
  3925. } else if (DdN < 0) {
  3926. sign = -1;
  3927. DdN = -DdN;
  3928. } else {
  3929. return null;
  3930. }
  3931. _diff.subVectors(this.origin, a);
  3932. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2));
  3933. // b1 < 0, no intersection
  3934. if (DdQxE2 < 0) {
  3935. return null;
  3936. }
  3937. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff));
  3938. // b2 < 0, no intersection
  3939. if (DdE1xQ < 0) {
  3940. return null;
  3941. }
  3942. // b1+b2 > 1, no intersection
  3943. if (DdQxE2 + DdE1xQ > DdN) {
  3944. return null;
  3945. }
  3946. // Line intersects triangle, check if ray does.
  3947. const QdN = -sign * _diff.dot(_normal$1);
  3948. // t < 0, no intersection
  3949. if (QdN < 0) {
  3950. return null;
  3951. }
  3952. // Ray intersects triangle.
  3953. return this.at(QdN / DdN, target);
  3954. }
  3955. applyMatrix4(matrix4) {
  3956. this.origin.applyMatrix4(matrix4);
  3957. this.direction.transformDirection(matrix4);
  3958. return this;
  3959. }
  3960. equals(ray) {
  3961. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3962. }
  3963. clone() {
  3964. return new this.constructor().copy(this);
  3965. }
  3966. }
  3967. class Matrix4 {
  3968. constructor() {
  3969. Matrix4.prototype.isMatrix4 = true;
  3970. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3971. }
  3972. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3973. const te = this.elements;
  3974. te[0] = n11;
  3975. te[4] = n12;
  3976. te[8] = n13;
  3977. te[12] = n14;
  3978. te[1] = n21;
  3979. te[5] = n22;
  3980. te[9] = n23;
  3981. te[13] = n24;
  3982. te[2] = n31;
  3983. te[6] = n32;
  3984. te[10] = n33;
  3985. te[14] = n34;
  3986. te[3] = n41;
  3987. te[7] = n42;
  3988. te[11] = n43;
  3989. te[15] = n44;
  3990. return this;
  3991. }
  3992. identity() {
  3993. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3994. return this;
  3995. }
  3996. clone() {
  3997. return new Matrix4().fromArray(this.elements);
  3998. }
  3999. copy(m) {
  4000. const te = this.elements;
  4001. const me = m.elements;
  4002. te[0] = me[0];
  4003. te[1] = me[1];
  4004. te[2] = me[2];
  4005. te[3] = me[3];
  4006. te[4] = me[4];
  4007. te[5] = me[5];
  4008. te[6] = me[6];
  4009. te[7] = me[7];
  4010. te[8] = me[8];
  4011. te[9] = me[9];
  4012. te[10] = me[10];
  4013. te[11] = me[11];
  4014. te[12] = me[12];
  4015. te[13] = me[13];
  4016. te[14] = me[14];
  4017. te[15] = me[15];
  4018. return this;
  4019. }
  4020. copyPosition(m) {
  4021. const te = this.elements,
  4022. me = m.elements;
  4023. te[12] = me[12];
  4024. te[13] = me[13];
  4025. te[14] = me[14];
  4026. return this;
  4027. }
  4028. setFromMatrix3(m) {
  4029. const me = m.elements;
  4030. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  4031. return this;
  4032. }
  4033. extractBasis(xAxis, yAxis, zAxis) {
  4034. xAxis.setFromMatrixColumn(this, 0);
  4035. yAxis.setFromMatrixColumn(this, 1);
  4036. zAxis.setFromMatrixColumn(this, 2);
  4037. return this;
  4038. }
  4039. makeBasis(xAxis, yAxis, zAxis) {
  4040. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  4041. return this;
  4042. }
  4043. extractRotation(m) {
  4044. // this method does not support reflection matrices
  4045. const te = this.elements;
  4046. const me = m.elements;
  4047. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  4048. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  4049. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  4050. te[0] = me[0] * scaleX;
  4051. te[1] = me[1] * scaleX;
  4052. te[2] = me[2] * scaleX;
  4053. te[3] = 0;
  4054. te[4] = me[4] * scaleY;
  4055. te[5] = me[5] * scaleY;
  4056. te[6] = me[6] * scaleY;
  4057. te[7] = 0;
  4058. te[8] = me[8] * scaleZ;
  4059. te[9] = me[9] * scaleZ;
  4060. te[10] = me[10] * scaleZ;
  4061. te[11] = 0;
  4062. te[12] = 0;
  4063. te[13] = 0;
  4064. te[14] = 0;
  4065. te[15] = 1;
  4066. return this;
  4067. }
  4068. makeRotationFromEuler(euler) {
  4069. const te = this.elements;
  4070. const x = euler.x,
  4071. y = euler.y,
  4072. z = euler.z;
  4073. const a = Math.cos(x),
  4074. b = Math.sin(x);
  4075. const c = Math.cos(y),
  4076. d = Math.sin(y);
  4077. const e = Math.cos(z),
  4078. f = Math.sin(z);
  4079. if (euler.order === 'XYZ') {
  4080. const ae = a * e,
  4081. af = a * f,
  4082. be = b * e,
  4083. bf = b * f;
  4084. te[0] = c * e;
  4085. te[4] = -c * f;
  4086. te[8] = d;
  4087. te[1] = af + be * d;
  4088. te[5] = ae - bf * d;
  4089. te[9] = -b * c;
  4090. te[2] = bf - ae * d;
  4091. te[6] = be + af * d;
  4092. te[10] = a * c;
  4093. } else if (euler.order === 'YXZ') {
  4094. const ce = c * e,
  4095. cf = c * f,
  4096. de = d * e,
  4097. df = d * f;
  4098. te[0] = ce + df * b;
  4099. te[4] = de * b - cf;
  4100. te[8] = a * d;
  4101. te[1] = a * f;
  4102. te[5] = a * e;
  4103. te[9] = -b;
  4104. te[2] = cf * b - de;
  4105. te[6] = df + ce * b;
  4106. te[10] = a * c;
  4107. } else if (euler.order === 'ZXY') {
  4108. const ce = c * e,
  4109. cf = c * f,
  4110. de = d * e,
  4111. df = d * f;
  4112. te[0] = ce - df * b;
  4113. te[4] = -a * f;
  4114. te[8] = de + cf * b;
  4115. te[1] = cf + de * b;
  4116. te[5] = a * e;
  4117. te[9] = df - ce * b;
  4118. te[2] = -a * d;
  4119. te[6] = b;
  4120. te[10] = a * c;
  4121. } else if (euler.order === 'ZYX') {
  4122. const ae = a * e,
  4123. af = a * f,
  4124. be = b * e,
  4125. bf = b * f;
  4126. te[0] = c * e;
  4127. te[4] = be * d - af;
  4128. te[8] = ae * d + bf;
  4129. te[1] = c * f;
  4130. te[5] = bf * d + ae;
  4131. te[9] = af * d - be;
  4132. te[2] = -d;
  4133. te[6] = b * c;
  4134. te[10] = a * c;
  4135. } else if (euler.order === 'YZX') {
  4136. const ac = a * c,
  4137. ad = a * d,
  4138. bc = b * c,
  4139. bd = b * d;
  4140. te[0] = c * e;
  4141. te[4] = bd - ac * f;
  4142. te[8] = bc * f + ad;
  4143. te[1] = f;
  4144. te[5] = a * e;
  4145. te[9] = -b * e;
  4146. te[2] = -d * e;
  4147. te[6] = ad * f + bc;
  4148. te[10] = ac - bd * f;
  4149. } else if (euler.order === 'XZY') {
  4150. const ac = a * c,
  4151. ad = a * d,
  4152. bc = b * c,
  4153. bd = b * d;
  4154. te[0] = c * e;
  4155. te[4] = -f;
  4156. te[8] = d * e;
  4157. te[1] = ac * f + bd;
  4158. te[5] = a * e;
  4159. te[9] = ad * f - bc;
  4160. te[2] = bc * f - ad;
  4161. te[6] = b * e;
  4162. te[10] = bd * f + ac;
  4163. }
  4164. // bottom row
  4165. te[3] = 0;
  4166. te[7] = 0;
  4167. te[11] = 0;
  4168. // last column
  4169. te[12] = 0;
  4170. te[13] = 0;
  4171. te[14] = 0;
  4172. te[15] = 1;
  4173. return this;
  4174. }
  4175. makeRotationFromQuaternion(q) {
  4176. return this.compose(_zero, q, _one);
  4177. }
  4178. lookAt(eye, target, up) {
  4179. const te = this.elements;
  4180. _z.subVectors(eye, target);
  4181. if (_z.lengthSq() === 0) {
  4182. // eye and target are in the same position
  4183. _z.z = 1;
  4184. }
  4185. _z.normalize();
  4186. _x.crossVectors(up, _z);
  4187. if (_x.lengthSq() === 0) {
  4188. // up and z are parallel
  4189. if (Math.abs(up.z) === 1) {
  4190. _z.x += 0.0001;
  4191. } else {
  4192. _z.z += 0.0001;
  4193. }
  4194. _z.normalize();
  4195. _x.crossVectors(up, _z);
  4196. }
  4197. _x.normalize();
  4198. _y.crossVectors(_z, _x);
  4199. te[0] = _x.x;
  4200. te[4] = _y.x;
  4201. te[8] = _z.x;
  4202. te[1] = _x.y;
  4203. te[5] = _y.y;
  4204. te[9] = _z.y;
  4205. te[2] = _x.z;
  4206. te[6] = _y.z;
  4207. te[10] = _z.z;
  4208. return this;
  4209. }
  4210. multiply(m) {
  4211. return this.multiplyMatrices(this, m);
  4212. }
  4213. premultiply(m) {
  4214. return this.multiplyMatrices(m, this);
  4215. }
  4216. multiplyMatrices(a, b) {
  4217. const ae = a.elements;
  4218. const be = b.elements;
  4219. const te = this.elements;
  4220. const a11 = ae[0],
  4221. a12 = ae[4],
  4222. a13 = ae[8],
  4223. a14 = ae[12];
  4224. const a21 = ae[1],
  4225. a22 = ae[5],
  4226. a23 = ae[9],
  4227. a24 = ae[13];
  4228. const a31 = ae[2],
  4229. a32 = ae[6],
  4230. a33 = ae[10],
  4231. a34 = ae[14];
  4232. const a41 = ae[3],
  4233. a42 = ae[7],
  4234. a43 = ae[11],
  4235. a44 = ae[15];
  4236. const b11 = be[0],
  4237. b12 = be[4],
  4238. b13 = be[8],
  4239. b14 = be[12];
  4240. const b21 = be[1],
  4241. b22 = be[5],
  4242. b23 = be[9],
  4243. b24 = be[13];
  4244. const b31 = be[2],
  4245. b32 = be[6],
  4246. b33 = be[10],
  4247. b34 = be[14];
  4248. const b41 = be[3],
  4249. b42 = be[7],
  4250. b43 = be[11],
  4251. b44 = be[15];
  4252. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4253. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4254. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4255. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4256. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4257. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4258. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4259. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4260. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4261. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4262. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4263. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4264. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4265. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4266. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4267. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4268. return this;
  4269. }
  4270. multiplyScalar(s) {
  4271. const te = this.elements;
  4272. te[0] *= s;
  4273. te[4] *= s;
  4274. te[8] *= s;
  4275. te[12] *= s;
  4276. te[1] *= s;
  4277. te[5] *= s;
  4278. te[9] *= s;
  4279. te[13] *= s;
  4280. te[2] *= s;
  4281. te[6] *= s;
  4282. te[10] *= s;
  4283. te[14] *= s;
  4284. te[3] *= s;
  4285. te[7] *= s;
  4286. te[11] *= s;
  4287. te[15] *= s;
  4288. return this;
  4289. }
  4290. determinant() {
  4291. const te = this.elements;
  4292. const n11 = te[0],
  4293. n12 = te[4],
  4294. n13 = te[8],
  4295. n14 = te[12];
  4296. const n21 = te[1],
  4297. n22 = te[5],
  4298. n23 = te[9],
  4299. n24 = te[13];
  4300. const n31 = te[2],
  4301. n32 = te[6],
  4302. n33 = te[10],
  4303. n34 = te[14];
  4304. const n41 = te[3],
  4305. n42 = te[7],
  4306. n43 = te[11],
  4307. n44 = te[15];
  4308. //TODO: make this more efficient
  4309. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4310. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  4311. }
  4312. transpose() {
  4313. const te = this.elements;
  4314. let tmp;
  4315. tmp = te[1];
  4316. te[1] = te[4];
  4317. te[4] = tmp;
  4318. tmp = te[2];
  4319. te[2] = te[8];
  4320. te[8] = tmp;
  4321. tmp = te[6];
  4322. te[6] = te[9];
  4323. te[9] = tmp;
  4324. tmp = te[3];
  4325. te[3] = te[12];
  4326. te[12] = tmp;
  4327. tmp = te[7];
  4328. te[7] = te[13];
  4329. te[13] = tmp;
  4330. tmp = te[11];
  4331. te[11] = te[14];
  4332. te[14] = tmp;
  4333. return this;
  4334. }
  4335. setPosition(x, y, z) {
  4336. const te = this.elements;
  4337. if (x.isVector3) {
  4338. te[12] = x.x;
  4339. te[13] = x.y;
  4340. te[14] = x.z;
  4341. } else {
  4342. te[12] = x;
  4343. te[13] = y;
  4344. te[14] = z;
  4345. }
  4346. return this;
  4347. }
  4348. invert() {
  4349. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4350. const te = this.elements,
  4351. n11 = te[0],
  4352. n21 = te[1],
  4353. n31 = te[2],
  4354. n41 = te[3],
  4355. n12 = te[4],
  4356. n22 = te[5],
  4357. n32 = te[6],
  4358. n42 = te[7],
  4359. n13 = te[8],
  4360. n23 = te[9],
  4361. n33 = te[10],
  4362. n43 = te[11],
  4363. n14 = te[12],
  4364. n24 = te[13],
  4365. n34 = te[14],
  4366. n44 = te[15],
  4367. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4368. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4369. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4370. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4371. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4372. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4373. const detInv = 1 / det;
  4374. te[0] = t11 * detInv;
  4375. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4376. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4377. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4378. te[4] = t12 * detInv;
  4379. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4380. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4381. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4382. te[8] = t13 * detInv;
  4383. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4384. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4385. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4386. te[12] = t14 * detInv;
  4387. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4388. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4389. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4390. return this;
  4391. }
  4392. scale(v) {
  4393. const te = this.elements;
  4394. const x = v.x,
  4395. y = v.y,
  4396. z = v.z;
  4397. te[0] *= x;
  4398. te[4] *= y;
  4399. te[8] *= z;
  4400. te[1] *= x;
  4401. te[5] *= y;
  4402. te[9] *= z;
  4403. te[2] *= x;
  4404. te[6] *= y;
  4405. te[10] *= z;
  4406. te[3] *= x;
  4407. te[7] *= y;
  4408. te[11] *= z;
  4409. return this;
  4410. }
  4411. getMaxScaleOnAxis() {
  4412. const te = this.elements;
  4413. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4414. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4415. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4416. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4417. }
  4418. makeTranslation(x, y, z) {
  4419. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4420. return this;
  4421. }
  4422. makeRotationX(theta) {
  4423. const c = Math.cos(theta),
  4424. s = Math.sin(theta);
  4425. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4426. return this;
  4427. }
  4428. makeRotationY(theta) {
  4429. const c = Math.cos(theta),
  4430. s = Math.sin(theta);
  4431. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4432. return this;
  4433. }
  4434. makeRotationZ(theta) {
  4435. const c = Math.cos(theta),
  4436. s = Math.sin(theta);
  4437. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4438. return this;
  4439. }
  4440. makeRotationAxis(axis, angle) {
  4441. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4442. const c = Math.cos(angle);
  4443. const s = Math.sin(angle);
  4444. const t = 1 - c;
  4445. const x = axis.x,
  4446. y = axis.y,
  4447. z = axis.z;
  4448. const tx = t * x,
  4449. ty = t * y;
  4450. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  4451. return this;
  4452. }
  4453. makeScale(x, y, z) {
  4454. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4455. return this;
  4456. }
  4457. makeShear(xy, xz, yx, yz, zx, zy) {
  4458. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4459. return this;
  4460. }
  4461. compose(position, quaternion, scale) {
  4462. const te = this.elements;
  4463. const x = quaternion._x,
  4464. y = quaternion._y,
  4465. z = quaternion._z,
  4466. w = quaternion._w;
  4467. const x2 = x + x,
  4468. y2 = y + y,
  4469. z2 = z + z;
  4470. const xx = x * x2,
  4471. xy = x * y2,
  4472. xz = x * z2;
  4473. const yy = y * y2,
  4474. yz = y * z2,
  4475. zz = z * z2;
  4476. const wx = w * x2,
  4477. wy = w * y2,
  4478. wz = w * z2;
  4479. const sx = scale.x,
  4480. sy = scale.y,
  4481. sz = scale.z;
  4482. te[0] = (1 - (yy + zz)) * sx;
  4483. te[1] = (xy + wz) * sx;
  4484. te[2] = (xz - wy) * sx;
  4485. te[3] = 0;
  4486. te[4] = (xy - wz) * sy;
  4487. te[5] = (1 - (xx + zz)) * sy;
  4488. te[6] = (yz + wx) * sy;
  4489. te[7] = 0;
  4490. te[8] = (xz + wy) * sz;
  4491. te[9] = (yz - wx) * sz;
  4492. te[10] = (1 - (xx + yy)) * sz;
  4493. te[11] = 0;
  4494. te[12] = position.x;
  4495. te[13] = position.y;
  4496. te[14] = position.z;
  4497. te[15] = 1;
  4498. return this;
  4499. }
  4500. decompose(position, quaternion, scale) {
  4501. const te = this.elements;
  4502. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4503. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4504. const sz = _v1$5.set(te[8], te[9], te[10]).length();
  4505. // if determine is negative, we need to invert one scale
  4506. const det = this.determinant();
  4507. if (det < 0) sx = -sx;
  4508. position.x = te[12];
  4509. position.y = te[13];
  4510. position.z = te[14];
  4511. // scale the rotation part
  4512. _m1$2.copy(this);
  4513. const invSX = 1 / sx;
  4514. const invSY = 1 / sy;
  4515. const invSZ = 1 / sz;
  4516. _m1$2.elements[0] *= invSX;
  4517. _m1$2.elements[1] *= invSX;
  4518. _m1$2.elements[2] *= invSX;
  4519. _m1$2.elements[4] *= invSY;
  4520. _m1$2.elements[5] *= invSY;
  4521. _m1$2.elements[6] *= invSY;
  4522. _m1$2.elements[8] *= invSZ;
  4523. _m1$2.elements[9] *= invSZ;
  4524. _m1$2.elements[10] *= invSZ;
  4525. quaternion.setFromRotationMatrix(_m1$2);
  4526. scale.x = sx;
  4527. scale.y = sy;
  4528. scale.z = sz;
  4529. return this;
  4530. }
  4531. makePerspective(left, right, top, bottom, near, far) {
  4532. const te = this.elements;
  4533. const x = 2 * near / (right - left);
  4534. const y = 2 * near / (top - bottom);
  4535. const a = (right + left) / (right - left);
  4536. const b = (top + bottom) / (top - bottom);
  4537. const c = -(far + near) / (far - near);
  4538. const d = -2 * far * near / (far - near);
  4539. te[0] = x;
  4540. te[4] = 0;
  4541. te[8] = a;
  4542. te[12] = 0;
  4543. te[1] = 0;
  4544. te[5] = y;
  4545. te[9] = b;
  4546. te[13] = 0;
  4547. te[2] = 0;
  4548. te[6] = 0;
  4549. te[10] = c;
  4550. te[14] = d;
  4551. te[3] = 0;
  4552. te[7] = 0;
  4553. te[11] = -1;
  4554. te[15] = 0;
  4555. return this;
  4556. }
  4557. makeOrthographic(left, right, top, bottom, near, far) {
  4558. const te = this.elements;
  4559. const w = 1.0 / (right - left);
  4560. const h = 1.0 / (top - bottom);
  4561. const p = 1.0 / (far - near);
  4562. const x = (right + left) * w;
  4563. const y = (top + bottom) * h;
  4564. const z = (far + near) * p;
  4565. te[0] = 2 * w;
  4566. te[4] = 0;
  4567. te[8] = 0;
  4568. te[12] = -x;
  4569. te[1] = 0;
  4570. te[5] = 2 * h;
  4571. te[9] = 0;
  4572. te[13] = -y;
  4573. te[2] = 0;
  4574. te[6] = 0;
  4575. te[10] = -2 * p;
  4576. te[14] = -z;
  4577. te[3] = 0;
  4578. te[7] = 0;
  4579. te[11] = 0;
  4580. te[15] = 1;
  4581. return this;
  4582. }
  4583. equals(matrix) {
  4584. const te = this.elements;
  4585. const me = matrix.elements;
  4586. for (let i = 0; i < 16; i++) {
  4587. if (te[i] !== me[i]) return false;
  4588. }
  4589. return true;
  4590. }
  4591. fromArray(array, offset = 0) {
  4592. for (let i = 0; i < 16; i++) {
  4593. this.elements[i] = array[i + offset];
  4594. }
  4595. return this;
  4596. }
  4597. toArray(array = [], offset = 0) {
  4598. const te = this.elements;
  4599. array[offset] = te[0];
  4600. array[offset + 1] = te[1];
  4601. array[offset + 2] = te[2];
  4602. array[offset + 3] = te[3];
  4603. array[offset + 4] = te[4];
  4604. array[offset + 5] = te[5];
  4605. array[offset + 6] = te[6];
  4606. array[offset + 7] = te[7];
  4607. array[offset + 8] = te[8];
  4608. array[offset + 9] = te[9];
  4609. array[offset + 10] = te[10];
  4610. array[offset + 11] = te[11];
  4611. array[offset + 12] = te[12];
  4612. array[offset + 13] = te[13];
  4613. array[offset + 14] = te[14];
  4614. array[offset + 15] = te[15];
  4615. return array;
  4616. }
  4617. }
  4618. const _v1$5 = /*@__PURE__*/new Vector3();
  4619. const _m1$2 = /*@__PURE__*/new Matrix4();
  4620. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4621. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4622. const _x = /*@__PURE__*/new Vector3();
  4623. const _y = /*@__PURE__*/new Vector3();
  4624. const _z = /*@__PURE__*/new Vector3();
  4625. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4626. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4627. class Euler {
  4628. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4629. this.isEuler = true;
  4630. this._x = x;
  4631. this._y = y;
  4632. this._z = z;
  4633. this._order = order;
  4634. }
  4635. get x() {
  4636. return this._x;
  4637. }
  4638. set x(value) {
  4639. this._x = value;
  4640. this._onChangeCallback();
  4641. }
  4642. get y() {
  4643. return this._y;
  4644. }
  4645. set y(value) {
  4646. this._y = value;
  4647. this._onChangeCallback();
  4648. }
  4649. get z() {
  4650. return this._z;
  4651. }
  4652. set z(value) {
  4653. this._z = value;
  4654. this._onChangeCallback();
  4655. }
  4656. get order() {
  4657. return this._order;
  4658. }
  4659. set order(value) {
  4660. this._order = value;
  4661. this._onChangeCallback();
  4662. }
  4663. set(x, y, z, order = this._order) {
  4664. this._x = x;
  4665. this._y = y;
  4666. this._z = z;
  4667. this._order = order;
  4668. this._onChangeCallback();
  4669. return this;
  4670. }
  4671. clone() {
  4672. return new this.constructor(this._x, this._y, this._z, this._order);
  4673. }
  4674. copy(euler) {
  4675. this._x = euler._x;
  4676. this._y = euler._y;
  4677. this._z = euler._z;
  4678. this._order = euler._order;
  4679. this._onChangeCallback();
  4680. return this;
  4681. }
  4682. setFromRotationMatrix(m, order = this._order, update = true) {
  4683. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4684. const te = m.elements;
  4685. const m11 = te[0],
  4686. m12 = te[4],
  4687. m13 = te[8];
  4688. const m21 = te[1],
  4689. m22 = te[5],
  4690. m23 = te[9];
  4691. const m31 = te[2],
  4692. m32 = te[6],
  4693. m33 = te[10];
  4694. switch (order) {
  4695. case 'XYZ':
  4696. this._y = Math.asin(clamp(m13, -1, 1));
  4697. if (Math.abs(m13) < 0.9999999) {
  4698. this._x = Math.atan2(-m23, m33);
  4699. this._z = Math.atan2(-m12, m11);
  4700. } else {
  4701. this._x = Math.atan2(m32, m22);
  4702. this._z = 0;
  4703. }
  4704. break;
  4705. case 'YXZ':
  4706. this._x = Math.asin(-clamp(m23, -1, 1));
  4707. if (Math.abs(m23) < 0.9999999) {
  4708. this._y = Math.atan2(m13, m33);
  4709. this._z = Math.atan2(m21, m22);
  4710. } else {
  4711. this._y = Math.atan2(-m31, m11);
  4712. this._z = 0;
  4713. }
  4714. break;
  4715. case 'ZXY':
  4716. this._x = Math.asin(clamp(m32, -1, 1));
  4717. if (Math.abs(m32) < 0.9999999) {
  4718. this._y = Math.atan2(-m31, m33);
  4719. this._z = Math.atan2(-m12, m22);
  4720. } else {
  4721. this._y = 0;
  4722. this._z = Math.atan2(m21, m11);
  4723. }
  4724. break;
  4725. case 'ZYX':
  4726. this._y = Math.asin(-clamp(m31, -1, 1));
  4727. if (Math.abs(m31) < 0.9999999) {
  4728. this._x = Math.atan2(m32, m33);
  4729. this._z = Math.atan2(m21, m11);
  4730. } else {
  4731. this._x = 0;
  4732. this._z = Math.atan2(-m12, m22);
  4733. }
  4734. break;
  4735. case 'YZX':
  4736. this._z = Math.asin(clamp(m21, -1, 1));
  4737. if (Math.abs(m21) < 0.9999999) {
  4738. this._x = Math.atan2(-m23, m22);
  4739. this._y = Math.atan2(-m31, m11);
  4740. } else {
  4741. this._x = 0;
  4742. this._y = Math.atan2(m13, m33);
  4743. }
  4744. break;
  4745. case 'XZY':
  4746. this._z = Math.asin(-clamp(m12, -1, 1));
  4747. if (Math.abs(m12) < 0.9999999) {
  4748. this._x = Math.atan2(m32, m22);
  4749. this._y = Math.atan2(m13, m11);
  4750. } else {
  4751. this._x = Math.atan2(-m23, m33);
  4752. this._y = 0;
  4753. }
  4754. break;
  4755. default:
  4756. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4757. }
  4758. this._order = order;
  4759. if (update === true) this._onChangeCallback();
  4760. return this;
  4761. }
  4762. setFromQuaternion(q, order, update) {
  4763. _matrix$1.makeRotationFromQuaternion(q);
  4764. return this.setFromRotationMatrix(_matrix$1, order, update);
  4765. }
  4766. setFromVector3(v, order = this._order) {
  4767. return this.set(v.x, v.y, v.z, order);
  4768. }
  4769. reorder(newOrder) {
  4770. // WARNING: this discards revolution information -bhouston
  4771. _quaternion$3.setFromEuler(this);
  4772. return this.setFromQuaternion(_quaternion$3, newOrder);
  4773. }
  4774. equals(euler) {
  4775. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4776. }
  4777. fromArray(array) {
  4778. this._x = array[0];
  4779. this._y = array[1];
  4780. this._z = array[2];
  4781. if (array[3] !== undefined) this._order = array[3];
  4782. this._onChangeCallback();
  4783. return this;
  4784. }
  4785. toArray(array = [], offset = 0) {
  4786. array[offset] = this._x;
  4787. array[offset + 1] = this._y;
  4788. array[offset + 2] = this._z;
  4789. array[offset + 3] = this._order;
  4790. return array;
  4791. }
  4792. _onChange(callback) {
  4793. this._onChangeCallback = callback;
  4794. return this;
  4795. }
  4796. _onChangeCallback() {}
  4797. *[Symbol.iterator]() {
  4798. yield this._x;
  4799. yield this._y;
  4800. yield this._z;
  4801. yield this._order;
  4802. }
  4803. // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4804. toVector3() {
  4805. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4806. }
  4807. }
  4808. Euler.DefaultOrder = 'XYZ';
  4809. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4810. class Layers {
  4811. constructor() {
  4812. this.mask = 1 | 0;
  4813. }
  4814. set(channel) {
  4815. this.mask = (1 << channel | 0) >>> 0;
  4816. }
  4817. enable(channel) {
  4818. this.mask |= 1 << channel | 0;
  4819. }
  4820. enableAll() {
  4821. this.mask = 0xffffffff | 0;
  4822. }
  4823. toggle(channel) {
  4824. this.mask ^= 1 << channel | 0;
  4825. }
  4826. disable(channel) {
  4827. this.mask &= ~(1 << channel | 0);
  4828. }
  4829. disableAll() {
  4830. this.mask = 0;
  4831. }
  4832. test(layers) {
  4833. return (this.mask & layers.mask) !== 0;
  4834. }
  4835. isEnabled(channel) {
  4836. return (this.mask & (1 << channel | 0)) !== 0;
  4837. }
  4838. }
  4839. let _object3DId = 0;
  4840. const _v1$4 = /*@__PURE__*/new Vector3();
  4841. const _q1 = /*@__PURE__*/new Quaternion();
  4842. const _m1$1 = /*@__PURE__*/new Matrix4();
  4843. const _target = /*@__PURE__*/new Vector3();
  4844. const _position$3 = /*@__PURE__*/new Vector3();
  4845. const _scale$2 = /*@__PURE__*/new Vector3();
  4846. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4847. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4848. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4849. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4850. const _addedEvent = {
  4851. type: 'added'
  4852. };
  4853. const _removedEvent = {
  4854. type: 'removed'
  4855. };
  4856. class Object3D extends EventDispatcher {
  4857. constructor() {
  4858. super();
  4859. this.isObject3D = true;
  4860. Object.defineProperty(this, 'id', {
  4861. value: _object3DId++
  4862. });
  4863. this.uuid = generateUUID();
  4864. this.name = '';
  4865. this.type = 'Object3D';
  4866. this.parent = null;
  4867. this.children = [];
  4868. this.up = Object3D.DefaultUp.clone();
  4869. const position = new Vector3();
  4870. const rotation = new Euler();
  4871. const quaternion = new Quaternion();
  4872. const scale = new Vector3(1, 1, 1);
  4873. function onRotationChange() {
  4874. quaternion.setFromEuler(rotation, false);
  4875. }
  4876. function onQuaternionChange() {
  4877. rotation.setFromQuaternion(quaternion, undefined, false);
  4878. }
  4879. rotation._onChange(onRotationChange);
  4880. quaternion._onChange(onQuaternionChange);
  4881. Object.defineProperties(this, {
  4882. position: {
  4883. configurable: true,
  4884. enumerable: true,
  4885. value: position
  4886. },
  4887. rotation: {
  4888. configurable: true,
  4889. enumerable: true,
  4890. value: rotation
  4891. },
  4892. quaternion: {
  4893. configurable: true,
  4894. enumerable: true,
  4895. value: quaternion
  4896. },
  4897. scale: {
  4898. configurable: true,
  4899. enumerable: true,
  4900. value: scale
  4901. },
  4902. modelViewMatrix: {
  4903. value: new Matrix4()
  4904. },
  4905. normalMatrix: {
  4906. value: new Matrix3()
  4907. }
  4908. });
  4909. this.matrix = new Matrix4();
  4910. this.matrixWorld = new Matrix4();
  4911. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4912. this.matrixWorldNeedsUpdate = false;
  4913. this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer
  4914. this.layers = new Layers();
  4915. this.visible = true;
  4916. this.castShadow = false;
  4917. this.receiveShadow = false;
  4918. this.frustumCulled = true;
  4919. this.renderOrder = 0;
  4920. this.animations = [];
  4921. this.userData = {};
  4922. }
  4923. onBeforeRender() {}
  4924. onAfterRender() {}
  4925. applyMatrix4(matrix) {
  4926. if (this.matrixAutoUpdate) this.updateMatrix();
  4927. this.matrix.premultiply(matrix);
  4928. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4929. }
  4930. applyQuaternion(q) {
  4931. this.quaternion.premultiply(q);
  4932. return this;
  4933. }
  4934. setRotationFromAxisAngle(axis, angle) {
  4935. // assumes axis is normalized
  4936. this.quaternion.setFromAxisAngle(axis, angle);
  4937. }
  4938. setRotationFromEuler(euler) {
  4939. this.quaternion.setFromEuler(euler, true);
  4940. }
  4941. setRotationFromMatrix(m) {
  4942. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4943. this.quaternion.setFromRotationMatrix(m);
  4944. }
  4945. setRotationFromQuaternion(q) {
  4946. // assumes q is normalized
  4947. this.quaternion.copy(q);
  4948. }
  4949. rotateOnAxis(axis, angle) {
  4950. // rotate object on axis in object space
  4951. // axis is assumed to be normalized
  4952. _q1.setFromAxisAngle(axis, angle);
  4953. this.quaternion.multiply(_q1);
  4954. return this;
  4955. }
  4956. rotateOnWorldAxis(axis, angle) {
  4957. // rotate object on axis in world space
  4958. // axis is assumed to be normalized
  4959. // method assumes no rotated parent
  4960. _q1.setFromAxisAngle(axis, angle);
  4961. this.quaternion.premultiply(_q1);
  4962. return this;
  4963. }
  4964. rotateX(angle) {
  4965. return this.rotateOnAxis(_xAxis, angle);
  4966. }
  4967. rotateY(angle) {
  4968. return this.rotateOnAxis(_yAxis, angle);
  4969. }
  4970. rotateZ(angle) {
  4971. return this.rotateOnAxis(_zAxis, angle);
  4972. }
  4973. translateOnAxis(axis, distance) {
  4974. // translate object by distance along axis in object space
  4975. // axis is assumed to be normalized
  4976. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4977. this.position.add(_v1$4.multiplyScalar(distance));
  4978. return this;
  4979. }
  4980. translateX(distance) {
  4981. return this.translateOnAxis(_xAxis, distance);
  4982. }
  4983. translateY(distance) {
  4984. return this.translateOnAxis(_yAxis, distance);
  4985. }
  4986. translateZ(distance) {
  4987. return this.translateOnAxis(_zAxis, distance);
  4988. }
  4989. localToWorld(vector) {
  4990. return vector.applyMatrix4(this.matrixWorld);
  4991. }
  4992. worldToLocal(vector) {
  4993. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4994. }
  4995. lookAt(x, y, z) {
  4996. // This method does not support objects having non-uniformly-scaled parent(s)
  4997. if (x.isVector3) {
  4998. _target.copy(x);
  4999. } else {
  5000. _target.set(x, y, z);
  5001. }
  5002. const parent = this.parent;
  5003. this.updateWorldMatrix(true, false);
  5004. _position$3.setFromMatrixPosition(this.matrixWorld);
  5005. if (this.isCamera || this.isLight) {
  5006. _m1$1.lookAt(_position$3, _target, this.up);
  5007. } else {
  5008. _m1$1.lookAt(_target, _position$3, this.up);
  5009. }
  5010. this.quaternion.setFromRotationMatrix(_m1$1);
  5011. if (parent) {
  5012. _m1$1.extractRotation(parent.matrixWorld);
  5013. _q1.setFromRotationMatrix(_m1$1);
  5014. this.quaternion.premultiply(_q1.invert());
  5015. }
  5016. }
  5017. add(object) {
  5018. if (arguments.length > 1) {
  5019. for (let i = 0; i < arguments.length; i++) {
  5020. this.add(arguments[i]);
  5021. }
  5022. return this;
  5023. }
  5024. if (object === this) {
  5025. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  5026. return this;
  5027. }
  5028. if (object && object.isObject3D) {
  5029. if (object.parent !== null) {
  5030. object.parent.remove(object);
  5031. }
  5032. object.parent = this;
  5033. this.children.push(object);
  5034. object.dispatchEvent(_addedEvent);
  5035. } else {
  5036. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  5037. }
  5038. return this;
  5039. }
  5040. remove(object) {
  5041. if (arguments.length > 1) {
  5042. for (let i = 0; i < arguments.length; i++) {
  5043. this.remove(arguments[i]);
  5044. }
  5045. return this;
  5046. }
  5047. const index = this.children.indexOf(object);
  5048. if (index !== -1) {
  5049. object.parent = null;
  5050. this.children.splice(index, 1);
  5051. object.dispatchEvent(_removedEvent);
  5052. }
  5053. return this;
  5054. }
  5055. removeFromParent() {
  5056. const parent = this.parent;
  5057. if (parent !== null) {
  5058. parent.remove(this);
  5059. }
  5060. return this;
  5061. }
  5062. clear() {
  5063. for (let i = 0; i < this.children.length; i++) {
  5064. const object = this.children[i];
  5065. object.parent = null;
  5066. object.dispatchEvent(_removedEvent);
  5067. }
  5068. this.children.length = 0;
  5069. return this;
  5070. }
  5071. attach(object) {
  5072. // adds object as a child of this, while maintaining the object's world transform
  5073. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5074. this.updateWorldMatrix(true, false);
  5075. _m1$1.copy(this.matrixWorld).invert();
  5076. if (object.parent !== null) {
  5077. object.parent.updateWorldMatrix(true, false);
  5078. _m1$1.multiply(object.parent.matrixWorld);
  5079. }
  5080. object.applyMatrix4(_m1$1);
  5081. this.add(object);
  5082. object.updateWorldMatrix(false, true);
  5083. return this;
  5084. }
  5085. getObjectById(id) {
  5086. return this.getObjectByProperty('id', id);
  5087. }
  5088. getObjectByName(name) {
  5089. return this.getObjectByProperty('name', name);
  5090. }
  5091. getObjectByProperty(name, value) {
  5092. if (this[name] === value) return this;
  5093. for (let i = 0, l = this.children.length; i < l; i++) {
  5094. const child = this.children[i];
  5095. const object = child.getObjectByProperty(name, value);
  5096. if (object !== undefined) {
  5097. return object;
  5098. }
  5099. }
  5100. return undefined;
  5101. }
  5102. getWorldPosition(target) {
  5103. this.updateWorldMatrix(true, false);
  5104. return target.setFromMatrixPosition(this.matrixWorld);
  5105. }
  5106. getWorldQuaternion(target) {
  5107. this.updateWorldMatrix(true, false);
  5108. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5109. return target;
  5110. }
  5111. getWorldScale(target) {
  5112. this.updateWorldMatrix(true, false);
  5113. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5114. return target;
  5115. }
  5116. getWorldDirection(target) {
  5117. this.updateWorldMatrix(true, false);
  5118. const e = this.matrixWorld.elements;
  5119. return target.set(e[8], e[9], e[10]).normalize();
  5120. }
  5121. raycast() {}
  5122. traverse(callback) {
  5123. callback(this);
  5124. const children = this.children;
  5125. for (let i = 0, l = children.length; i < l; i++) {
  5126. children[i].traverse(callback);
  5127. }
  5128. }
  5129. traverseVisible(callback) {
  5130. if (this.visible === false) return;
  5131. callback(this);
  5132. const children = this.children;
  5133. for (let i = 0, l = children.length; i < l; i++) {
  5134. children[i].traverseVisible(callback);
  5135. }
  5136. }
  5137. traverseAncestors(callback) {
  5138. const parent = this.parent;
  5139. if (parent !== null) {
  5140. callback(parent);
  5141. parent.traverseAncestors(callback);
  5142. }
  5143. }
  5144. updateMatrix() {
  5145. this.matrix.compose(this.position, this.quaternion, this.scale);
  5146. this.matrixWorldNeedsUpdate = true;
  5147. }
  5148. updateMatrixWorld(force) {
  5149. if (this.matrixAutoUpdate) this.updateMatrix();
  5150. if (this.matrixWorldNeedsUpdate || force) {
  5151. if (this.parent === null) {
  5152. this.matrixWorld.copy(this.matrix);
  5153. } else {
  5154. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5155. }
  5156. this.matrixWorldNeedsUpdate = false;
  5157. force = true;
  5158. }
  5159. // update children
  5160. const children = this.children;
  5161. for (let i = 0, l = children.length; i < l; i++) {
  5162. const child = children[i];
  5163. if (child.matrixWorldAutoUpdate === true || force === true) {
  5164. child.updateMatrixWorld(force);
  5165. }
  5166. }
  5167. }
  5168. updateWorldMatrix(updateParents, updateChildren) {
  5169. const parent = this.parent;
  5170. if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) {
  5171. parent.updateWorldMatrix(true, false);
  5172. }
  5173. if (this.matrixAutoUpdate) this.updateMatrix();
  5174. if (this.parent === null) {
  5175. this.matrixWorld.copy(this.matrix);
  5176. } else {
  5177. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5178. }
  5179. // update children
  5180. if (updateChildren === true) {
  5181. const children = this.children;
  5182. for (let i = 0, l = children.length; i < l; i++) {
  5183. const child = children[i];
  5184. if (child.matrixWorldAutoUpdate === true) {
  5185. child.updateWorldMatrix(false, true);
  5186. }
  5187. }
  5188. }
  5189. }
  5190. toJSON(meta) {
  5191. // meta is a string when called from JSON.stringify
  5192. const isRootObject = meta === undefined || typeof meta === 'string';
  5193. const output = {};
  5194. // meta is a hash used to collect geometries, materials.
  5195. // not providing it implies that this is the root object
  5196. // being serialized.
  5197. if (isRootObject) {
  5198. // initialize meta obj
  5199. meta = {
  5200. geometries: {},
  5201. materials: {},
  5202. textures: {},
  5203. images: {},
  5204. shapes: {},
  5205. skeletons: {},
  5206. animations: {},
  5207. nodes: {}
  5208. };
  5209. output.metadata = {
  5210. version: 4.5,
  5211. type: 'Object',
  5212. generator: 'Object3D.toJSON'
  5213. };
  5214. }
  5215. // standard Object3D serialization
  5216. const object = {};
  5217. object.uuid = this.uuid;
  5218. object.type = this.type;
  5219. if (this.name !== '') object.name = this.name;
  5220. if (this.castShadow === true) object.castShadow = true;
  5221. if (this.receiveShadow === true) object.receiveShadow = true;
  5222. if (this.visible === false) object.visible = false;
  5223. if (this.frustumCulled === false) object.frustumCulled = false;
  5224. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5225. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5226. object.layers = this.layers.mask;
  5227. object.matrix = this.matrix.toArray();
  5228. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false;
  5229. // object specific properties
  5230. if (this.isInstancedMesh) {
  5231. object.type = 'InstancedMesh';
  5232. object.count = this.count;
  5233. object.instanceMatrix = this.instanceMatrix.toJSON();
  5234. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5235. }
  5236. //
  5237. function serialize(library, element) {
  5238. if (library[element.uuid] === undefined) {
  5239. library[element.uuid] = element.toJSON(meta);
  5240. }
  5241. return element.uuid;
  5242. }
  5243. if (this.isScene) {
  5244. if (this.background) {
  5245. if (this.background.isColor) {
  5246. object.background = this.background.toJSON();
  5247. } else if (this.background.isTexture) {
  5248. object.background = this.background.toJSON(meta).uuid;
  5249. }
  5250. }
  5251. if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
  5252. object.environment = this.environment.toJSON(meta).uuid;
  5253. }
  5254. } else if (this.isMesh || this.isLine || this.isPoints) {
  5255. object.geometry = serialize(meta.geometries, this.geometry);
  5256. const parameters = this.geometry.parameters;
  5257. if (parameters !== undefined && parameters.shapes !== undefined) {
  5258. const shapes = parameters.shapes;
  5259. if (Array.isArray(shapes)) {
  5260. for (let i = 0, l = shapes.length; i < l; i++) {
  5261. const shape = shapes[i];
  5262. serialize(meta.shapes, shape);
  5263. }
  5264. } else {
  5265. serialize(meta.shapes, shapes);
  5266. }
  5267. }
  5268. }
  5269. if (this.isSkinnedMesh) {
  5270. object.bindMode = this.bindMode;
  5271. object.bindMatrix = this.bindMatrix.toArray();
  5272. if (this.skeleton !== undefined) {
  5273. serialize(meta.skeletons, this.skeleton);
  5274. object.skeleton = this.skeleton.uuid;
  5275. }
  5276. }
  5277. if (this.material !== undefined) {
  5278. if (Array.isArray(this.material)) {
  5279. const uuids = [];
  5280. for (let i = 0, l = this.material.length; i < l; i++) {
  5281. uuids.push(serialize(meta.materials, this.material[i]));
  5282. }
  5283. object.material = uuids;
  5284. } else {
  5285. object.material = serialize(meta.materials, this.material);
  5286. }
  5287. }
  5288. //
  5289. if (this.children.length > 0) {
  5290. object.children = [];
  5291. for (let i = 0; i < this.children.length; i++) {
  5292. object.children.push(this.children[i].toJSON(meta).object);
  5293. }
  5294. }
  5295. //
  5296. if (this.animations.length > 0) {
  5297. object.animations = [];
  5298. for (let i = 0; i < this.animations.length; i++) {
  5299. const animation = this.animations[i];
  5300. object.animations.push(serialize(meta.animations, animation));
  5301. }
  5302. }
  5303. if (isRootObject) {
  5304. const geometries = extractFromCache(meta.geometries);
  5305. const materials = extractFromCache(meta.materials);
  5306. const textures = extractFromCache(meta.textures);
  5307. const images = extractFromCache(meta.images);
  5308. const shapes = extractFromCache(meta.shapes);
  5309. const skeletons = extractFromCache(meta.skeletons);
  5310. const animations = extractFromCache(meta.animations);
  5311. const nodes = extractFromCache(meta.nodes);
  5312. if (geometries.length > 0) output.geometries = geometries;
  5313. if (materials.length > 0) output.materials = materials;
  5314. if (textures.length > 0) output.textures = textures;
  5315. if (images.length > 0) output.images = images;
  5316. if (shapes.length > 0) output.shapes = shapes;
  5317. if (skeletons.length > 0) output.skeletons = skeletons;
  5318. if (animations.length > 0) output.animations = animations;
  5319. if (nodes.length > 0) output.nodes = nodes;
  5320. }
  5321. output.object = object;
  5322. return output;
  5323. // extract data from the cache hash
  5324. // remove metadata on each item
  5325. // and return as array
  5326. function extractFromCache(cache) {
  5327. const values = [];
  5328. for (const key in cache) {
  5329. const data = cache[key];
  5330. delete data.metadata;
  5331. values.push(data);
  5332. }
  5333. return values;
  5334. }
  5335. }
  5336. clone(recursive) {
  5337. return new this.constructor().copy(this, recursive);
  5338. }
  5339. copy(source, recursive = true) {
  5340. this.name = source.name;
  5341. this.up.copy(source.up);
  5342. this.position.copy(source.position);
  5343. this.rotation.order = source.rotation.order;
  5344. this.quaternion.copy(source.quaternion);
  5345. this.scale.copy(source.scale);
  5346. this.matrix.copy(source.matrix);
  5347. this.matrixWorld.copy(source.matrixWorld);
  5348. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5349. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5350. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5351. this.layers.mask = source.layers.mask;
  5352. this.visible = source.visible;
  5353. this.castShadow = source.castShadow;
  5354. this.receiveShadow = source.receiveShadow;
  5355. this.frustumCulled = source.frustumCulled;
  5356. this.renderOrder = source.renderOrder;
  5357. this.userData = JSON.parse(JSON.stringify(source.userData));
  5358. if (recursive === true) {
  5359. for (let i = 0; i < source.children.length; i++) {
  5360. const child = source.children[i];
  5361. this.add(child.clone());
  5362. }
  5363. }
  5364. return this;
  5365. }
  5366. }
  5367. Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0);
  5368. Object3D.DefaultMatrixAutoUpdate = true;
  5369. Object3D.DefaultMatrixWorldAutoUpdate = true;
  5370. const _v0$1 = /*@__PURE__*/new Vector3();
  5371. const _v1$3 = /*@__PURE__*/new Vector3();
  5372. const _v2$2 = /*@__PURE__*/new Vector3();
  5373. const _v3$1 = /*@__PURE__*/new Vector3();
  5374. const _vab = /*@__PURE__*/new Vector3();
  5375. const _vac = /*@__PURE__*/new Vector3();
  5376. const _vbc = /*@__PURE__*/new Vector3();
  5377. const _vap = /*@__PURE__*/new Vector3();
  5378. const _vbp = /*@__PURE__*/new Vector3();
  5379. const _vcp = /*@__PURE__*/new Vector3();
  5380. class Triangle {
  5381. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5382. this.a = a;
  5383. this.b = b;
  5384. this.c = c;
  5385. }
  5386. static getNormal(a, b, c, target) {
  5387. target.subVectors(c, b);
  5388. _v0$1.subVectors(a, b);
  5389. target.cross(_v0$1);
  5390. const targetLengthSq = target.lengthSq();
  5391. if (targetLengthSq > 0) {
  5392. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5393. }
  5394. return target.set(0, 0, 0);
  5395. }
  5396. // static/instance method to calculate barycentric coordinates
  5397. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5398. static getBarycoord(point, a, b, c, target) {
  5399. _v0$1.subVectors(c, a);
  5400. _v1$3.subVectors(b, a);
  5401. _v2$2.subVectors(point, a);
  5402. const dot00 = _v0$1.dot(_v0$1);
  5403. const dot01 = _v0$1.dot(_v1$3);
  5404. const dot02 = _v0$1.dot(_v2$2);
  5405. const dot11 = _v1$3.dot(_v1$3);
  5406. const dot12 = _v1$3.dot(_v2$2);
  5407. const denom = dot00 * dot11 - dot01 * dot01;
  5408. // collinear or singular triangle
  5409. if (denom === 0) {
  5410. // arbitrary location outside of triangle?
  5411. // not sure if this is the best idea, maybe should be returning undefined
  5412. return target.set(-2, -1, -1);
  5413. }
  5414. const invDenom = 1 / denom;
  5415. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5416. const v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  5417. // barycentric coordinates must always sum to 1
  5418. return target.set(1 - u - v, v, u);
  5419. }
  5420. static containsPoint(point, a, b, c) {
  5421. this.getBarycoord(point, a, b, c, _v3$1);
  5422. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5423. }
  5424. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5425. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5426. target.set(0, 0);
  5427. target.addScaledVector(uv1, _v3$1.x);
  5428. target.addScaledVector(uv2, _v3$1.y);
  5429. target.addScaledVector(uv3, _v3$1.z);
  5430. return target;
  5431. }
  5432. static isFrontFacing(a, b, c, direction) {
  5433. _v0$1.subVectors(c, b);
  5434. _v1$3.subVectors(a, b);
  5435. // strictly front facing
  5436. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5437. }
  5438. set(a, b, c) {
  5439. this.a.copy(a);
  5440. this.b.copy(b);
  5441. this.c.copy(c);
  5442. return this;
  5443. }
  5444. setFromPointsAndIndices(points, i0, i1, i2) {
  5445. this.a.copy(points[i0]);
  5446. this.b.copy(points[i1]);
  5447. this.c.copy(points[i2]);
  5448. return this;
  5449. }
  5450. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5451. this.a.fromBufferAttribute(attribute, i0);
  5452. this.b.fromBufferAttribute(attribute, i1);
  5453. this.c.fromBufferAttribute(attribute, i2);
  5454. return this;
  5455. }
  5456. clone() {
  5457. return new this.constructor().copy(this);
  5458. }
  5459. copy(triangle) {
  5460. this.a.copy(triangle.a);
  5461. this.b.copy(triangle.b);
  5462. this.c.copy(triangle.c);
  5463. return this;
  5464. }
  5465. getArea() {
  5466. _v0$1.subVectors(this.c, this.b);
  5467. _v1$3.subVectors(this.a, this.b);
  5468. return _v0$1.cross(_v1$3).length() * 0.5;
  5469. }
  5470. getMidpoint(target) {
  5471. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5472. }
  5473. getNormal(target) {
  5474. return Triangle.getNormal(this.a, this.b, this.c, target);
  5475. }
  5476. getPlane(target) {
  5477. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5478. }
  5479. getBarycoord(point, target) {
  5480. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5481. }
  5482. getUV(point, uv1, uv2, uv3, target) {
  5483. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5484. }
  5485. containsPoint(point) {
  5486. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5487. }
  5488. isFrontFacing(direction) {
  5489. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5490. }
  5491. intersectsBox(box) {
  5492. return box.intersectsTriangle(this);
  5493. }
  5494. closestPointToPoint(p, target) {
  5495. const a = this.a,
  5496. b = this.b,
  5497. c = this.c;
  5498. let v, w;
  5499. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5500. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5501. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5502. // basically, we're distinguishing which of the voronoi regions of the triangle
  5503. // the point lies in with the minimum amount of redundant computation.
  5504. _vab.subVectors(b, a);
  5505. _vac.subVectors(c, a);
  5506. _vap.subVectors(p, a);
  5507. const d1 = _vab.dot(_vap);
  5508. const d2 = _vac.dot(_vap);
  5509. if (d1 <= 0 && d2 <= 0) {
  5510. // vertex region of A; barycentric coords (1, 0, 0)
  5511. return target.copy(a);
  5512. }
  5513. _vbp.subVectors(p, b);
  5514. const d3 = _vab.dot(_vbp);
  5515. const d4 = _vac.dot(_vbp);
  5516. if (d3 >= 0 && d4 <= d3) {
  5517. // vertex region of B; barycentric coords (0, 1, 0)
  5518. return target.copy(b);
  5519. }
  5520. const vc = d1 * d4 - d3 * d2;
  5521. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5522. v = d1 / (d1 - d3);
  5523. // edge region of AB; barycentric coords (1-v, v, 0)
  5524. return target.copy(a).addScaledVector(_vab, v);
  5525. }
  5526. _vcp.subVectors(p, c);
  5527. const d5 = _vab.dot(_vcp);
  5528. const d6 = _vac.dot(_vcp);
  5529. if (d6 >= 0 && d5 <= d6) {
  5530. // vertex region of C; barycentric coords (0, 0, 1)
  5531. return target.copy(c);
  5532. }
  5533. const vb = d5 * d2 - d1 * d6;
  5534. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5535. w = d2 / (d2 - d6);
  5536. // edge region of AC; barycentric coords (1-w, 0, w)
  5537. return target.copy(a).addScaledVector(_vac, w);
  5538. }
  5539. const va = d3 * d6 - d5 * d4;
  5540. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5541. _vbc.subVectors(c, b);
  5542. w = (d4 - d3) / (d4 - d3 + (d5 - d6));
  5543. // edge region of BC; barycentric coords (0, 1-w, w)
  5544. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5545. }
  5546. // face region
  5547. const denom = 1 / (va + vb + vc);
  5548. // u = va * denom
  5549. v = vb * denom;
  5550. w = vc * denom;
  5551. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5552. }
  5553. equals(triangle) {
  5554. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5555. }
  5556. }
  5557. let materialId = 0;
  5558. class Material extends EventDispatcher {
  5559. constructor() {
  5560. super();
  5561. this.isMaterial = true;
  5562. Object.defineProperty(this, 'id', {
  5563. value: materialId++
  5564. });
  5565. this.uuid = generateUUID();
  5566. this.name = '';
  5567. this.type = 'Material';
  5568. this.blending = NormalBlending;
  5569. this.side = FrontSide;
  5570. this.vertexColors = false;
  5571. this.opacity = 1;
  5572. this.transparent = false;
  5573. this.blendSrc = SrcAlphaFactor;
  5574. this.blendDst = OneMinusSrcAlphaFactor;
  5575. this.blendEquation = AddEquation;
  5576. this.blendSrcAlpha = null;
  5577. this.blendDstAlpha = null;
  5578. this.blendEquationAlpha = null;
  5579. this.depthFunc = LessEqualDepth;
  5580. this.depthTest = true;
  5581. this.depthWrite = true;
  5582. this.stencilWriteMask = 0xff;
  5583. this.stencilFunc = AlwaysStencilFunc;
  5584. this.stencilRef = 0;
  5585. this.stencilFuncMask = 0xff;
  5586. this.stencilFail = KeepStencilOp;
  5587. this.stencilZFail = KeepStencilOp;
  5588. this.stencilZPass = KeepStencilOp;
  5589. this.stencilWrite = false;
  5590. this.clippingPlanes = null;
  5591. this.clipIntersection = false;
  5592. this.clipShadows = false;
  5593. this.shadowSide = null;
  5594. this.colorWrite = true;
  5595. this.precision = null; // override the renderer's default precision for this material
  5596. this.polygonOffset = false;
  5597. this.polygonOffsetFactor = 0;
  5598. this.polygonOffsetUnits = 0;
  5599. this.dithering = false;
  5600. this.alphaToCoverage = false;
  5601. this.premultipliedAlpha = false;
  5602. this.visible = true;
  5603. this.toneMapped = true;
  5604. this.userData = {};
  5605. this.version = 0;
  5606. this._alphaTest = 0;
  5607. }
  5608. get alphaTest() {
  5609. return this._alphaTest;
  5610. }
  5611. set alphaTest(value) {
  5612. if (this._alphaTest > 0 !== value > 0) {
  5613. this.version++;
  5614. }
  5615. this._alphaTest = value;
  5616. }
  5617. onBuild() {}
  5618. onBeforeRender() {}
  5619. onBeforeCompile() {}
  5620. customProgramCacheKey() {
  5621. return this.onBeforeCompile.toString();
  5622. }
  5623. setValues(values) {
  5624. if (values === undefined) return;
  5625. for (const key in values) {
  5626. const newValue = values[key];
  5627. if (newValue === undefined) {
  5628. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5629. continue;
  5630. }
  5631. const currentValue = this[key];
  5632. if (currentValue === undefined) {
  5633. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5634. continue;
  5635. }
  5636. if (currentValue && currentValue.isColor) {
  5637. currentValue.set(newValue);
  5638. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5639. currentValue.copy(newValue);
  5640. } else {
  5641. this[key] = newValue;
  5642. }
  5643. }
  5644. }
  5645. toJSON(meta) {
  5646. const isRootObject = meta === undefined || typeof meta === 'string';
  5647. if (isRootObject) {
  5648. meta = {
  5649. textures: {},
  5650. images: {}
  5651. };
  5652. }
  5653. const data = {
  5654. metadata: {
  5655. version: 4.5,
  5656. type: 'Material',
  5657. generator: 'Material.toJSON'
  5658. }
  5659. };
  5660. // standard Material serialization
  5661. data.uuid = this.uuid;
  5662. data.type = this.type;
  5663. if (this.name !== '') data.name = this.name;
  5664. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5665. if (this.roughness !== undefined) data.roughness = this.roughness;
  5666. if (this.metalness !== undefined) data.metalness = this.metalness;
  5667. if (this.sheen !== undefined) data.sheen = this.sheen;
  5668. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5669. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5670. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5671. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5672. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5673. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5674. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5675. if (this.shininess !== undefined) data.shininess = this.shininess;
  5676. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5677. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5678. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5679. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5680. }
  5681. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5682. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5683. }
  5684. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5685. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5686. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5687. }
  5688. if (this.iridescence !== undefined) data.iridescence = this.iridescence;
  5689. if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR;
  5690. if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5691. if (this.iridescenceMap && this.iridescenceMap.isTexture) {
  5692. data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
  5693. }
  5694. if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
  5695. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
  5696. }
  5697. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5698. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5699. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5700. if (this.lightMap && this.lightMap.isTexture) {
  5701. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5702. data.lightMapIntensity = this.lightMapIntensity;
  5703. }
  5704. if (this.aoMap && this.aoMap.isTexture) {
  5705. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5706. data.aoMapIntensity = this.aoMapIntensity;
  5707. }
  5708. if (this.bumpMap && this.bumpMap.isTexture) {
  5709. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5710. data.bumpScale = this.bumpScale;
  5711. }
  5712. if (this.normalMap && this.normalMap.isTexture) {
  5713. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5714. data.normalMapType = this.normalMapType;
  5715. data.normalScale = this.normalScale.toArray();
  5716. }
  5717. if (this.displacementMap && this.displacementMap.isTexture) {
  5718. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5719. data.displacementScale = this.displacementScale;
  5720. data.displacementBias = this.displacementBias;
  5721. }
  5722. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5723. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5724. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5725. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5726. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5727. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5728. if (this.envMap && this.envMap.isTexture) {
  5729. data.envMap = this.envMap.toJSON(meta).uuid;
  5730. if (this.combine !== undefined) data.combine = this.combine;
  5731. }
  5732. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5733. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5734. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5735. if (this.gradientMap && this.gradientMap.isTexture) {
  5736. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5737. }
  5738. if (this.transmission !== undefined) data.transmission = this.transmission;
  5739. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5740. if (this.thickness !== undefined) data.thickness = this.thickness;
  5741. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5742. if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance;
  5743. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5744. if (this.size !== undefined) data.size = this.size;
  5745. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5746. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5747. if (this.blending !== NormalBlending) data.blending = this.blending;
  5748. if (this.side !== FrontSide) data.side = this.side;
  5749. if (this.vertexColors) data.vertexColors = true;
  5750. if (this.opacity < 1) data.opacity = this.opacity;
  5751. if (this.transparent === true) data.transparent = this.transparent;
  5752. data.depthFunc = this.depthFunc;
  5753. data.depthTest = this.depthTest;
  5754. data.depthWrite = this.depthWrite;
  5755. data.colorWrite = this.colorWrite;
  5756. data.stencilWrite = this.stencilWrite;
  5757. data.stencilWriteMask = this.stencilWriteMask;
  5758. data.stencilFunc = this.stencilFunc;
  5759. data.stencilRef = this.stencilRef;
  5760. data.stencilFuncMask = this.stencilFuncMask;
  5761. data.stencilFail = this.stencilFail;
  5762. data.stencilZFail = this.stencilZFail;
  5763. data.stencilZPass = this.stencilZPass;
  5764. // rotation (SpriteMaterial)
  5765. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5766. if (this.polygonOffset === true) data.polygonOffset = true;
  5767. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5768. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5769. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5770. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5771. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5772. if (this.scale !== undefined) data.scale = this.scale;
  5773. if (this.dithering === true) data.dithering = true;
  5774. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5775. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5776. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5777. if (this.wireframe === true) data.wireframe = this.wireframe;
  5778. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5779. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5780. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5781. if (this.flatShading === true) data.flatShading = this.flatShading;
  5782. if (this.visible === false) data.visible = false;
  5783. if (this.toneMapped === false) data.toneMapped = false;
  5784. if (this.fog === false) data.fog = false;
  5785. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData;
  5786. // TODO: Copied from Object3D.toJSON
  5787. function extractFromCache(cache) {
  5788. const values = [];
  5789. for (const key in cache) {
  5790. const data = cache[key];
  5791. delete data.metadata;
  5792. values.push(data);
  5793. }
  5794. return values;
  5795. }
  5796. if (isRootObject) {
  5797. const textures = extractFromCache(meta.textures);
  5798. const images = extractFromCache(meta.images);
  5799. if (textures.length > 0) data.textures = textures;
  5800. if (images.length > 0) data.images = images;
  5801. }
  5802. return data;
  5803. }
  5804. clone() {
  5805. return new this.constructor().copy(this);
  5806. }
  5807. copy(source) {
  5808. this.name = source.name;
  5809. this.blending = source.blending;
  5810. this.side = source.side;
  5811. this.vertexColors = source.vertexColors;
  5812. this.opacity = source.opacity;
  5813. this.transparent = source.transparent;
  5814. this.blendSrc = source.blendSrc;
  5815. this.blendDst = source.blendDst;
  5816. this.blendEquation = source.blendEquation;
  5817. this.blendSrcAlpha = source.blendSrcAlpha;
  5818. this.blendDstAlpha = source.blendDstAlpha;
  5819. this.blendEquationAlpha = source.blendEquationAlpha;
  5820. this.depthFunc = source.depthFunc;
  5821. this.depthTest = source.depthTest;
  5822. this.depthWrite = source.depthWrite;
  5823. this.stencilWriteMask = source.stencilWriteMask;
  5824. this.stencilFunc = source.stencilFunc;
  5825. this.stencilRef = source.stencilRef;
  5826. this.stencilFuncMask = source.stencilFuncMask;
  5827. this.stencilFail = source.stencilFail;
  5828. this.stencilZFail = source.stencilZFail;
  5829. this.stencilZPass = source.stencilZPass;
  5830. this.stencilWrite = source.stencilWrite;
  5831. const srcPlanes = source.clippingPlanes;
  5832. let dstPlanes = null;
  5833. if (srcPlanes !== null) {
  5834. const n = srcPlanes.length;
  5835. dstPlanes = new Array(n);
  5836. for (let i = 0; i !== n; ++i) {
  5837. dstPlanes[i] = srcPlanes[i].clone();
  5838. }
  5839. }
  5840. this.clippingPlanes = dstPlanes;
  5841. this.clipIntersection = source.clipIntersection;
  5842. this.clipShadows = source.clipShadows;
  5843. this.shadowSide = source.shadowSide;
  5844. this.colorWrite = source.colorWrite;
  5845. this.precision = source.precision;
  5846. this.polygonOffset = source.polygonOffset;
  5847. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5848. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5849. this.dithering = source.dithering;
  5850. this.alphaTest = source.alphaTest;
  5851. this.alphaToCoverage = source.alphaToCoverage;
  5852. this.premultipliedAlpha = source.premultipliedAlpha;
  5853. this.visible = source.visible;
  5854. this.toneMapped = source.toneMapped;
  5855. this.userData = JSON.parse(JSON.stringify(source.userData));
  5856. return this;
  5857. }
  5858. dispose() {
  5859. this.dispatchEvent({
  5860. type: 'dispose'
  5861. });
  5862. }
  5863. set needsUpdate(value) {
  5864. if (value === true) this.version++;
  5865. }
  5866. }
  5867. class MeshBasicMaterial extends Material {
  5868. constructor(parameters) {
  5869. super();
  5870. this.isMeshBasicMaterial = true;
  5871. this.type = 'MeshBasicMaterial';
  5872. this.color = new Color(0xffffff); // emissive
  5873. this.map = null;
  5874. this.lightMap = null;
  5875. this.lightMapIntensity = 1.0;
  5876. this.aoMap = null;
  5877. this.aoMapIntensity = 1.0;
  5878. this.specularMap = null;
  5879. this.alphaMap = null;
  5880. this.envMap = null;
  5881. this.combine = MultiplyOperation;
  5882. this.reflectivity = 1;
  5883. this.refractionRatio = 0.98;
  5884. this.wireframe = false;
  5885. this.wireframeLinewidth = 1;
  5886. this.wireframeLinecap = 'round';
  5887. this.wireframeLinejoin = 'round';
  5888. this.fog = true;
  5889. this.setValues(parameters);
  5890. }
  5891. copy(source) {
  5892. super.copy(source);
  5893. this.color.copy(source.color);
  5894. this.map = source.map;
  5895. this.lightMap = source.lightMap;
  5896. this.lightMapIntensity = source.lightMapIntensity;
  5897. this.aoMap = source.aoMap;
  5898. this.aoMapIntensity = source.aoMapIntensity;
  5899. this.specularMap = source.specularMap;
  5900. this.alphaMap = source.alphaMap;
  5901. this.envMap = source.envMap;
  5902. this.combine = source.combine;
  5903. this.reflectivity = source.reflectivity;
  5904. this.refractionRatio = source.refractionRatio;
  5905. this.wireframe = source.wireframe;
  5906. this.wireframeLinewidth = source.wireframeLinewidth;
  5907. this.wireframeLinecap = source.wireframeLinecap;
  5908. this.wireframeLinejoin = source.wireframeLinejoin;
  5909. this.fog = source.fog;
  5910. return this;
  5911. }
  5912. }
  5913. const _vector$9 = /*@__PURE__*/new Vector3();
  5914. const _vector2$1 = /*@__PURE__*/new Vector2();
  5915. class BufferAttribute {
  5916. constructor(array, itemSize, normalized) {
  5917. if (Array.isArray(array)) {
  5918. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5919. }
  5920. this.isBufferAttribute = true;
  5921. this.name = '';
  5922. this.array = array;
  5923. this.itemSize = itemSize;
  5924. this.count = array !== undefined ? array.length / itemSize : 0;
  5925. this.normalized = normalized === true;
  5926. this.usage = StaticDrawUsage;
  5927. this.updateRange = {
  5928. offset: 0,
  5929. count: -1
  5930. };
  5931. this.version = 0;
  5932. }
  5933. onUploadCallback() {}
  5934. set needsUpdate(value) {
  5935. if (value === true) this.version++;
  5936. }
  5937. setUsage(value) {
  5938. this.usage = value;
  5939. return this;
  5940. }
  5941. copy(source) {
  5942. this.name = source.name;
  5943. this.array = new source.array.constructor(source.array);
  5944. this.itemSize = source.itemSize;
  5945. this.count = source.count;
  5946. this.normalized = source.normalized;
  5947. this.usage = source.usage;
  5948. return this;
  5949. }
  5950. copyAt(index1, attribute, index2) {
  5951. index1 *= this.itemSize;
  5952. index2 *= attribute.itemSize;
  5953. for (let i = 0, l = this.itemSize; i < l; i++) {
  5954. this.array[index1 + i] = attribute.array[index2 + i];
  5955. }
  5956. return this;
  5957. }
  5958. copyArray(array) {
  5959. this.array.set(array);
  5960. return this;
  5961. }
  5962. applyMatrix3(m) {
  5963. if (this.itemSize === 2) {
  5964. for (let i = 0, l = this.count; i < l; i++) {
  5965. _vector2$1.fromBufferAttribute(this, i);
  5966. _vector2$1.applyMatrix3(m);
  5967. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5968. }
  5969. } else if (this.itemSize === 3) {
  5970. for (let i = 0, l = this.count; i < l; i++) {
  5971. _vector$9.fromBufferAttribute(this, i);
  5972. _vector$9.applyMatrix3(m);
  5973. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5974. }
  5975. }
  5976. return this;
  5977. }
  5978. applyMatrix4(m) {
  5979. for (let i = 0, l = this.count; i < l; i++) {
  5980. _vector$9.fromBufferAttribute(this, i);
  5981. _vector$9.applyMatrix4(m);
  5982. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5983. }
  5984. return this;
  5985. }
  5986. applyNormalMatrix(m) {
  5987. for (let i = 0, l = this.count; i < l; i++) {
  5988. _vector$9.fromBufferAttribute(this, i);
  5989. _vector$9.applyNormalMatrix(m);
  5990. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5991. }
  5992. return this;
  5993. }
  5994. transformDirection(m) {
  5995. for (let i = 0, l = this.count; i < l; i++) {
  5996. _vector$9.fromBufferAttribute(this, i);
  5997. _vector$9.transformDirection(m);
  5998. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5999. }
  6000. return this;
  6001. }
  6002. set(value, offset = 0) {
  6003. // Matching BufferAttribute constructor, do not normalize the array.
  6004. this.array.set(value, offset);
  6005. return this;
  6006. }
  6007. getX(index) {
  6008. let x = this.array[index * this.itemSize];
  6009. if (this.normalized) x = denormalize(x, this.array);
  6010. return x;
  6011. }
  6012. setX(index, x) {
  6013. if (this.normalized) x = normalize(x, this.array);
  6014. this.array[index * this.itemSize] = x;
  6015. return this;
  6016. }
  6017. getY(index) {
  6018. let y = this.array[index * this.itemSize + 1];
  6019. if (this.normalized) y = denormalize(y, this.array);
  6020. return y;
  6021. }
  6022. setY(index, y) {
  6023. if (this.normalized) y = normalize(y, this.array);
  6024. this.array[index * this.itemSize + 1] = y;
  6025. return this;
  6026. }
  6027. getZ(index) {
  6028. let z = this.array[index * this.itemSize + 2];
  6029. if (this.normalized) z = denormalize(z, this.array);
  6030. return z;
  6031. }
  6032. setZ(index, z) {
  6033. if (this.normalized) z = normalize(z, this.array);
  6034. this.array[index * this.itemSize + 2] = z;
  6035. return this;
  6036. }
  6037. getW(index) {
  6038. let w = this.array[index * this.itemSize + 3];
  6039. if (this.normalized) w = denormalize(w, this.array);
  6040. return w;
  6041. }
  6042. setW(index, w) {
  6043. if (this.normalized) w = normalize(w, this.array);
  6044. this.array[index * this.itemSize + 3] = w;
  6045. return this;
  6046. }
  6047. setXY(index, x, y) {
  6048. index *= this.itemSize;
  6049. if (this.normalized) {
  6050. x = normalize(x, this.array);
  6051. y = normalize(y, this.array);
  6052. }
  6053. this.array[index + 0] = x;
  6054. this.array[index + 1] = y;
  6055. return this;
  6056. }
  6057. setXYZ(index, x, y, z) {
  6058. index *= this.itemSize;
  6059. if (this.normalized) {
  6060. x = normalize(x, this.array);
  6061. y = normalize(y, this.array);
  6062. z = normalize(z, this.array);
  6063. }
  6064. this.array[index + 0] = x;
  6065. this.array[index + 1] = y;
  6066. this.array[index + 2] = z;
  6067. return this;
  6068. }
  6069. setXYZW(index, x, y, z, w) {
  6070. index *= this.itemSize;
  6071. if (this.normalized) {
  6072. x = normalize(x, this.array);
  6073. y = normalize(y, this.array);
  6074. z = normalize(z, this.array);
  6075. w = normalize(w, this.array);
  6076. }
  6077. this.array[index + 0] = x;
  6078. this.array[index + 1] = y;
  6079. this.array[index + 2] = z;
  6080. this.array[index + 3] = w;
  6081. return this;
  6082. }
  6083. onUpload(callback) {
  6084. this.onUploadCallback = callback;
  6085. return this;
  6086. }
  6087. clone() {
  6088. return new this.constructor(this.array, this.itemSize).copy(this);
  6089. }
  6090. toJSON() {
  6091. const data = {
  6092. itemSize: this.itemSize,
  6093. type: this.array.constructor.name,
  6094. array: Array.from(this.array),
  6095. normalized: this.normalized
  6096. };
  6097. if (this.name !== '') data.name = this.name;
  6098. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6099. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6100. return data;
  6101. }
  6102. // @deprecated
  6103. copyColorsArray() {
  6104. console.error('THREE.BufferAttribute: copyColorsArray() was removed in r144.');
  6105. }
  6106. copyVector2sArray() {
  6107. console.error('THREE.BufferAttribute: copyVector2sArray() was removed in r144.');
  6108. }
  6109. copyVector3sArray() {
  6110. console.error('THREE.BufferAttribute: copyVector3sArray() was removed in r144.');
  6111. }
  6112. copyVector4sArray() {
  6113. console.error('THREE.BufferAttribute: copyVector4sArray() was removed in r144.');
  6114. }
  6115. }
  6116. //
  6117. class Int8BufferAttribute extends BufferAttribute {
  6118. constructor(array, itemSize, normalized) {
  6119. super(new Int8Array(array), itemSize, normalized);
  6120. }
  6121. }
  6122. class Uint8BufferAttribute extends BufferAttribute {
  6123. constructor(array, itemSize, normalized) {
  6124. super(new Uint8Array(array), itemSize, normalized);
  6125. }
  6126. }
  6127. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6128. constructor(array, itemSize, normalized) {
  6129. super(new Uint8ClampedArray(array), itemSize, normalized);
  6130. }
  6131. }
  6132. class Int16BufferAttribute extends BufferAttribute {
  6133. constructor(array, itemSize, normalized) {
  6134. super(new Int16Array(array), itemSize, normalized);
  6135. }
  6136. }
  6137. class Uint16BufferAttribute extends BufferAttribute {
  6138. constructor(array, itemSize, normalized) {
  6139. super(new Uint16Array(array), itemSize, normalized);
  6140. }
  6141. }
  6142. class Int32BufferAttribute extends BufferAttribute {
  6143. constructor(array, itemSize, normalized) {
  6144. super(new Int32Array(array), itemSize, normalized);
  6145. }
  6146. }
  6147. class Uint32BufferAttribute extends BufferAttribute {
  6148. constructor(array, itemSize, normalized) {
  6149. super(new Uint32Array(array), itemSize, normalized);
  6150. }
  6151. }
  6152. class Float16BufferAttribute extends BufferAttribute {
  6153. constructor(array, itemSize, normalized) {
  6154. super(new Uint16Array(array), itemSize, normalized);
  6155. this.isFloat16BufferAttribute = true;
  6156. }
  6157. }
  6158. class Float32BufferAttribute extends BufferAttribute {
  6159. constructor(array, itemSize, normalized) {
  6160. super(new Float32Array(array), itemSize, normalized);
  6161. }
  6162. }
  6163. class Float64BufferAttribute extends BufferAttribute {
  6164. constructor(array, itemSize, normalized) {
  6165. super(new Float64Array(array), itemSize, normalized);
  6166. }
  6167. }
  6168. let _id$1 = 0;
  6169. const _m1 = /*@__PURE__*/new Matrix4();
  6170. const _obj = /*@__PURE__*/new Object3D();
  6171. const _offset = /*@__PURE__*/new Vector3();
  6172. const _box$1 = /*@__PURE__*/new Box3();
  6173. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6174. const _vector$8 = /*@__PURE__*/new Vector3();
  6175. class BufferGeometry extends EventDispatcher {
  6176. constructor() {
  6177. super();
  6178. this.isBufferGeometry = true;
  6179. Object.defineProperty(this, 'id', {
  6180. value: _id$1++
  6181. });
  6182. this.uuid = generateUUID();
  6183. this.name = '';
  6184. this.type = 'BufferGeometry';
  6185. this.index = null;
  6186. this.attributes = {};
  6187. this.morphAttributes = {};
  6188. this.morphTargetsRelative = false;
  6189. this.groups = [];
  6190. this.boundingBox = null;
  6191. this.boundingSphere = null;
  6192. this.drawRange = {
  6193. start: 0,
  6194. count: Infinity
  6195. };
  6196. this.userData = {};
  6197. }
  6198. getIndex() {
  6199. return this.index;
  6200. }
  6201. setIndex(index) {
  6202. if (Array.isArray(index)) {
  6203. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6204. } else {
  6205. this.index = index;
  6206. }
  6207. return this;
  6208. }
  6209. getAttribute(name) {
  6210. return this.attributes[name];
  6211. }
  6212. setAttribute(name, attribute) {
  6213. this.attributes[name] = attribute;
  6214. return this;
  6215. }
  6216. deleteAttribute(name) {
  6217. delete this.attributes[name];
  6218. return this;
  6219. }
  6220. hasAttribute(name) {
  6221. return this.attributes[name] !== undefined;
  6222. }
  6223. addGroup(start, count, materialIndex = 0) {
  6224. this.groups.push({
  6225. start: start,
  6226. count: count,
  6227. materialIndex: materialIndex
  6228. });
  6229. }
  6230. clearGroups() {
  6231. this.groups = [];
  6232. }
  6233. setDrawRange(start, count) {
  6234. this.drawRange.start = start;
  6235. this.drawRange.count = count;
  6236. }
  6237. applyMatrix4(matrix) {
  6238. const position = this.attributes.position;
  6239. if (position !== undefined) {
  6240. position.applyMatrix4(matrix);
  6241. position.needsUpdate = true;
  6242. }
  6243. const normal = this.attributes.normal;
  6244. if (normal !== undefined) {
  6245. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6246. normal.applyNormalMatrix(normalMatrix);
  6247. normal.needsUpdate = true;
  6248. }
  6249. const tangent = this.attributes.tangent;
  6250. if (tangent !== undefined) {
  6251. tangent.transformDirection(matrix);
  6252. tangent.needsUpdate = true;
  6253. }
  6254. if (this.boundingBox !== null) {
  6255. this.computeBoundingBox();
  6256. }
  6257. if (this.boundingSphere !== null) {
  6258. this.computeBoundingSphere();
  6259. }
  6260. return this;
  6261. }
  6262. applyQuaternion(q) {
  6263. _m1.makeRotationFromQuaternion(q);
  6264. this.applyMatrix4(_m1);
  6265. return this;
  6266. }
  6267. rotateX(angle) {
  6268. // rotate geometry around world x-axis
  6269. _m1.makeRotationX(angle);
  6270. this.applyMatrix4(_m1);
  6271. return this;
  6272. }
  6273. rotateY(angle) {
  6274. // rotate geometry around world y-axis
  6275. _m1.makeRotationY(angle);
  6276. this.applyMatrix4(_m1);
  6277. return this;
  6278. }
  6279. rotateZ(angle) {
  6280. // rotate geometry around world z-axis
  6281. _m1.makeRotationZ(angle);
  6282. this.applyMatrix4(_m1);
  6283. return this;
  6284. }
  6285. translate(x, y, z) {
  6286. // translate geometry
  6287. _m1.makeTranslation(x, y, z);
  6288. this.applyMatrix4(_m1);
  6289. return this;
  6290. }
  6291. scale(x, y, z) {
  6292. // scale geometry
  6293. _m1.makeScale(x, y, z);
  6294. this.applyMatrix4(_m1);
  6295. return this;
  6296. }
  6297. lookAt(vector) {
  6298. _obj.lookAt(vector);
  6299. _obj.updateMatrix();
  6300. this.applyMatrix4(_obj.matrix);
  6301. return this;
  6302. }
  6303. center() {
  6304. this.computeBoundingBox();
  6305. this.boundingBox.getCenter(_offset).negate();
  6306. this.translate(_offset.x, _offset.y, _offset.z);
  6307. return this;
  6308. }
  6309. setFromPoints(points) {
  6310. const position = [];
  6311. for (let i = 0, l = points.length; i < l; i++) {
  6312. const point = points[i];
  6313. position.push(point.x, point.y, point.z || 0);
  6314. }
  6315. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6316. return this;
  6317. }
  6318. computeBoundingBox() {
  6319. if (this.boundingBox === null) {
  6320. this.boundingBox = new Box3();
  6321. }
  6322. const position = this.attributes.position;
  6323. const morphAttributesPosition = this.morphAttributes.position;
  6324. if (position && position.isGLBufferAttribute) {
  6325. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6326. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6327. return;
  6328. }
  6329. if (position !== undefined) {
  6330. this.boundingBox.setFromBufferAttribute(position);
  6331. // process morph attributes if present
  6332. if (morphAttributesPosition) {
  6333. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6334. const morphAttribute = morphAttributesPosition[i];
  6335. _box$1.setFromBufferAttribute(morphAttribute);
  6336. if (this.morphTargetsRelative) {
  6337. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6338. this.boundingBox.expandByPoint(_vector$8);
  6339. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6340. this.boundingBox.expandByPoint(_vector$8);
  6341. } else {
  6342. this.boundingBox.expandByPoint(_box$1.min);
  6343. this.boundingBox.expandByPoint(_box$1.max);
  6344. }
  6345. }
  6346. }
  6347. } else {
  6348. this.boundingBox.makeEmpty();
  6349. }
  6350. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6351. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6352. }
  6353. }
  6354. computeBoundingSphere() {
  6355. if (this.boundingSphere === null) {
  6356. this.boundingSphere = new Sphere();
  6357. }
  6358. const position = this.attributes.position;
  6359. const morphAttributesPosition = this.morphAttributes.position;
  6360. if (position && position.isGLBufferAttribute) {
  6361. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6362. this.boundingSphere.set(new Vector3(), Infinity);
  6363. return;
  6364. }
  6365. if (position) {
  6366. // first, find the center of the bounding sphere
  6367. const center = this.boundingSphere.center;
  6368. _box$1.setFromBufferAttribute(position);
  6369. // process morph attributes if present
  6370. if (morphAttributesPosition) {
  6371. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6372. const morphAttribute = morphAttributesPosition[i];
  6373. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6374. if (this.morphTargetsRelative) {
  6375. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6376. _box$1.expandByPoint(_vector$8);
  6377. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6378. _box$1.expandByPoint(_vector$8);
  6379. } else {
  6380. _box$1.expandByPoint(_boxMorphTargets.min);
  6381. _box$1.expandByPoint(_boxMorphTargets.max);
  6382. }
  6383. }
  6384. }
  6385. _box$1.getCenter(center);
  6386. // second, try to find a boundingSphere with a radius smaller than the
  6387. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6388. let maxRadiusSq = 0;
  6389. for (let i = 0, il = position.count; i < il; i++) {
  6390. _vector$8.fromBufferAttribute(position, i);
  6391. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6392. }
  6393. // process morph attributes if present
  6394. if (morphAttributesPosition) {
  6395. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6396. const morphAttribute = morphAttributesPosition[i];
  6397. const morphTargetsRelative = this.morphTargetsRelative;
  6398. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6399. _vector$8.fromBufferAttribute(morphAttribute, j);
  6400. if (morphTargetsRelative) {
  6401. _offset.fromBufferAttribute(position, j);
  6402. _vector$8.add(_offset);
  6403. }
  6404. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6405. }
  6406. }
  6407. }
  6408. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6409. if (isNaN(this.boundingSphere.radius)) {
  6410. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6411. }
  6412. }
  6413. }
  6414. computeTangents() {
  6415. const index = this.index;
  6416. const attributes = this.attributes;
  6417. // based on http://www.terathon.com/code/tangent.html
  6418. // (per vertex tangents)
  6419. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6420. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6421. return;
  6422. }
  6423. const indices = index.array;
  6424. const positions = attributes.position.array;
  6425. const normals = attributes.normal.array;
  6426. const uvs = attributes.uv.array;
  6427. const nVertices = positions.length / 3;
  6428. if (this.hasAttribute('tangent') === false) {
  6429. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6430. }
  6431. const tangents = this.getAttribute('tangent').array;
  6432. const tan1 = [],
  6433. tan2 = [];
  6434. for (let i = 0; i < nVertices; i++) {
  6435. tan1[i] = new Vector3();
  6436. tan2[i] = new Vector3();
  6437. }
  6438. const vA = new Vector3(),
  6439. vB = new Vector3(),
  6440. vC = new Vector3(),
  6441. uvA = new Vector2(),
  6442. uvB = new Vector2(),
  6443. uvC = new Vector2(),
  6444. sdir = new Vector3(),
  6445. tdir = new Vector3();
  6446. function handleTriangle(a, b, c) {
  6447. vA.fromArray(positions, a * 3);
  6448. vB.fromArray(positions, b * 3);
  6449. vC.fromArray(positions, c * 3);
  6450. uvA.fromArray(uvs, a * 2);
  6451. uvB.fromArray(uvs, b * 2);
  6452. uvC.fromArray(uvs, c * 2);
  6453. vB.sub(vA);
  6454. vC.sub(vA);
  6455. uvB.sub(uvA);
  6456. uvC.sub(uvA);
  6457. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y);
  6458. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6459. if (!isFinite(r)) return;
  6460. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6461. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6462. tan1[a].add(sdir);
  6463. tan1[b].add(sdir);
  6464. tan1[c].add(sdir);
  6465. tan2[a].add(tdir);
  6466. tan2[b].add(tdir);
  6467. tan2[c].add(tdir);
  6468. }
  6469. let groups = this.groups;
  6470. if (groups.length === 0) {
  6471. groups = [{
  6472. start: 0,
  6473. count: indices.length
  6474. }];
  6475. }
  6476. for (let i = 0, il = groups.length; i < il; ++i) {
  6477. const group = groups[i];
  6478. const start = group.start;
  6479. const count = group.count;
  6480. for (let j = start, jl = start + count; j < jl; j += 3) {
  6481. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6482. }
  6483. }
  6484. const tmp = new Vector3(),
  6485. tmp2 = new Vector3();
  6486. const n = new Vector3(),
  6487. n2 = new Vector3();
  6488. function handleVertex(v) {
  6489. n.fromArray(normals, v * 3);
  6490. n2.copy(n);
  6491. const t = tan1[v];
  6492. // Gram-Schmidt orthogonalize
  6493. tmp.copy(t);
  6494. tmp.sub(n.multiplyScalar(n.dot(t))).normalize();
  6495. // Calculate handedness
  6496. tmp2.crossVectors(n2, t);
  6497. const test = tmp2.dot(tan2[v]);
  6498. const w = test < 0.0 ? -1.0 : 1.0;
  6499. tangents[v * 4] = tmp.x;
  6500. tangents[v * 4 + 1] = tmp.y;
  6501. tangents[v * 4 + 2] = tmp.z;
  6502. tangents[v * 4 + 3] = w;
  6503. }
  6504. for (let i = 0, il = groups.length; i < il; ++i) {
  6505. const group = groups[i];
  6506. const start = group.start;
  6507. const count = group.count;
  6508. for (let j = start, jl = start + count; j < jl; j += 3) {
  6509. handleVertex(indices[j + 0]);
  6510. handleVertex(indices[j + 1]);
  6511. handleVertex(indices[j + 2]);
  6512. }
  6513. }
  6514. }
  6515. computeVertexNormals() {
  6516. const index = this.index;
  6517. const positionAttribute = this.getAttribute('position');
  6518. if (positionAttribute !== undefined) {
  6519. let normalAttribute = this.getAttribute('normal');
  6520. if (normalAttribute === undefined) {
  6521. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6522. this.setAttribute('normal', normalAttribute);
  6523. } else {
  6524. // reset existing normals to zero
  6525. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6526. normalAttribute.setXYZ(i, 0, 0, 0);
  6527. }
  6528. }
  6529. const pA = new Vector3(),
  6530. pB = new Vector3(),
  6531. pC = new Vector3();
  6532. const nA = new Vector3(),
  6533. nB = new Vector3(),
  6534. nC = new Vector3();
  6535. const cb = new Vector3(),
  6536. ab = new Vector3();
  6537. // indexed elements
  6538. if (index) {
  6539. for (let i = 0, il = index.count; i < il; i += 3) {
  6540. const vA = index.getX(i + 0);
  6541. const vB = index.getX(i + 1);
  6542. const vC = index.getX(i + 2);
  6543. pA.fromBufferAttribute(positionAttribute, vA);
  6544. pB.fromBufferAttribute(positionAttribute, vB);
  6545. pC.fromBufferAttribute(positionAttribute, vC);
  6546. cb.subVectors(pC, pB);
  6547. ab.subVectors(pA, pB);
  6548. cb.cross(ab);
  6549. nA.fromBufferAttribute(normalAttribute, vA);
  6550. nB.fromBufferAttribute(normalAttribute, vB);
  6551. nC.fromBufferAttribute(normalAttribute, vC);
  6552. nA.add(cb);
  6553. nB.add(cb);
  6554. nC.add(cb);
  6555. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6556. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6557. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6558. }
  6559. } else {
  6560. // non-indexed elements (unconnected triangle soup)
  6561. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6562. pA.fromBufferAttribute(positionAttribute, i + 0);
  6563. pB.fromBufferAttribute(positionAttribute, i + 1);
  6564. pC.fromBufferAttribute(positionAttribute, i + 2);
  6565. cb.subVectors(pC, pB);
  6566. ab.subVectors(pA, pB);
  6567. cb.cross(ab);
  6568. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6569. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6570. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6571. }
  6572. }
  6573. this.normalizeNormals();
  6574. normalAttribute.needsUpdate = true;
  6575. }
  6576. }
  6577. // @deprecated since r144
  6578. merge() {
  6579. console.error('THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.');
  6580. return this;
  6581. }
  6582. normalizeNormals() {
  6583. const normals = this.attributes.normal;
  6584. for (let i = 0, il = normals.count; i < il; i++) {
  6585. _vector$8.fromBufferAttribute(normals, i);
  6586. _vector$8.normalize();
  6587. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6588. }
  6589. }
  6590. toNonIndexed() {
  6591. function convertBufferAttribute(attribute, indices) {
  6592. const array = attribute.array;
  6593. const itemSize = attribute.itemSize;
  6594. const normalized = attribute.normalized;
  6595. const array2 = new array.constructor(indices.length * itemSize);
  6596. let index = 0,
  6597. index2 = 0;
  6598. for (let i = 0, l = indices.length; i < l; i++) {
  6599. if (attribute.isInterleavedBufferAttribute) {
  6600. index = indices[i] * attribute.data.stride + attribute.offset;
  6601. } else {
  6602. index = indices[i] * itemSize;
  6603. }
  6604. for (let j = 0; j < itemSize; j++) {
  6605. array2[index2++] = array[index++];
  6606. }
  6607. }
  6608. return new BufferAttribute(array2, itemSize, normalized);
  6609. }
  6610. //
  6611. if (this.index === null) {
  6612. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6613. return this;
  6614. }
  6615. const geometry2 = new BufferGeometry();
  6616. const indices = this.index.array;
  6617. const attributes = this.attributes;
  6618. // attributes
  6619. for (const name in attributes) {
  6620. const attribute = attributes[name];
  6621. const newAttribute = convertBufferAttribute(attribute, indices);
  6622. geometry2.setAttribute(name, newAttribute);
  6623. }
  6624. // morph attributes
  6625. const morphAttributes = this.morphAttributes;
  6626. for (const name in morphAttributes) {
  6627. const morphArray = [];
  6628. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6629. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6630. const attribute = morphAttribute[i];
  6631. const newAttribute = convertBufferAttribute(attribute, indices);
  6632. morphArray.push(newAttribute);
  6633. }
  6634. geometry2.morphAttributes[name] = morphArray;
  6635. }
  6636. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6637. // groups
  6638. const groups = this.groups;
  6639. for (let i = 0, l = groups.length; i < l; i++) {
  6640. const group = groups[i];
  6641. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6642. }
  6643. return geometry2;
  6644. }
  6645. toJSON() {
  6646. const data = {
  6647. metadata: {
  6648. version: 4.5,
  6649. type: 'BufferGeometry',
  6650. generator: 'BufferGeometry.toJSON'
  6651. }
  6652. };
  6653. // standard BufferGeometry serialization
  6654. data.uuid = this.uuid;
  6655. data.type = this.type;
  6656. if (this.name !== '') data.name = this.name;
  6657. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6658. if (this.parameters !== undefined) {
  6659. const parameters = this.parameters;
  6660. for (const key in parameters) {
  6661. if (parameters[key] !== undefined) data[key] = parameters[key];
  6662. }
  6663. return data;
  6664. }
  6665. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6666. data.data = {
  6667. attributes: {}
  6668. };
  6669. const index = this.index;
  6670. if (index !== null) {
  6671. data.data.index = {
  6672. type: index.array.constructor.name,
  6673. array: Array.prototype.slice.call(index.array)
  6674. };
  6675. }
  6676. const attributes = this.attributes;
  6677. for (const key in attributes) {
  6678. const attribute = attributes[key];
  6679. data.data.attributes[key] = attribute.toJSON(data.data);
  6680. }
  6681. const morphAttributes = {};
  6682. let hasMorphAttributes = false;
  6683. for (const key in this.morphAttributes) {
  6684. const attributeArray = this.morphAttributes[key];
  6685. const array = [];
  6686. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6687. const attribute = attributeArray[i];
  6688. array.push(attribute.toJSON(data.data));
  6689. }
  6690. if (array.length > 0) {
  6691. morphAttributes[key] = array;
  6692. hasMorphAttributes = true;
  6693. }
  6694. }
  6695. if (hasMorphAttributes) {
  6696. data.data.morphAttributes = morphAttributes;
  6697. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6698. }
  6699. const groups = this.groups;
  6700. if (groups.length > 0) {
  6701. data.data.groups = JSON.parse(JSON.stringify(groups));
  6702. }
  6703. const boundingSphere = this.boundingSphere;
  6704. if (boundingSphere !== null) {
  6705. data.data.boundingSphere = {
  6706. center: boundingSphere.center.toArray(),
  6707. radius: boundingSphere.radius
  6708. };
  6709. }
  6710. return data;
  6711. }
  6712. clone() {
  6713. return new this.constructor().copy(this);
  6714. }
  6715. copy(source) {
  6716. // reset
  6717. this.index = null;
  6718. this.attributes = {};
  6719. this.morphAttributes = {};
  6720. this.groups = [];
  6721. this.boundingBox = null;
  6722. this.boundingSphere = null;
  6723. // used for storing cloned, shared data
  6724. const data = {};
  6725. // name
  6726. this.name = source.name;
  6727. // index
  6728. const index = source.index;
  6729. if (index !== null) {
  6730. this.setIndex(index.clone(data));
  6731. }
  6732. // attributes
  6733. const attributes = source.attributes;
  6734. for (const name in attributes) {
  6735. const attribute = attributes[name];
  6736. this.setAttribute(name, attribute.clone(data));
  6737. }
  6738. // morph attributes
  6739. const morphAttributes = source.morphAttributes;
  6740. for (const name in morphAttributes) {
  6741. const array = [];
  6742. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6743. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6744. array.push(morphAttribute[i].clone(data));
  6745. }
  6746. this.morphAttributes[name] = array;
  6747. }
  6748. this.morphTargetsRelative = source.morphTargetsRelative;
  6749. // groups
  6750. const groups = source.groups;
  6751. for (let i = 0, l = groups.length; i < l; i++) {
  6752. const group = groups[i];
  6753. this.addGroup(group.start, group.count, group.materialIndex);
  6754. }
  6755. // bounding box
  6756. const boundingBox = source.boundingBox;
  6757. if (boundingBox !== null) {
  6758. this.boundingBox = boundingBox.clone();
  6759. }
  6760. // bounding sphere
  6761. const boundingSphere = source.boundingSphere;
  6762. if (boundingSphere !== null) {
  6763. this.boundingSphere = boundingSphere.clone();
  6764. }
  6765. // draw range
  6766. this.drawRange.start = source.drawRange.start;
  6767. this.drawRange.count = source.drawRange.count;
  6768. // user data
  6769. this.userData = source.userData;
  6770. // geometry generator parameters
  6771. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6772. return this;
  6773. }
  6774. dispose() {
  6775. this.dispatchEvent({
  6776. type: 'dispose'
  6777. });
  6778. }
  6779. }
  6780. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6781. const _ray$2 = /*@__PURE__*/new Ray();
  6782. const _sphere$3 = /*@__PURE__*/new Sphere();
  6783. const _vA$1 = /*@__PURE__*/new Vector3();
  6784. const _vB$1 = /*@__PURE__*/new Vector3();
  6785. const _vC$1 = /*@__PURE__*/new Vector3();
  6786. const _tempA = /*@__PURE__*/new Vector3();
  6787. const _tempB = /*@__PURE__*/new Vector3();
  6788. const _tempC = /*@__PURE__*/new Vector3();
  6789. const _morphA = /*@__PURE__*/new Vector3();
  6790. const _morphB = /*@__PURE__*/new Vector3();
  6791. const _morphC = /*@__PURE__*/new Vector3();
  6792. const _uvA$1 = /*@__PURE__*/new Vector2();
  6793. const _uvB$1 = /*@__PURE__*/new Vector2();
  6794. const _uvC$1 = /*@__PURE__*/new Vector2();
  6795. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6796. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6797. class Mesh extends Object3D {
  6798. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6799. super();
  6800. this.isMesh = true;
  6801. this.type = 'Mesh';
  6802. this.geometry = geometry;
  6803. this.material = material;
  6804. this.updateMorphTargets();
  6805. }
  6806. copy(source, recursive) {
  6807. super.copy(source, recursive);
  6808. if (source.morphTargetInfluences !== undefined) {
  6809. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6810. }
  6811. if (source.morphTargetDictionary !== undefined) {
  6812. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6813. }
  6814. this.material = source.material;
  6815. this.geometry = source.geometry;
  6816. return this;
  6817. }
  6818. updateMorphTargets() {
  6819. const geometry = this.geometry;
  6820. const morphAttributes = geometry.morphAttributes;
  6821. const keys = Object.keys(morphAttributes);
  6822. if (keys.length > 0) {
  6823. const morphAttribute = morphAttributes[keys[0]];
  6824. if (morphAttribute !== undefined) {
  6825. this.morphTargetInfluences = [];
  6826. this.morphTargetDictionary = {};
  6827. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6828. const name = morphAttribute[m].name || String(m);
  6829. this.morphTargetInfluences.push(0);
  6830. this.morphTargetDictionary[name] = m;
  6831. }
  6832. }
  6833. }
  6834. }
  6835. raycast(raycaster, intersects) {
  6836. const geometry = this.geometry;
  6837. const material = this.material;
  6838. const matrixWorld = this.matrixWorld;
  6839. if (material === undefined) return;
  6840. // Checking boundingSphere distance to ray
  6841. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6842. _sphere$3.copy(geometry.boundingSphere);
  6843. _sphere$3.applyMatrix4(matrixWorld);
  6844. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return;
  6845. //
  6846. _inverseMatrix$2.copy(matrixWorld).invert();
  6847. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  6848. // Check boundingBox before continuing
  6849. if (geometry.boundingBox !== null) {
  6850. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6851. }
  6852. let intersection;
  6853. const index = geometry.index;
  6854. const position = geometry.attributes.position;
  6855. const morphPosition = geometry.morphAttributes.position;
  6856. const morphTargetsRelative = geometry.morphTargetsRelative;
  6857. const uv = geometry.attributes.uv;
  6858. const uv2 = geometry.attributes.uv2;
  6859. const groups = geometry.groups;
  6860. const drawRange = geometry.drawRange;
  6861. if (index !== null) {
  6862. // indexed buffer geometry
  6863. if (Array.isArray(material)) {
  6864. for (let i = 0, il = groups.length; i < il; i++) {
  6865. const group = groups[i];
  6866. const groupMaterial = material[group.materialIndex];
  6867. const start = Math.max(group.start, drawRange.start);
  6868. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6869. for (let j = start, jl = end; j < jl; j += 3) {
  6870. const a = index.getX(j);
  6871. const b = index.getX(j + 1);
  6872. const c = index.getX(j + 2);
  6873. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6874. if (intersection) {
  6875. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6876. intersection.face.materialIndex = group.materialIndex;
  6877. intersects.push(intersection);
  6878. }
  6879. }
  6880. }
  6881. } else {
  6882. const start = Math.max(0, drawRange.start);
  6883. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6884. for (let i = start, il = end; i < il; i += 3) {
  6885. const a = index.getX(i);
  6886. const b = index.getX(i + 1);
  6887. const c = index.getX(i + 2);
  6888. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6889. if (intersection) {
  6890. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6891. intersects.push(intersection);
  6892. }
  6893. }
  6894. }
  6895. } else if (position !== undefined) {
  6896. // non-indexed buffer geometry
  6897. if (Array.isArray(material)) {
  6898. for (let i = 0, il = groups.length; i < il; i++) {
  6899. const group = groups[i];
  6900. const groupMaterial = material[group.materialIndex];
  6901. const start = Math.max(group.start, drawRange.start);
  6902. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6903. for (let j = start, jl = end; j < jl; j += 3) {
  6904. const a = j;
  6905. const b = j + 1;
  6906. const c = j + 2;
  6907. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6908. if (intersection) {
  6909. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6910. intersection.face.materialIndex = group.materialIndex;
  6911. intersects.push(intersection);
  6912. }
  6913. }
  6914. }
  6915. } else {
  6916. const start = Math.max(0, drawRange.start);
  6917. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6918. for (let i = start, il = end; i < il; i += 3) {
  6919. const a = i;
  6920. const b = i + 1;
  6921. const c = i + 2;
  6922. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6923. if (intersection) {
  6924. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6925. intersects.push(intersection);
  6926. }
  6927. }
  6928. }
  6929. }
  6930. }
  6931. }
  6932. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6933. let intersect;
  6934. if (material.side === BackSide) {
  6935. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6936. } else {
  6937. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6938. }
  6939. if (intersect === null) return null;
  6940. _intersectionPointWorld.copy(point);
  6941. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6942. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6943. if (distance < raycaster.near || distance > raycaster.far) return null;
  6944. return {
  6945. distance: distance,
  6946. point: _intersectionPointWorld.clone(),
  6947. object: object
  6948. };
  6949. }
  6950. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6951. _vA$1.fromBufferAttribute(position, a);
  6952. _vB$1.fromBufferAttribute(position, b);
  6953. _vC$1.fromBufferAttribute(position, c);
  6954. const morphInfluences = object.morphTargetInfluences;
  6955. if (morphPosition && morphInfluences) {
  6956. _morphA.set(0, 0, 0);
  6957. _morphB.set(0, 0, 0);
  6958. _morphC.set(0, 0, 0);
  6959. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6960. const influence = morphInfluences[i];
  6961. const morphAttribute = morphPosition[i];
  6962. if (influence === 0) continue;
  6963. _tempA.fromBufferAttribute(morphAttribute, a);
  6964. _tempB.fromBufferAttribute(morphAttribute, b);
  6965. _tempC.fromBufferAttribute(morphAttribute, c);
  6966. if (morphTargetsRelative) {
  6967. _morphA.addScaledVector(_tempA, influence);
  6968. _morphB.addScaledVector(_tempB, influence);
  6969. _morphC.addScaledVector(_tempC, influence);
  6970. } else {
  6971. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6972. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6973. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6974. }
  6975. }
  6976. _vA$1.add(_morphA);
  6977. _vB$1.add(_morphB);
  6978. _vC$1.add(_morphC);
  6979. }
  6980. if (object.isSkinnedMesh) {
  6981. object.boneTransform(a, _vA$1);
  6982. object.boneTransform(b, _vB$1);
  6983. object.boneTransform(c, _vC$1);
  6984. }
  6985. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6986. if (intersection) {
  6987. if (uv) {
  6988. _uvA$1.fromBufferAttribute(uv, a);
  6989. _uvB$1.fromBufferAttribute(uv, b);
  6990. _uvC$1.fromBufferAttribute(uv, c);
  6991. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6992. }
  6993. if (uv2) {
  6994. _uvA$1.fromBufferAttribute(uv2, a);
  6995. _uvB$1.fromBufferAttribute(uv2, b);
  6996. _uvC$1.fromBufferAttribute(uv2, c);
  6997. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6998. }
  6999. const face = {
  7000. a: a,
  7001. b: b,
  7002. c: c,
  7003. normal: new Vector3(),
  7004. materialIndex: 0
  7005. };
  7006. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  7007. intersection.face = face;
  7008. }
  7009. return intersection;
  7010. }
  7011. class BoxGeometry extends BufferGeometry {
  7012. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  7013. super();
  7014. this.type = 'BoxGeometry';
  7015. this.parameters = {
  7016. width: width,
  7017. height: height,
  7018. depth: depth,
  7019. widthSegments: widthSegments,
  7020. heightSegments: heightSegments,
  7021. depthSegments: depthSegments
  7022. };
  7023. const scope = this;
  7024. // segments
  7025. widthSegments = Math.floor(widthSegments);
  7026. heightSegments = Math.floor(heightSegments);
  7027. depthSegments = Math.floor(depthSegments);
  7028. // buffers
  7029. const indices = [];
  7030. const vertices = [];
  7031. const normals = [];
  7032. const uvs = [];
  7033. // helper variables
  7034. let numberOfVertices = 0;
  7035. let groupStart = 0;
  7036. // build each side of the box geometry
  7037. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7038. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7039. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7040. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7041. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7042. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7043. // build geometry
  7044. this.setIndex(indices);
  7045. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7046. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7047. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7048. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7049. const segmentWidth = width / gridX;
  7050. const segmentHeight = height / gridY;
  7051. const widthHalf = width / 2;
  7052. const heightHalf = height / 2;
  7053. const depthHalf = depth / 2;
  7054. const gridX1 = gridX + 1;
  7055. const gridY1 = gridY + 1;
  7056. let vertexCounter = 0;
  7057. let groupCount = 0;
  7058. const vector = new Vector3();
  7059. // generate vertices, normals and uvs
  7060. for (let iy = 0; iy < gridY1; iy++) {
  7061. const y = iy * segmentHeight - heightHalf;
  7062. for (let ix = 0; ix < gridX1; ix++) {
  7063. const x = ix * segmentWidth - widthHalf;
  7064. // set values to correct vector component
  7065. vector[u] = x * udir;
  7066. vector[v] = y * vdir;
  7067. vector[w] = depthHalf;
  7068. // now apply vector to vertex buffer
  7069. vertices.push(vector.x, vector.y, vector.z);
  7070. // set values to correct vector component
  7071. vector[u] = 0;
  7072. vector[v] = 0;
  7073. vector[w] = depth > 0 ? 1 : -1;
  7074. // now apply vector to normal buffer
  7075. normals.push(vector.x, vector.y, vector.z);
  7076. // uvs
  7077. uvs.push(ix / gridX);
  7078. uvs.push(1 - iy / gridY);
  7079. // counters
  7080. vertexCounter += 1;
  7081. }
  7082. }
  7083. // indices
  7084. // 1. you need three indices to draw a single face
  7085. // 2. a single segment consists of two faces
  7086. // 3. so we need to generate six (2*3) indices per segment
  7087. for (let iy = 0; iy < gridY; iy++) {
  7088. for (let ix = 0; ix < gridX; ix++) {
  7089. const a = numberOfVertices + ix + gridX1 * iy;
  7090. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7091. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7092. const d = numberOfVertices + (ix + 1) + gridX1 * iy;
  7093. // faces
  7094. indices.push(a, b, d);
  7095. indices.push(b, c, d);
  7096. // increase counter
  7097. groupCount += 6;
  7098. }
  7099. }
  7100. // add a group to the geometry. this will ensure multi material support
  7101. scope.addGroup(groupStart, groupCount, materialIndex);
  7102. // calculate new start value for groups
  7103. groupStart += groupCount;
  7104. // update total number of vertices
  7105. numberOfVertices += vertexCounter;
  7106. }
  7107. }
  7108. static fromJSON(data) {
  7109. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  7110. }
  7111. }
  7112. /**
  7113. * Uniform Utilities
  7114. */
  7115. function cloneUniforms(src) {
  7116. const dst = {};
  7117. for (const u in src) {
  7118. dst[u] = {};
  7119. for (const p in src[u]) {
  7120. const property = src[u][p];
  7121. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7122. dst[u][p] = property.clone();
  7123. } else if (Array.isArray(property)) {
  7124. dst[u][p] = property.slice();
  7125. } else {
  7126. dst[u][p] = property;
  7127. }
  7128. }
  7129. }
  7130. return dst;
  7131. }
  7132. function mergeUniforms(uniforms) {
  7133. const merged = {};
  7134. for (let u = 0; u < uniforms.length; u++) {
  7135. const tmp = cloneUniforms(uniforms[u]);
  7136. for (const p in tmp) {
  7137. merged[p] = tmp[p];
  7138. }
  7139. }
  7140. return merged;
  7141. }
  7142. function cloneUniformsGroups(src) {
  7143. const dst = [];
  7144. for (let u = 0; u < src.length; u++) {
  7145. dst.push(src[u].clone());
  7146. }
  7147. return dst;
  7148. }
  7149. function getUnlitUniformColorSpace(renderer) {
  7150. if (renderer.getRenderTarget() === null) {
  7151. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7152. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  7153. }
  7154. return LinearSRGBColorSpace;
  7155. }
  7156. // Legacy
  7157. const UniformsUtils = {
  7158. clone: cloneUniforms,
  7159. merge: mergeUniforms
  7160. };
  7161. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7162. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7163. class ShaderMaterial extends Material {
  7164. constructor(parameters) {
  7165. super();
  7166. this.isShaderMaterial = true;
  7167. this.type = 'ShaderMaterial';
  7168. this.defines = {};
  7169. this.uniforms = {};
  7170. this.uniformsGroups = [];
  7171. this.vertexShader = default_vertex;
  7172. this.fragmentShader = default_fragment;
  7173. this.linewidth = 1;
  7174. this.wireframe = false;
  7175. this.wireframeLinewidth = 1;
  7176. this.fog = false; // set to use scene fog
  7177. this.lights = false; // set to use scene lights
  7178. this.clipping = false; // set to use user-defined clipping planes
  7179. this.extensions = {
  7180. derivatives: false,
  7181. // set to use derivatives
  7182. fragDepth: false,
  7183. // set to use fragment depth values
  7184. drawBuffers: false,
  7185. // set to use draw buffers
  7186. shaderTextureLOD: false // set to use shader texture LOD
  7187. };
  7188. // When rendered geometry doesn't include these attributes but the material does,
  7189. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7190. this.defaultAttributeValues = {
  7191. 'color': [1, 1, 1],
  7192. 'uv': [0, 0],
  7193. 'uv2': [0, 0]
  7194. };
  7195. this.index0AttributeName = undefined;
  7196. this.uniformsNeedUpdate = false;
  7197. this.glslVersion = null;
  7198. if (parameters !== undefined) {
  7199. this.setValues(parameters);
  7200. }
  7201. }
  7202. copy(source) {
  7203. super.copy(source);
  7204. this.fragmentShader = source.fragmentShader;
  7205. this.vertexShader = source.vertexShader;
  7206. this.uniforms = cloneUniforms(source.uniforms);
  7207. this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
  7208. this.defines = Object.assign({}, source.defines);
  7209. this.wireframe = source.wireframe;
  7210. this.wireframeLinewidth = source.wireframeLinewidth;
  7211. this.fog = source.fog;
  7212. this.lights = source.lights;
  7213. this.clipping = source.clipping;
  7214. this.extensions = Object.assign({}, source.extensions);
  7215. this.glslVersion = source.glslVersion;
  7216. return this;
  7217. }
  7218. toJSON(meta) {
  7219. const data = super.toJSON(meta);
  7220. data.glslVersion = this.glslVersion;
  7221. data.uniforms = {};
  7222. for (const name in this.uniforms) {
  7223. const uniform = this.uniforms[name];
  7224. const value = uniform.value;
  7225. if (value && value.isTexture) {
  7226. data.uniforms[name] = {
  7227. type: 't',
  7228. value: value.toJSON(meta).uuid
  7229. };
  7230. } else if (value && value.isColor) {
  7231. data.uniforms[name] = {
  7232. type: 'c',
  7233. value: value.getHex()
  7234. };
  7235. } else if (value && value.isVector2) {
  7236. data.uniforms[name] = {
  7237. type: 'v2',
  7238. value: value.toArray()
  7239. };
  7240. } else if (value && value.isVector3) {
  7241. data.uniforms[name] = {
  7242. type: 'v3',
  7243. value: value.toArray()
  7244. };
  7245. } else if (value && value.isVector4) {
  7246. data.uniforms[name] = {
  7247. type: 'v4',
  7248. value: value.toArray()
  7249. };
  7250. } else if (value && value.isMatrix3) {
  7251. data.uniforms[name] = {
  7252. type: 'm3',
  7253. value: value.toArray()
  7254. };
  7255. } else if (value && value.isMatrix4) {
  7256. data.uniforms[name] = {
  7257. type: 'm4',
  7258. value: value.toArray()
  7259. };
  7260. } else {
  7261. data.uniforms[name] = {
  7262. value: value
  7263. };
  7264. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7265. }
  7266. }
  7267. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7268. data.vertexShader = this.vertexShader;
  7269. data.fragmentShader = this.fragmentShader;
  7270. const extensions = {};
  7271. for (const key in this.extensions) {
  7272. if (this.extensions[key] === true) extensions[key] = true;
  7273. }
  7274. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7275. return data;
  7276. }
  7277. }
  7278. class Camera extends Object3D {
  7279. constructor() {
  7280. super();
  7281. this.isCamera = true;
  7282. this.type = 'Camera';
  7283. this.matrixWorldInverse = new Matrix4();
  7284. this.projectionMatrix = new Matrix4();
  7285. this.projectionMatrixInverse = new Matrix4();
  7286. }
  7287. copy(source, recursive) {
  7288. super.copy(source, recursive);
  7289. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7290. this.projectionMatrix.copy(source.projectionMatrix);
  7291. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7292. return this;
  7293. }
  7294. getWorldDirection(target) {
  7295. this.updateWorldMatrix(true, false);
  7296. const e = this.matrixWorld.elements;
  7297. return target.set(-e[8], -e[9], -e[10]).normalize();
  7298. }
  7299. updateMatrixWorld(force) {
  7300. super.updateMatrixWorld(force);
  7301. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7302. }
  7303. updateWorldMatrix(updateParents, updateChildren) {
  7304. super.updateWorldMatrix(updateParents, updateChildren);
  7305. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7306. }
  7307. clone() {
  7308. return new this.constructor().copy(this);
  7309. }
  7310. }
  7311. class PerspectiveCamera extends Camera {
  7312. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7313. super();
  7314. this.isPerspectiveCamera = true;
  7315. this.type = 'PerspectiveCamera';
  7316. this.fov = fov;
  7317. this.zoom = 1;
  7318. this.near = near;
  7319. this.far = far;
  7320. this.focus = 10;
  7321. this.aspect = aspect;
  7322. this.view = null;
  7323. this.filmGauge = 35; // width of the film (default in millimeters)
  7324. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7325. this.updateProjectionMatrix();
  7326. }
  7327. copy(source, recursive) {
  7328. super.copy(source, recursive);
  7329. this.fov = source.fov;
  7330. this.zoom = source.zoom;
  7331. this.near = source.near;
  7332. this.far = source.far;
  7333. this.focus = source.focus;
  7334. this.aspect = source.aspect;
  7335. this.view = source.view === null ? null : Object.assign({}, source.view);
  7336. this.filmGauge = source.filmGauge;
  7337. this.filmOffset = source.filmOffset;
  7338. return this;
  7339. }
  7340. /**
  7341. * Sets the FOV by focal length in respect to the current .filmGauge.
  7342. *
  7343. * The default film gauge is 35, so that the focal length can be specified for
  7344. * a 35mm (full frame) camera.
  7345. *
  7346. * Values for focal length and film gauge must have the same unit.
  7347. */
  7348. setFocalLength(focalLength) {
  7349. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7350. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7351. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7352. this.updateProjectionMatrix();
  7353. }
  7354. /**
  7355. * Calculates the focal length from the current .fov and .filmGauge.
  7356. */
  7357. getFocalLength() {
  7358. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7359. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7360. }
  7361. getEffectiveFOV() {
  7362. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7363. }
  7364. getFilmWidth() {
  7365. // film not completely covered in portrait format (aspect < 1)
  7366. return this.filmGauge * Math.min(this.aspect, 1);
  7367. }
  7368. getFilmHeight() {
  7369. // film not completely covered in landscape format (aspect > 1)
  7370. return this.filmGauge / Math.max(this.aspect, 1);
  7371. }
  7372. /**
  7373. * Sets an offset in a larger frustum. This is useful for multi-window or
  7374. * multi-monitor/multi-machine setups.
  7375. *
  7376. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7377. * the monitors are in grid like this
  7378. *
  7379. * +---+---+---+
  7380. * | A | B | C |
  7381. * +---+---+---+
  7382. * | D | E | F |
  7383. * +---+---+---+
  7384. *
  7385. * then for each monitor you would call it like this
  7386. *
  7387. * const w = 1920;
  7388. * const h = 1080;
  7389. * const fullWidth = w * 3;
  7390. * const fullHeight = h * 2;
  7391. *
  7392. * --A--
  7393. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7394. * --B--
  7395. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7396. * --C--
  7397. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7398. * --D--
  7399. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7400. * --E--
  7401. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7402. * --F--
  7403. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7404. *
  7405. * Note there is no reason monitors have to be the same size or in a grid.
  7406. */
  7407. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7408. this.aspect = fullWidth / fullHeight;
  7409. if (this.view === null) {
  7410. this.view = {
  7411. enabled: true,
  7412. fullWidth: 1,
  7413. fullHeight: 1,
  7414. offsetX: 0,
  7415. offsetY: 0,
  7416. width: 1,
  7417. height: 1
  7418. };
  7419. }
  7420. this.view.enabled = true;
  7421. this.view.fullWidth = fullWidth;
  7422. this.view.fullHeight = fullHeight;
  7423. this.view.offsetX = x;
  7424. this.view.offsetY = y;
  7425. this.view.width = width;
  7426. this.view.height = height;
  7427. this.updateProjectionMatrix();
  7428. }
  7429. clearViewOffset() {
  7430. if (this.view !== null) {
  7431. this.view.enabled = false;
  7432. }
  7433. this.updateProjectionMatrix();
  7434. }
  7435. updateProjectionMatrix() {
  7436. const near = this.near;
  7437. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7438. let height = 2 * top;
  7439. let width = this.aspect * height;
  7440. let left = -0.5 * width;
  7441. const view = this.view;
  7442. if (this.view !== null && this.view.enabled) {
  7443. const fullWidth = view.fullWidth,
  7444. fullHeight = view.fullHeight;
  7445. left += view.offsetX * width / fullWidth;
  7446. top -= view.offsetY * height / fullHeight;
  7447. width *= view.width / fullWidth;
  7448. height *= view.height / fullHeight;
  7449. }
  7450. const skew = this.filmOffset;
  7451. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7452. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7453. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7454. }
  7455. toJSON(meta) {
  7456. const data = super.toJSON(meta);
  7457. data.object.fov = this.fov;
  7458. data.object.zoom = this.zoom;
  7459. data.object.near = this.near;
  7460. data.object.far = this.far;
  7461. data.object.focus = this.focus;
  7462. data.object.aspect = this.aspect;
  7463. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7464. data.object.filmGauge = this.filmGauge;
  7465. data.object.filmOffset = this.filmOffset;
  7466. return data;
  7467. }
  7468. }
  7469. const fov = -90; // negative fov is not an error
  7470. const aspect = 1;
  7471. class CubeCamera extends Object3D {
  7472. constructor(near, far, renderTarget) {
  7473. super();
  7474. this.type = 'CubeCamera';
  7475. this.renderTarget = renderTarget;
  7476. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7477. cameraPX.layers = this.layers;
  7478. cameraPX.up.set(0, 1, 0);
  7479. cameraPX.lookAt(1, 0, 0);
  7480. this.add(cameraPX);
  7481. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7482. cameraNX.layers = this.layers;
  7483. cameraNX.up.set(0, 1, 0);
  7484. cameraNX.lookAt(-1, 0, 0);
  7485. this.add(cameraNX);
  7486. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7487. cameraPY.layers = this.layers;
  7488. cameraPY.up.set(0, 0, -1);
  7489. cameraPY.lookAt(0, 1, 0);
  7490. this.add(cameraPY);
  7491. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7492. cameraNY.layers = this.layers;
  7493. cameraNY.up.set(0, 0, 1);
  7494. cameraNY.lookAt(0, -1, 0);
  7495. this.add(cameraNY);
  7496. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7497. cameraPZ.layers = this.layers;
  7498. cameraPZ.up.set(0, 1, 0);
  7499. cameraPZ.lookAt(0, 0, 1);
  7500. this.add(cameraPZ);
  7501. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7502. cameraNZ.layers = this.layers;
  7503. cameraNZ.up.set(0, 1, 0);
  7504. cameraNZ.lookAt(0, 0, -1);
  7505. this.add(cameraNZ);
  7506. }
  7507. update(renderer, scene) {
  7508. if (this.parent === null) this.updateMatrixWorld();
  7509. const renderTarget = this.renderTarget;
  7510. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7511. const currentRenderTarget = renderer.getRenderTarget();
  7512. const currentToneMapping = renderer.toneMapping;
  7513. const currentXrEnabled = renderer.xr.enabled;
  7514. renderer.toneMapping = NoToneMapping;
  7515. renderer.xr.enabled = false;
  7516. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7517. renderTarget.texture.generateMipmaps = false;
  7518. renderer.setRenderTarget(renderTarget, 0);
  7519. renderer.render(scene, cameraPX);
  7520. renderer.setRenderTarget(renderTarget, 1);
  7521. renderer.render(scene, cameraNX);
  7522. renderer.setRenderTarget(renderTarget, 2);
  7523. renderer.render(scene, cameraPY);
  7524. renderer.setRenderTarget(renderTarget, 3);
  7525. renderer.render(scene, cameraNY);
  7526. renderer.setRenderTarget(renderTarget, 4);
  7527. renderer.render(scene, cameraPZ);
  7528. renderTarget.texture.generateMipmaps = generateMipmaps;
  7529. renderer.setRenderTarget(renderTarget, 5);
  7530. renderer.render(scene, cameraNZ);
  7531. renderer.setRenderTarget(currentRenderTarget);
  7532. renderer.toneMapping = currentToneMapping;
  7533. renderer.xr.enabled = currentXrEnabled;
  7534. renderTarget.texture.needsPMREMUpdate = true;
  7535. }
  7536. }
  7537. class CubeTexture extends Texture {
  7538. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7539. images = images !== undefined ? images : [];
  7540. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7541. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7542. this.isCubeTexture = true;
  7543. this.flipY = false;
  7544. }
  7545. get images() {
  7546. return this.image;
  7547. }
  7548. set images(value) {
  7549. this.image = value;
  7550. }
  7551. }
  7552. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7553. constructor(size = 1, options = {}) {
  7554. super(size, size, options);
  7555. this.isWebGLCubeRenderTarget = true;
  7556. const image = {
  7557. width: size,
  7558. height: size,
  7559. depth: 1
  7560. };
  7561. const images = [image, image, image, image, image, image];
  7562. this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7563. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7564. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7565. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7566. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7567. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7568. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7569. this.texture.isRenderTargetTexture = true;
  7570. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7571. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7572. }
  7573. fromEquirectangularTexture(renderer, texture) {
  7574. this.texture.type = texture.type;
  7575. this.texture.encoding = texture.encoding;
  7576. this.texture.generateMipmaps = texture.generateMipmaps;
  7577. this.texture.minFilter = texture.minFilter;
  7578. this.texture.magFilter = texture.magFilter;
  7579. const shader = {
  7580. uniforms: {
  7581. tEquirect: {
  7582. value: null
  7583. }
  7584. },
  7585. vertexShader: /* glsl */`
  7586. varying vec3 vWorldDirection;
  7587. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7588. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7589. }
  7590. void main() {
  7591. vWorldDirection = transformDirection( position, modelMatrix );
  7592. #include <begin_vertex>
  7593. #include <project_vertex>
  7594. }
  7595. `,
  7596. fragmentShader: /* glsl */`
  7597. uniform sampler2D tEquirect;
  7598. varying vec3 vWorldDirection;
  7599. #include <common>
  7600. void main() {
  7601. vec3 direction = normalize( vWorldDirection );
  7602. vec2 sampleUV = equirectUv( direction );
  7603. gl_FragColor = texture2D( tEquirect, sampleUV );
  7604. }
  7605. `
  7606. };
  7607. const geometry = new BoxGeometry(5, 5, 5);
  7608. const material = new ShaderMaterial({
  7609. name: 'CubemapFromEquirect',
  7610. uniforms: cloneUniforms(shader.uniforms),
  7611. vertexShader: shader.vertexShader,
  7612. fragmentShader: shader.fragmentShader,
  7613. side: BackSide,
  7614. blending: NoBlending
  7615. });
  7616. material.uniforms.tEquirect.value = texture;
  7617. const mesh = new Mesh(geometry, material);
  7618. const currentMinFilter = texture.minFilter;
  7619. // Avoid blurred poles
  7620. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7621. const camera = new CubeCamera(1, 10, this);
  7622. camera.update(renderer, mesh);
  7623. texture.minFilter = currentMinFilter;
  7624. mesh.geometry.dispose();
  7625. mesh.material.dispose();
  7626. return this;
  7627. }
  7628. clear(renderer, color, depth, stencil) {
  7629. const currentRenderTarget = renderer.getRenderTarget();
  7630. for (let i = 0; i < 6; i++) {
  7631. renderer.setRenderTarget(this, i);
  7632. renderer.clear(color, depth, stencil);
  7633. }
  7634. renderer.setRenderTarget(currentRenderTarget);
  7635. }
  7636. }
  7637. const _vector1 = /*@__PURE__*/new Vector3();
  7638. const _vector2 = /*@__PURE__*/new Vector3();
  7639. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7640. class Plane {
  7641. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7642. this.isPlane = true;
  7643. // normal is assumed to be normalized
  7644. this.normal = normal;
  7645. this.constant = constant;
  7646. }
  7647. set(normal, constant) {
  7648. this.normal.copy(normal);
  7649. this.constant = constant;
  7650. return this;
  7651. }
  7652. setComponents(x, y, z, w) {
  7653. this.normal.set(x, y, z);
  7654. this.constant = w;
  7655. return this;
  7656. }
  7657. setFromNormalAndCoplanarPoint(normal, point) {
  7658. this.normal.copy(normal);
  7659. this.constant = -point.dot(this.normal);
  7660. return this;
  7661. }
  7662. setFromCoplanarPoints(a, b, c) {
  7663. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize();
  7664. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7665. this.setFromNormalAndCoplanarPoint(normal, a);
  7666. return this;
  7667. }
  7668. copy(plane) {
  7669. this.normal.copy(plane.normal);
  7670. this.constant = plane.constant;
  7671. return this;
  7672. }
  7673. normalize() {
  7674. // Note: will lead to a divide by zero if the plane is invalid.
  7675. const inverseNormalLength = 1.0 / this.normal.length();
  7676. this.normal.multiplyScalar(inverseNormalLength);
  7677. this.constant *= inverseNormalLength;
  7678. return this;
  7679. }
  7680. negate() {
  7681. this.constant *= -1;
  7682. this.normal.negate();
  7683. return this;
  7684. }
  7685. distanceToPoint(point) {
  7686. return this.normal.dot(point) + this.constant;
  7687. }
  7688. distanceToSphere(sphere) {
  7689. return this.distanceToPoint(sphere.center) - sphere.radius;
  7690. }
  7691. projectPoint(point, target) {
  7692. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7693. }
  7694. intersectLine(line, target) {
  7695. const direction = line.delta(_vector1);
  7696. const denominator = this.normal.dot(direction);
  7697. if (denominator === 0) {
  7698. // line is coplanar, return origin
  7699. if (this.distanceToPoint(line.start) === 0) {
  7700. return target.copy(line.start);
  7701. }
  7702. // Unsure if this is the correct method to handle this case.
  7703. return null;
  7704. }
  7705. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7706. if (t < 0 || t > 1) {
  7707. return null;
  7708. }
  7709. return target.copy(direction).multiplyScalar(t).add(line.start);
  7710. }
  7711. intersectsLine(line) {
  7712. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7713. const startSign = this.distanceToPoint(line.start);
  7714. const endSign = this.distanceToPoint(line.end);
  7715. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7716. }
  7717. intersectsBox(box) {
  7718. return box.intersectsPlane(this);
  7719. }
  7720. intersectsSphere(sphere) {
  7721. return sphere.intersectsPlane(this);
  7722. }
  7723. coplanarPoint(target) {
  7724. return target.copy(this.normal).multiplyScalar(-this.constant);
  7725. }
  7726. applyMatrix4(matrix, optionalNormalMatrix) {
  7727. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7728. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7729. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7730. this.constant = -referencePoint.dot(normal);
  7731. return this;
  7732. }
  7733. translate(offset) {
  7734. this.constant -= offset.dot(this.normal);
  7735. return this;
  7736. }
  7737. equals(plane) {
  7738. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7739. }
  7740. clone() {
  7741. return new this.constructor().copy(this);
  7742. }
  7743. }
  7744. const _sphere$2 = /*@__PURE__*/new Sphere();
  7745. const _vector$7 = /*@__PURE__*/new Vector3();
  7746. class Frustum {
  7747. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7748. this.planes = [p0, p1, p2, p3, p4, p5];
  7749. }
  7750. set(p0, p1, p2, p3, p4, p5) {
  7751. const planes = this.planes;
  7752. planes[0].copy(p0);
  7753. planes[1].copy(p1);
  7754. planes[2].copy(p2);
  7755. planes[3].copy(p3);
  7756. planes[4].copy(p4);
  7757. planes[5].copy(p5);
  7758. return this;
  7759. }
  7760. copy(frustum) {
  7761. const planes = this.planes;
  7762. for (let i = 0; i < 6; i++) {
  7763. planes[i].copy(frustum.planes[i]);
  7764. }
  7765. return this;
  7766. }
  7767. setFromProjectionMatrix(m) {
  7768. const planes = this.planes;
  7769. const me = m.elements;
  7770. const me0 = me[0],
  7771. me1 = me[1],
  7772. me2 = me[2],
  7773. me3 = me[3];
  7774. const me4 = me[4],
  7775. me5 = me[5],
  7776. me6 = me[6],
  7777. me7 = me[7];
  7778. const me8 = me[8],
  7779. me9 = me[9],
  7780. me10 = me[10],
  7781. me11 = me[11];
  7782. const me12 = me[12],
  7783. me13 = me[13],
  7784. me14 = me[14],
  7785. me15 = me[15];
  7786. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7787. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7788. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7789. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7790. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7791. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7792. return this;
  7793. }
  7794. intersectsObject(object) {
  7795. const geometry = object.geometry;
  7796. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7797. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7798. return this.intersectsSphere(_sphere$2);
  7799. }
  7800. intersectsSprite(sprite) {
  7801. _sphere$2.center.set(0, 0, 0);
  7802. _sphere$2.radius = 0.7071067811865476;
  7803. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7804. return this.intersectsSphere(_sphere$2);
  7805. }
  7806. intersectsSphere(sphere) {
  7807. const planes = this.planes;
  7808. const center = sphere.center;
  7809. const negRadius = -sphere.radius;
  7810. for (let i = 0; i < 6; i++) {
  7811. const distance = planes[i].distanceToPoint(center);
  7812. if (distance < negRadius) {
  7813. return false;
  7814. }
  7815. }
  7816. return true;
  7817. }
  7818. intersectsBox(box) {
  7819. const planes = this.planes;
  7820. for (let i = 0; i < 6; i++) {
  7821. const plane = planes[i];
  7822. // corner at max distance
  7823. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7824. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7825. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7826. if (plane.distanceToPoint(_vector$7) < 0) {
  7827. return false;
  7828. }
  7829. }
  7830. return true;
  7831. }
  7832. containsPoint(point) {
  7833. const planes = this.planes;
  7834. for (let i = 0; i < 6; i++) {
  7835. if (planes[i].distanceToPoint(point) < 0) {
  7836. return false;
  7837. }
  7838. }
  7839. return true;
  7840. }
  7841. clone() {
  7842. return new this.constructor().copy(this);
  7843. }
  7844. }
  7845. function WebGLAnimation() {
  7846. let context = null;
  7847. let isAnimating = false;
  7848. let animationLoop = null;
  7849. let requestId = null;
  7850. function onAnimationFrame(time, frame) {
  7851. animationLoop(time, frame);
  7852. requestId = context.requestAnimationFrame(onAnimationFrame);
  7853. }
  7854. return {
  7855. start: function () {
  7856. if (isAnimating === true) return;
  7857. if (animationLoop === null) return;
  7858. requestId = context.requestAnimationFrame(onAnimationFrame);
  7859. isAnimating = true;
  7860. },
  7861. stop: function () {
  7862. context.cancelAnimationFrame(requestId);
  7863. isAnimating = false;
  7864. },
  7865. setAnimationLoop: function (callback) {
  7866. animationLoop = callback;
  7867. },
  7868. setContext: function (value) {
  7869. context = value;
  7870. }
  7871. };
  7872. }
  7873. function WebGLAttributes(gl, capabilities) {
  7874. const isWebGL2 = capabilities.isWebGL2;
  7875. const buffers = new WeakMap();
  7876. function createBuffer(attribute, bufferType) {
  7877. const array = attribute.array;
  7878. const usage = attribute.usage;
  7879. const buffer = gl.createBuffer();
  7880. gl.bindBuffer(bufferType, buffer);
  7881. gl.bufferData(bufferType, array, usage);
  7882. attribute.onUploadCallback();
  7883. let type;
  7884. if (array instanceof Float32Array) {
  7885. type = gl.FLOAT;
  7886. } else if (array instanceof Uint16Array) {
  7887. if (attribute.isFloat16BufferAttribute) {
  7888. if (isWebGL2) {
  7889. type = gl.HALF_FLOAT;
  7890. } else {
  7891. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7892. }
  7893. } else {
  7894. type = gl.UNSIGNED_SHORT;
  7895. }
  7896. } else if (array instanceof Int16Array) {
  7897. type = gl.SHORT;
  7898. } else if (array instanceof Uint32Array) {
  7899. type = gl.UNSIGNED_INT;
  7900. } else if (array instanceof Int32Array) {
  7901. type = gl.INT;
  7902. } else if (array instanceof Int8Array) {
  7903. type = gl.BYTE;
  7904. } else if (array instanceof Uint8Array) {
  7905. type = gl.UNSIGNED_BYTE;
  7906. } else if (array instanceof Uint8ClampedArray) {
  7907. type = gl.UNSIGNED_BYTE;
  7908. } else {
  7909. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7910. }
  7911. return {
  7912. buffer: buffer,
  7913. type: type,
  7914. bytesPerElement: array.BYTES_PER_ELEMENT,
  7915. version: attribute.version
  7916. };
  7917. }
  7918. function updateBuffer(buffer, attribute, bufferType) {
  7919. const array = attribute.array;
  7920. const updateRange = attribute.updateRange;
  7921. gl.bindBuffer(bufferType, buffer);
  7922. if (updateRange.count === -1) {
  7923. // Not using update ranges
  7924. gl.bufferSubData(bufferType, 0, array);
  7925. } else {
  7926. if (isWebGL2) {
  7927. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7928. } else {
  7929. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7930. }
  7931. updateRange.count = -1; // reset range
  7932. }
  7933. attribute.onUploadCallback();
  7934. }
  7935. //
  7936. function get(attribute) {
  7937. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7938. return buffers.get(attribute);
  7939. }
  7940. function remove(attribute) {
  7941. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7942. const data = buffers.get(attribute);
  7943. if (data) {
  7944. gl.deleteBuffer(data.buffer);
  7945. buffers.delete(attribute);
  7946. }
  7947. }
  7948. function update(attribute, bufferType) {
  7949. if (attribute.isGLBufferAttribute) {
  7950. const cached = buffers.get(attribute);
  7951. if (!cached || cached.version < attribute.version) {
  7952. buffers.set(attribute, {
  7953. buffer: attribute.buffer,
  7954. type: attribute.type,
  7955. bytesPerElement: attribute.elementSize,
  7956. version: attribute.version
  7957. });
  7958. }
  7959. return;
  7960. }
  7961. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7962. const data = buffers.get(attribute);
  7963. if (data === undefined) {
  7964. buffers.set(attribute, createBuffer(attribute, bufferType));
  7965. } else if (data.version < attribute.version) {
  7966. updateBuffer(data.buffer, attribute, bufferType);
  7967. data.version = attribute.version;
  7968. }
  7969. }
  7970. return {
  7971. get: get,
  7972. remove: remove,
  7973. update: update
  7974. };
  7975. }
  7976. class PlaneGeometry extends BufferGeometry {
  7977. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7978. super();
  7979. this.type = 'PlaneGeometry';
  7980. this.parameters = {
  7981. width: width,
  7982. height: height,
  7983. widthSegments: widthSegments,
  7984. heightSegments: heightSegments
  7985. };
  7986. const width_half = width / 2;
  7987. const height_half = height / 2;
  7988. const gridX = Math.floor(widthSegments);
  7989. const gridY = Math.floor(heightSegments);
  7990. const gridX1 = gridX + 1;
  7991. const gridY1 = gridY + 1;
  7992. const segment_width = width / gridX;
  7993. const segment_height = height / gridY;
  7994. //
  7995. const indices = [];
  7996. const vertices = [];
  7997. const normals = [];
  7998. const uvs = [];
  7999. for (let iy = 0; iy < gridY1; iy++) {
  8000. const y = iy * segment_height - height_half;
  8001. for (let ix = 0; ix < gridX1; ix++) {
  8002. const x = ix * segment_width - width_half;
  8003. vertices.push(x, -y, 0);
  8004. normals.push(0, 0, 1);
  8005. uvs.push(ix / gridX);
  8006. uvs.push(1 - iy / gridY);
  8007. }
  8008. }
  8009. for (let iy = 0; iy < gridY; iy++) {
  8010. for (let ix = 0; ix < gridX; ix++) {
  8011. const a = ix + gridX1 * iy;
  8012. const b = ix + gridX1 * (iy + 1);
  8013. const c = ix + 1 + gridX1 * (iy + 1);
  8014. const d = ix + 1 + gridX1 * iy;
  8015. indices.push(a, b, d);
  8016. indices.push(b, c, d);
  8017. }
  8018. }
  8019. this.setIndex(indices);
  8020. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8021. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8022. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8023. }
  8024. static fromJSON(data) {
  8025. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  8026. }
  8027. }
  8028. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8029. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8030. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8031. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8032. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  8033. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8034. var begin_vertex = "vec3 transformed = vec3( position );";
  8035. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8036. var bsdfs = "vec3 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}\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}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float 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\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\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 = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\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\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}\nfloat 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}\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";
  8037. 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\t return 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 R21 = R12;\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";
  8038. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + 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 = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = 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";
  8039. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8040. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8041. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8042. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8043. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8044. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8045. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8046. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_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";
  8047. 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};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\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}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\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}";
  8048. 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\tvec2 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_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\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";
  8049. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8050. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8051. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8052. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8053. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8054. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8055. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( 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}";
  8056. 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, 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";
  8057. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  8058. 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";
  8059. 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";
  8060. 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";
  8061. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8062. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8063. 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";
  8064. 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";
  8065. 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}";
  8066. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8067. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8068. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8069. 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 GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, 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 GeometricContext geometry, 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";
  8070. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\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\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\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, const in GeometricContext geometry, 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 GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\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 GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\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";
  8071. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, 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#if defined( 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, 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#endif";
  8072. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8073. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, 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";
  8074. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8075. 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 GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, 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";
  8076. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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 SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\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, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).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_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).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_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  8077. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\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};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, 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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, 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( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, 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}";
  8078. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\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, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, 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, geometry, 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 *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, 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, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, 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, geometry, 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\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\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 ], geometry.normal );\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";
  8079. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\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( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8080. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  8081. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8082. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8083. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8084. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  8085. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8086. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8087. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\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";
  8088. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8089. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8090. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8091. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\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";
  8092. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  8093. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  8094. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  8095. 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 = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8096. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).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( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8097. 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";
  8098. 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";
  8099. 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";
  8100. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.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 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  8101. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8102. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  8103. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  8104. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8105. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8106. 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.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( 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( 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 linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( 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 invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  8107. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8108. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8109. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8110. 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";
  8111. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8112. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8113. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform 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 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 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 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 shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\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 shadow;\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 shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8114. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying 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 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 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 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";
  8115. var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#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\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  8116. 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.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.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.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}";
  8117. 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";
  8118. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  8119. 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";
  8120. 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";
  8121. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8122. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8123. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8124. 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 toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( 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}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8125. 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, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  8126. 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\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 framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\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 ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  8127. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8128. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  8129. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8130. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8131. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  8132. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8133. 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_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8134. 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}";
  8135. 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 <encodings_fragment>\n}";
  8136. 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}";
  8137. 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;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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 <encodings_fragment>\n}";
  8138. 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}";
  8139. 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 <encodings_fragment>\n}";
  8140. const vertex$e = "#include <common>\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 <skinbase_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}";
  8141. 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 <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\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 <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#endif\n}";
  8142. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\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 <skinbase_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}";
  8143. 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 <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8144. 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}";
  8145. 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 <encodings_fragment>\n}";
  8146. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\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>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_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}";
  8147. 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 <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8148. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8149. 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 <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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, vUv2 );\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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8150. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8151. 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 <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8152. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\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 <morphcolor_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}";
  8153. 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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8154. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\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 <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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8155. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\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\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 ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8156. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8157. 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 <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8158. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8159. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define 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 SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\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_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\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 <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8160. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8161. 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 <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8162. 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>\nvoid main() {\n\t#include <color_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}";
  8163. 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 <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8164. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\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 <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8165. 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 <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8166. 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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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}";
  8167. 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 <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8168. const ShaderChunk = {
  8169. alphamap_fragment: alphamap_fragment,
  8170. alphamap_pars_fragment: alphamap_pars_fragment,
  8171. alphatest_fragment: alphatest_fragment,
  8172. alphatest_pars_fragment: alphatest_pars_fragment,
  8173. aomap_fragment: aomap_fragment,
  8174. aomap_pars_fragment: aomap_pars_fragment,
  8175. begin_vertex: begin_vertex,
  8176. beginnormal_vertex: beginnormal_vertex,
  8177. bsdfs: bsdfs,
  8178. iridescence_fragment: iridescence_fragment,
  8179. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8180. clipping_planes_fragment: clipping_planes_fragment,
  8181. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8182. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8183. clipping_planes_vertex: clipping_planes_vertex,
  8184. color_fragment: color_fragment,
  8185. color_pars_fragment: color_pars_fragment,
  8186. color_pars_vertex: color_pars_vertex,
  8187. color_vertex: color_vertex,
  8188. common: common,
  8189. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8190. defaultnormal_vertex: defaultnormal_vertex,
  8191. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8192. displacementmap_vertex: displacementmap_vertex,
  8193. emissivemap_fragment: emissivemap_fragment,
  8194. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8195. encodings_fragment: encodings_fragment,
  8196. encodings_pars_fragment: encodings_pars_fragment,
  8197. envmap_fragment: envmap_fragment,
  8198. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8199. envmap_pars_fragment: envmap_pars_fragment,
  8200. envmap_pars_vertex: envmap_pars_vertex,
  8201. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8202. envmap_vertex: envmap_vertex,
  8203. fog_vertex: fog_vertex,
  8204. fog_pars_vertex: fog_pars_vertex,
  8205. fog_fragment: fog_fragment,
  8206. fog_pars_fragment: fog_pars_fragment,
  8207. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8208. lightmap_fragment: lightmap_fragment,
  8209. lightmap_pars_fragment: lightmap_pars_fragment,
  8210. lights_lambert_fragment: lights_lambert_fragment,
  8211. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8212. lights_pars_begin: lights_pars_begin,
  8213. lights_toon_fragment: lights_toon_fragment,
  8214. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8215. lights_phong_fragment: lights_phong_fragment,
  8216. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8217. lights_physical_fragment: lights_physical_fragment,
  8218. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8219. lights_fragment_begin: lights_fragment_begin,
  8220. lights_fragment_maps: lights_fragment_maps,
  8221. lights_fragment_end: lights_fragment_end,
  8222. logdepthbuf_fragment: logdepthbuf_fragment,
  8223. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8224. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8225. logdepthbuf_vertex: logdepthbuf_vertex,
  8226. map_fragment: map_fragment,
  8227. map_pars_fragment: map_pars_fragment,
  8228. map_particle_fragment: map_particle_fragment,
  8229. map_particle_pars_fragment: map_particle_pars_fragment,
  8230. metalnessmap_fragment: metalnessmap_fragment,
  8231. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8232. morphcolor_vertex: morphcolor_vertex,
  8233. morphnormal_vertex: morphnormal_vertex,
  8234. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8235. morphtarget_vertex: morphtarget_vertex,
  8236. normal_fragment_begin: normal_fragment_begin,
  8237. normal_fragment_maps: normal_fragment_maps,
  8238. normal_pars_fragment: normal_pars_fragment,
  8239. normal_pars_vertex: normal_pars_vertex,
  8240. normal_vertex: normal_vertex,
  8241. normalmap_pars_fragment: normalmap_pars_fragment,
  8242. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8243. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8244. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8245. iridescence_pars_fragment: iridescence_pars_fragment,
  8246. output_fragment: output_fragment,
  8247. packing: packing,
  8248. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8249. project_vertex: project_vertex,
  8250. dithering_fragment: dithering_fragment,
  8251. dithering_pars_fragment: dithering_pars_fragment,
  8252. roughnessmap_fragment: roughnessmap_fragment,
  8253. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8254. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8255. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8256. shadowmap_vertex: shadowmap_vertex,
  8257. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8258. skinbase_vertex: skinbase_vertex,
  8259. skinning_pars_vertex: skinning_pars_vertex,
  8260. skinning_vertex: skinning_vertex,
  8261. skinnormal_vertex: skinnormal_vertex,
  8262. specularmap_fragment: specularmap_fragment,
  8263. specularmap_pars_fragment: specularmap_pars_fragment,
  8264. tonemapping_fragment: tonemapping_fragment,
  8265. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8266. transmission_fragment: transmission_fragment,
  8267. transmission_pars_fragment: transmission_pars_fragment,
  8268. uv_pars_fragment: uv_pars_fragment,
  8269. uv_pars_vertex: uv_pars_vertex,
  8270. uv_vertex: uv_vertex,
  8271. uv2_pars_fragment: uv2_pars_fragment,
  8272. uv2_pars_vertex: uv2_pars_vertex,
  8273. uv2_vertex: uv2_vertex,
  8274. worldpos_vertex: worldpos_vertex,
  8275. background_vert: vertex$h,
  8276. background_frag: fragment$h,
  8277. backgroundCube_vert: vertex$g,
  8278. backgroundCube_frag: fragment$g,
  8279. cube_vert: vertex$f,
  8280. cube_frag: fragment$f,
  8281. depth_vert: vertex$e,
  8282. depth_frag: fragment$e,
  8283. distanceRGBA_vert: vertex$d,
  8284. distanceRGBA_frag: fragment$d,
  8285. equirect_vert: vertex$c,
  8286. equirect_frag: fragment$c,
  8287. linedashed_vert: vertex$b,
  8288. linedashed_frag: fragment$b,
  8289. meshbasic_vert: vertex$a,
  8290. meshbasic_frag: fragment$a,
  8291. meshlambert_vert: vertex$9,
  8292. meshlambert_frag: fragment$9,
  8293. meshmatcap_vert: vertex$8,
  8294. meshmatcap_frag: fragment$8,
  8295. meshnormal_vert: vertex$7,
  8296. meshnormal_frag: fragment$7,
  8297. meshphong_vert: vertex$6,
  8298. meshphong_frag: fragment$6,
  8299. meshphysical_vert: vertex$5,
  8300. meshphysical_frag: fragment$5,
  8301. meshtoon_vert: vertex$4,
  8302. meshtoon_frag: fragment$4,
  8303. points_vert: vertex$3,
  8304. points_frag: fragment$3,
  8305. shadow_vert: vertex$2,
  8306. shadow_frag: fragment$2,
  8307. sprite_vert: vertex$1,
  8308. sprite_frag: fragment$1
  8309. };
  8310. /**
  8311. * Uniforms library for shared webgl shaders
  8312. */
  8313. const UniformsLib = {
  8314. common: {
  8315. diffuse: {
  8316. value: /*@__PURE__*/new Color(0xffffff)
  8317. },
  8318. opacity: {
  8319. value: 1.0
  8320. },
  8321. map: {
  8322. value: null
  8323. },
  8324. uvTransform: {
  8325. value: /*@__PURE__*/new Matrix3()
  8326. },
  8327. uv2Transform: {
  8328. value: /*@__PURE__*/new Matrix3()
  8329. },
  8330. alphaMap: {
  8331. value: null
  8332. },
  8333. alphaTest: {
  8334. value: 0
  8335. }
  8336. },
  8337. specularmap: {
  8338. specularMap: {
  8339. value: null
  8340. }
  8341. },
  8342. envmap: {
  8343. envMap: {
  8344. value: null
  8345. },
  8346. flipEnvMap: {
  8347. value: -1
  8348. },
  8349. reflectivity: {
  8350. value: 1.0
  8351. },
  8352. // basic, lambert, phong
  8353. ior: {
  8354. value: 1.5
  8355. },
  8356. // physical
  8357. refractionRatio: {
  8358. value: 0.98
  8359. } // basic, lambert, phong
  8360. },
  8361. aomap: {
  8362. aoMap: {
  8363. value: null
  8364. },
  8365. aoMapIntensity: {
  8366. value: 1
  8367. }
  8368. },
  8369. lightmap: {
  8370. lightMap: {
  8371. value: null
  8372. },
  8373. lightMapIntensity: {
  8374. value: 1
  8375. }
  8376. },
  8377. emissivemap: {
  8378. emissiveMap: {
  8379. value: null
  8380. }
  8381. },
  8382. bumpmap: {
  8383. bumpMap: {
  8384. value: null
  8385. },
  8386. bumpScale: {
  8387. value: 1
  8388. }
  8389. },
  8390. normalmap: {
  8391. normalMap: {
  8392. value: null
  8393. },
  8394. normalScale: {
  8395. value: /*@__PURE__*/new Vector2(1, 1)
  8396. }
  8397. },
  8398. displacementmap: {
  8399. displacementMap: {
  8400. value: null
  8401. },
  8402. displacementScale: {
  8403. value: 1
  8404. },
  8405. displacementBias: {
  8406. value: 0
  8407. }
  8408. },
  8409. roughnessmap: {
  8410. roughnessMap: {
  8411. value: null
  8412. }
  8413. },
  8414. metalnessmap: {
  8415. metalnessMap: {
  8416. value: null
  8417. }
  8418. },
  8419. gradientmap: {
  8420. gradientMap: {
  8421. value: null
  8422. }
  8423. },
  8424. fog: {
  8425. fogDensity: {
  8426. value: 0.00025
  8427. },
  8428. fogNear: {
  8429. value: 1
  8430. },
  8431. fogFar: {
  8432. value: 2000
  8433. },
  8434. fogColor: {
  8435. value: /*@__PURE__*/new Color(0xffffff)
  8436. }
  8437. },
  8438. lights: {
  8439. ambientLightColor: {
  8440. value: []
  8441. },
  8442. lightProbe: {
  8443. value: []
  8444. },
  8445. directionalLights: {
  8446. value: [],
  8447. properties: {
  8448. direction: {},
  8449. color: {}
  8450. }
  8451. },
  8452. directionalLightShadows: {
  8453. value: [],
  8454. properties: {
  8455. shadowBias: {},
  8456. shadowNormalBias: {},
  8457. shadowRadius: {},
  8458. shadowMapSize: {}
  8459. }
  8460. },
  8461. directionalShadowMap: {
  8462. value: []
  8463. },
  8464. directionalShadowMatrix: {
  8465. value: []
  8466. },
  8467. spotLights: {
  8468. value: [],
  8469. properties: {
  8470. color: {},
  8471. position: {},
  8472. direction: {},
  8473. distance: {},
  8474. coneCos: {},
  8475. penumbraCos: {},
  8476. decay: {}
  8477. }
  8478. },
  8479. spotLightShadows: {
  8480. value: [],
  8481. properties: {
  8482. shadowBias: {},
  8483. shadowNormalBias: {},
  8484. shadowRadius: {},
  8485. shadowMapSize: {}
  8486. }
  8487. },
  8488. spotLightMap: {
  8489. value: []
  8490. },
  8491. spotShadowMap: {
  8492. value: []
  8493. },
  8494. spotLightMatrix: {
  8495. value: []
  8496. },
  8497. pointLights: {
  8498. value: [],
  8499. properties: {
  8500. color: {},
  8501. position: {},
  8502. decay: {},
  8503. distance: {}
  8504. }
  8505. },
  8506. pointLightShadows: {
  8507. value: [],
  8508. properties: {
  8509. shadowBias: {},
  8510. shadowNormalBias: {},
  8511. shadowRadius: {},
  8512. shadowMapSize: {},
  8513. shadowCameraNear: {},
  8514. shadowCameraFar: {}
  8515. }
  8516. },
  8517. pointShadowMap: {
  8518. value: []
  8519. },
  8520. pointShadowMatrix: {
  8521. value: []
  8522. },
  8523. hemisphereLights: {
  8524. value: [],
  8525. properties: {
  8526. direction: {},
  8527. skyColor: {},
  8528. groundColor: {}
  8529. }
  8530. },
  8531. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8532. rectAreaLights: {
  8533. value: [],
  8534. properties: {
  8535. color: {},
  8536. position: {},
  8537. width: {},
  8538. height: {}
  8539. }
  8540. },
  8541. ltc_1: {
  8542. value: null
  8543. },
  8544. ltc_2: {
  8545. value: null
  8546. }
  8547. },
  8548. points: {
  8549. diffuse: {
  8550. value: /*@__PURE__*/new Color(0xffffff)
  8551. },
  8552. opacity: {
  8553. value: 1.0
  8554. },
  8555. size: {
  8556. value: 1.0
  8557. },
  8558. scale: {
  8559. value: 1.0
  8560. },
  8561. map: {
  8562. value: null
  8563. },
  8564. alphaMap: {
  8565. value: null
  8566. },
  8567. alphaTest: {
  8568. value: 0
  8569. },
  8570. uvTransform: {
  8571. value: /*@__PURE__*/new Matrix3()
  8572. }
  8573. },
  8574. sprite: {
  8575. diffuse: {
  8576. value: /*@__PURE__*/new Color(0xffffff)
  8577. },
  8578. opacity: {
  8579. value: 1.0
  8580. },
  8581. center: {
  8582. value: /*@__PURE__*/new Vector2(0.5, 0.5)
  8583. },
  8584. rotation: {
  8585. value: 0.0
  8586. },
  8587. map: {
  8588. value: null
  8589. },
  8590. alphaMap: {
  8591. value: null
  8592. },
  8593. alphaTest: {
  8594. value: 0
  8595. },
  8596. uvTransform: {
  8597. value: /*@__PURE__*/new Matrix3()
  8598. }
  8599. }
  8600. };
  8601. const ShaderLib = {
  8602. basic: {
  8603. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8604. vertexShader: ShaderChunk.meshbasic_vert,
  8605. fragmentShader: ShaderChunk.meshbasic_frag
  8606. },
  8607. lambert: {
  8608. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8609. emissive: {
  8610. value: /*@__PURE__*/new Color(0x000000)
  8611. }
  8612. }]),
  8613. vertexShader: ShaderChunk.meshlambert_vert,
  8614. fragmentShader: ShaderChunk.meshlambert_frag
  8615. },
  8616. phong: {
  8617. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8618. emissive: {
  8619. value: /*@__PURE__*/new Color(0x000000)
  8620. },
  8621. specular: {
  8622. value: /*@__PURE__*/new Color(0x111111)
  8623. },
  8624. shininess: {
  8625. value: 30
  8626. }
  8627. }]),
  8628. vertexShader: ShaderChunk.meshphong_vert,
  8629. fragmentShader: ShaderChunk.meshphong_frag
  8630. },
  8631. standard: {
  8632. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  8633. emissive: {
  8634. value: /*@__PURE__*/new Color(0x000000)
  8635. },
  8636. roughness: {
  8637. value: 1.0
  8638. },
  8639. metalness: {
  8640. value: 0.0
  8641. },
  8642. envMapIntensity: {
  8643. value: 1
  8644. } // temporary
  8645. }]),
  8646. vertexShader: ShaderChunk.meshphysical_vert,
  8647. fragmentShader: ShaderChunk.meshphysical_frag
  8648. },
  8649. toon: {
  8650. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8651. emissive: {
  8652. value: /*@__PURE__*/new Color(0x000000)
  8653. }
  8654. }]),
  8655. vertexShader: ShaderChunk.meshtoon_vert,
  8656. fragmentShader: ShaderChunk.meshtoon_frag
  8657. },
  8658. matcap: {
  8659. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8660. matcap: {
  8661. value: null
  8662. }
  8663. }]),
  8664. vertexShader: ShaderChunk.meshmatcap_vert,
  8665. fragmentShader: ShaderChunk.meshmatcap_frag
  8666. },
  8667. points: {
  8668. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8669. vertexShader: ShaderChunk.points_vert,
  8670. fragmentShader: ShaderChunk.points_frag
  8671. },
  8672. dashed: {
  8673. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8674. scale: {
  8675. value: 1
  8676. },
  8677. dashSize: {
  8678. value: 1
  8679. },
  8680. totalSize: {
  8681. value: 2
  8682. }
  8683. }]),
  8684. vertexShader: ShaderChunk.linedashed_vert,
  8685. fragmentShader: ShaderChunk.linedashed_frag
  8686. },
  8687. depth: {
  8688. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8689. vertexShader: ShaderChunk.depth_vert,
  8690. fragmentShader: ShaderChunk.depth_frag
  8691. },
  8692. normal: {
  8693. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8694. opacity: {
  8695. value: 1.0
  8696. }
  8697. }]),
  8698. vertexShader: ShaderChunk.meshnormal_vert,
  8699. fragmentShader: ShaderChunk.meshnormal_frag
  8700. },
  8701. sprite: {
  8702. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8703. vertexShader: ShaderChunk.sprite_vert,
  8704. fragmentShader: ShaderChunk.sprite_frag
  8705. },
  8706. background: {
  8707. uniforms: {
  8708. uvTransform: {
  8709. value: /*@__PURE__*/new Matrix3()
  8710. },
  8711. t2D: {
  8712. value: null
  8713. },
  8714. backgroundIntensity: {
  8715. value: 1
  8716. }
  8717. },
  8718. vertexShader: ShaderChunk.background_vert,
  8719. fragmentShader: ShaderChunk.background_frag
  8720. },
  8721. backgroundCube: {
  8722. uniforms: {
  8723. envMap: {
  8724. value: null
  8725. },
  8726. flipEnvMap: {
  8727. value: -1
  8728. },
  8729. backgroundBlurriness: {
  8730. value: 0
  8731. },
  8732. backgroundIntensity: {
  8733. value: 1
  8734. }
  8735. },
  8736. vertexShader: ShaderChunk.backgroundCube_vert,
  8737. fragmentShader: ShaderChunk.backgroundCube_frag
  8738. },
  8739. cube: {
  8740. uniforms: {
  8741. tCube: {
  8742. value: null
  8743. },
  8744. tFlip: {
  8745. value: -1
  8746. },
  8747. opacity: {
  8748. value: 1.0
  8749. }
  8750. },
  8751. vertexShader: ShaderChunk.cube_vert,
  8752. fragmentShader: ShaderChunk.cube_frag
  8753. },
  8754. equirect: {
  8755. uniforms: {
  8756. tEquirect: {
  8757. value: null
  8758. }
  8759. },
  8760. vertexShader: ShaderChunk.equirect_vert,
  8761. fragmentShader: ShaderChunk.equirect_frag
  8762. },
  8763. distanceRGBA: {
  8764. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8765. referencePosition: {
  8766. value: /*@__PURE__*/new Vector3()
  8767. },
  8768. nearDistance: {
  8769. value: 1
  8770. },
  8771. farDistance: {
  8772. value: 1000
  8773. }
  8774. }]),
  8775. vertexShader: ShaderChunk.distanceRGBA_vert,
  8776. fragmentShader: ShaderChunk.distanceRGBA_frag
  8777. },
  8778. shadow: {
  8779. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8780. color: {
  8781. value: /*@__PURE__*/new Color(0x00000)
  8782. },
  8783. opacity: {
  8784. value: 1.0
  8785. }
  8786. }]),
  8787. vertexShader: ShaderChunk.shadow_vert,
  8788. fragmentShader: ShaderChunk.shadow_frag
  8789. }
  8790. };
  8791. ShaderLib.physical = {
  8792. uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, {
  8793. clearcoat: {
  8794. value: 0
  8795. },
  8796. clearcoatMap: {
  8797. value: null
  8798. },
  8799. clearcoatRoughness: {
  8800. value: 0
  8801. },
  8802. clearcoatRoughnessMap: {
  8803. value: null
  8804. },
  8805. clearcoatNormalScale: {
  8806. value: /*@__PURE__*/new Vector2(1, 1)
  8807. },
  8808. clearcoatNormalMap: {
  8809. value: null
  8810. },
  8811. iridescence: {
  8812. value: 0
  8813. },
  8814. iridescenceMap: {
  8815. value: null
  8816. },
  8817. iridescenceIOR: {
  8818. value: 1.3
  8819. },
  8820. iridescenceThicknessMinimum: {
  8821. value: 100
  8822. },
  8823. iridescenceThicknessMaximum: {
  8824. value: 400
  8825. },
  8826. iridescenceThicknessMap: {
  8827. value: null
  8828. },
  8829. sheen: {
  8830. value: 0
  8831. },
  8832. sheenColor: {
  8833. value: /*@__PURE__*/new Color(0x000000)
  8834. },
  8835. sheenColorMap: {
  8836. value: null
  8837. },
  8838. sheenRoughness: {
  8839. value: 1
  8840. },
  8841. sheenRoughnessMap: {
  8842. value: null
  8843. },
  8844. transmission: {
  8845. value: 0
  8846. },
  8847. transmissionMap: {
  8848. value: null
  8849. },
  8850. transmissionSamplerSize: {
  8851. value: /*@__PURE__*/new Vector2()
  8852. },
  8853. transmissionSamplerMap: {
  8854. value: null
  8855. },
  8856. thickness: {
  8857. value: 0
  8858. },
  8859. thicknessMap: {
  8860. value: null
  8861. },
  8862. attenuationDistance: {
  8863. value: 0
  8864. },
  8865. attenuationColor: {
  8866. value: /*@__PURE__*/new Color(0x000000)
  8867. },
  8868. specularIntensity: {
  8869. value: 1
  8870. },
  8871. specularIntensityMap: {
  8872. value: null
  8873. },
  8874. specularColor: {
  8875. value: /*@__PURE__*/new Color(1, 1, 1)
  8876. },
  8877. specularColorMap: {
  8878. value: null
  8879. }
  8880. }]),
  8881. vertexShader: ShaderChunk.meshphysical_vert,
  8882. fragmentShader: ShaderChunk.meshphysical_frag
  8883. };
  8884. const _rgb = {
  8885. r: 0,
  8886. b: 0,
  8887. g: 0
  8888. };
  8889. function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) {
  8890. const clearColor = new Color(0x000000);
  8891. let clearAlpha = alpha === true ? 0 : 1;
  8892. let planeMesh;
  8893. let boxMesh;
  8894. let currentBackground = null;
  8895. let currentBackgroundVersion = 0;
  8896. let currentTonemapping = null;
  8897. function render(renderList, scene) {
  8898. let forceClear = false;
  8899. let background = scene.isScene === true ? scene.background : null;
  8900. if (background && background.isTexture) {
  8901. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8902. background = (usePMREM ? cubeuvmaps : cubemaps).get(background);
  8903. }
  8904. // Ignore background in AR
  8905. // TODO: Reconsider this.
  8906. const xr = renderer.xr;
  8907. const session = xr.getSession && xr.getSession();
  8908. if (session && session.environmentBlendMode === 'additive') {
  8909. background = null;
  8910. }
  8911. if (background === null) {
  8912. setClear(clearColor, clearAlpha);
  8913. } else if (background && background.isColor) {
  8914. setClear(background, 1);
  8915. forceClear = true;
  8916. }
  8917. if (renderer.autoClear || forceClear) {
  8918. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8919. }
  8920. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8921. if (boxMesh === undefined) {
  8922. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8923. name: 'BackgroundCubeMaterial',
  8924. uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms),
  8925. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8926. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8927. side: BackSide,
  8928. depthTest: false,
  8929. depthWrite: false,
  8930. fog: false
  8931. }));
  8932. boxMesh.geometry.deleteAttribute('normal');
  8933. boxMesh.geometry.deleteAttribute('uv');
  8934. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8935. this.matrixWorld.copyPosition(camera.matrixWorld);
  8936. };
  8937. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8938. Object.defineProperty(boxMesh.material, 'envMap', {
  8939. get: function () {
  8940. return this.uniforms.envMap.value;
  8941. }
  8942. });
  8943. objects.update(boxMesh);
  8944. }
  8945. boxMesh.material.uniforms.envMap.value = background;
  8946. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8947. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8948. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8949. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8950. boxMesh.material.needsUpdate = true;
  8951. currentBackground = background;
  8952. currentBackgroundVersion = background.version;
  8953. currentTonemapping = renderer.toneMapping;
  8954. }
  8955. boxMesh.layers.enableAll();
  8956. // push to the pre-sorted opaque render list
  8957. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8958. } else if (background && background.isTexture) {
  8959. if (planeMesh === undefined) {
  8960. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8961. name: 'BackgroundMaterial',
  8962. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8963. vertexShader: ShaderLib.background.vertexShader,
  8964. fragmentShader: ShaderLib.background.fragmentShader,
  8965. side: FrontSide,
  8966. depthTest: false,
  8967. depthWrite: false,
  8968. fog: false
  8969. }));
  8970. planeMesh.geometry.deleteAttribute('normal');
  8971. // add "map" material property so the renderer can evaluate it like for built-in materials
  8972. Object.defineProperty(planeMesh.material, 'map', {
  8973. get: function () {
  8974. return this.uniforms.t2D.value;
  8975. }
  8976. });
  8977. objects.update(planeMesh);
  8978. }
  8979. planeMesh.material.uniforms.t2D.value = background;
  8980. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8981. if (background.matrixAutoUpdate === true) {
  8982. background.updateMatrix();
  8983. }
  8984. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8985. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8986. planeMesh.material.needsUpdate = true;
  8987. currentBackground = background;
  8988. currentBackgroundVersion = background.version;
  8989. currentTonemapping = renderer.toneMapping;
  8990. }
  8991. planeMesh.layers.enableAll();
  8992. // push to the pre-sorted opaque render list
  8993. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8994. }
  8995. }
  8996. function setClear(color, alpha) {
  8997. color.getRGB(_rgb, getUnlitUniformColorSpace(renderer));
  8998. state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha);
  8999. }
  9000. return {
  9001. getClearColor: function () {
  9002. return clearColor;
  9003. },
  9004. setClearColor: function (color, alpha = 1) {
  9005. clearColor.set(color);
  9006. clearAlpha = alpha;
  9007. setClear(clearColor, clearAlpha);
  9008. },
  9009. getClearAlpha: function () {
  9010. return clearAlpha;
  9011. },
  9012. setClearAlpha: function (alpha) {
  9013. clearAlpha = alpha;
  9014. setClear(clearColor, clearAlpha);
  9015. },
  9016. render: render
  9017. };
  9018. }
  9019. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  9020. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9021. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  9022. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9023. const bindingStates = {};
  9024. const defaultState = createBindingState(null);
  9025. let currentState = defaultState;
  9026. let forceUpdate = false;
  9027. function setup(object, material, program, geometry, index) {
  9028. let updateBuffers = false;
  9029. if (vaoAvailable) {
  9030. const state = getBindingState(geometry, program, material);
  9031. if (currentState !== state) {
  9032. currentState = state;
  9033. bindVertexArrayObject(currentState.object);
  9034. }
  9035. updateBuffers = needsUpdate(object, geometry, program, index);
  9036. if (updateBuffers) saveCache(object, geometry, program, index);
  9037. } else {
  9038. const wireframe = material.wireframe === true;
  9039. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  9040. currentState.geometry = geometry.id;
  9041. currentState.program = program.id;
  9042. currentState.wireframe = wireframe;
  9043. updateBuffers = true;
  9044. }
  9045. }
  9046. if (index !== null) {
  9047. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  9048. }
  9049. if (updateBuffers || forceUpdate) {
  9050. forceUpdate = false;
  9051. setupVertexAttributes(object, material, program, geometry);
  9052. if (index !== null) {
  9053. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  9054. }
  9055. }
  9056. }
  9057. function createVertexArrayObject() {
  9058. if (capabilities.isWebGL2) return gl.createVertexArray();
  9059. return extension.createVertexArrayOES();
  9060. }
  9061. function bindVertexArrayObject(vao) {
  9062. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  9063. return extension.bindVertexArrayOES(vao);
  9064. }
  9065. function deleteVertexArrayObject(vao) {
  9066. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  9067. return extension.deleteVertexArrayOES(vao);
  9068. }
  9069. function getBindingState(geometry, program, material) {
  9070. const wireframe = material.wireframe === true;
  9071. let programMap = bindingStates[geometry.id];
  9072. if (programMap === undefined) {
  9073. programMap = {};
  9074. bindingStates[geometry.id] = programMap;
  9075. }
  9076. let stateMap = programMap[program.id];
  9077. if (stateMap === undefined) {
  9078. stateMap = {};
  9079. programMap[program.id] = stateMap;
  9080. }
  9081. let state = stateMap[wireframe];
  9082. if (state === undefined) {
  9083. state = createBindingState(createVertexArrayObject());
  9084. stateMap[wireframe] = state;
  9085. }
  9086. return state;
  9087. }
  9088. function createBindingState(vao) {
  9089. const newAttributes = [];
  9090. const enabledAttributes = [];
  9091. const attributeDivisors = [];
  9092. for (let i = 0; i < maxVertexAttributes; i++) {
  9093. newAttributes[i] = 0;
  9094. enabledAttributes[i] = 0;
  9095. attributeDivisors[i] = 0;
  9096. }
  9097. return {
  9098. // for backward compatibility on non-VAO support browser
  9099. geometry: null,
  9100. program: null,
  9101. wireframe: false,
  9102. newAttributes: newAttributes,
  9103. enabledAttributes: enabledAttributes,
  9104. attributeDivisors: attributeDivisors,
  9105. object: vao,
  9106. attributes: {},
  9107. index: null
  9108. };
  9109. }
  9110. function needsUpdate(object, geometry, program, index) {
  9111. const cachedAttributes = currentState.attributes;
  9112. const geometryAttributes = geometry.attributes;
  9113. let attributesNum = 0;
  9114. const programAttributes = program.getAttributes();
  9115. for (const name in programAttributes) {
  9116. const programAttribute = programAttributes[name];
  9117. if (programAttribute.location >= 0) {
  9118. const cachedAttribute = cachedAttributes[name];
  9119. let geometryAttribute = geometryAttributes[name];
  9120. if (geometryAttribute === undefined) {
  9121. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9122. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9123. }
  9124. if (cachedAttribute === undefined) return true;
  9125. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9126. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  9127. attributesNum++;
  9128. }
  9129. }
  9130. if (currentState.attributesNum !== attributesNum) return true;
  9131. if (currentState.index !== index) return true;
  9132. return false;
  9133. }
  9134. function saveCache(object, geometry, program, index) {
  9135. const cache = {};
  9136. const attributes = geometry.attributes;
  9137. let attributesNum = 0;
  9138. const programAttributes = program.getAttributes();
  9139. for (const name in programAttributes) {
  9140. const programAttribute = programAttributes[name];
  9141. if (programAttribute.location >= 0) {
  9142. let attribute = attributes[name];
  9143. if (attribute === undefined) {
  9144. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  9145. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  9146. }
  9147. const data = {};
  9148. data.attribute = attribute;
  9149. if (attribute && attribute.data) {
  9150. data.data = attribute.data;
  9151. }
  9152. cache[name] = data;
  9153. attributesNum++;
  9154. }
  9155. }
  9156. currentState.attributes = cache;
  9157. currentState.attributesNum = attributesNum;
  9158. currentState.index = index;
  9159. }
  9160. function initAttributes() {
  9161. const newAttributes = currentState.newAttributes;
  9162. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9163. newAttributes[i] = 0;
  9164. }
  9165. }
  9166. function enableAttribute(attribute) {
  9167. enableAttributeAndDivisor(attribute, 0);
  9168. }
  9169. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9170. const newAttributes = currentState.newAttributes;
  9171. const enabledAttributes = currentState.enabledAttributes;
  9172. const attributeDivisors = currentState.attributeDivisors;
  9173. newAttributes[attribute] = 1;
  9174. if (enabledAttributes[attribute] === 0) {
  9175. gl.enableVertexAttribArray(attribute);
  9176. enabledAttributes[attribute] = 1;
  9177. }
  9178. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9179. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9180. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9181. attributeDivisors[attribute] = meshPerAttribute;
  9182. }
  9183. }
  9184. function disableUnusedAttributes() {
  9185. const newAttributes = currentState.newAttributes;
  9186. const enabledAttributes = currentState.enabledAttributes;
  9187. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9188. if (enabledAttributes[i] !== newAttributes[i]) {
  9189. gl.disableVertexAttribArray(i);
  9190. enabledAttributes[i] = 0;
  9191. }
  9192. }
  9193. }
  9194. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9195. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9196. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9197. } else {
  9198. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9199. }
  9200. }
  9201. function setupVertexAttributes(object, material, program, geometry) {
  9202. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9203. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9204. }
  9205. initAttributes();
  9206. const geometryAttributes = geometry.attributes;
  9207. const programAttributes = program.getAttributes();
  9208. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9209. for (const name in programAttributes) {
  9210. const programAttribute = programAttributes[name];
  9211. if (programAttribute.location >= 0) {
  9212. let geometryAttribute = geometryAttributes[name];
  9213. if (geometryAttribute === undefined) {
  9214. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9215. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9216. }
  9217. if (geometryAttribute !== undefined) {
  9218. const normalized = geometryAttribute.normalized;
  9219. const size = geometryAttribute.itemSize;
  9220. const attribute = attributes.get(geometryAttribute);
  9221. // TODO Attribute may not be available on context restore
  9222. if (attribute === undefined) continue;
  9223. const buffer = attribute.buffer;
  9224. const type = attribute.type;
  9225. const bytesPerElement = attribute.bytesPerElement;
  9226. if (geometryAttribute.isInterleavedBufferAttribute) {
  9227. const data = geometryAttribute.data;
  9228. const stride = data.stride;
  9229. const offset = geometryAttribute.offset;
  9230. if (data.isInstancedInterleavedBuffer) {
  9231. for (let i = 0; i < programAttribute.locationSize; i++) {
  9232. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9233. }
  9234. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9235. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9236. }
  9237. } else {
  9238. for (let i = 0; i < programAttribute.locationSize; i++) {
  9239. enableAttribute(programAttribute.location + i);
  9240. }
  9241. }
  9242. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9243. for (let i = 0; i < programAttribute.locationSize; i++) {
  9244. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9245. }
  9246. } else {
  9247. if (geometryAttribute.isInstancedBufferAttribute) {
  9248. for (let i = 0; i < programAttribute.locationSize; i++) {
  9249. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9250. }
  9251. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9252. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9253. }
  9254. } else {
  9255. for (let i = 0; i < programAttribute.locationSize; i++) {
  9256. enableAttribute(programAttribute.location + i);
  9257. }
  9258. }
  9259. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9260. for (let i = 0; i < programAttribute.locationSize; i++) {
  9261. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9262. }
  9263. }
  9264. } else if (materialDefaultAttributeValues !== undefined) {
  9265. const value = materialDefaultAttributeValues[name];
  9266. if (value !== undefined) {
  9267. switch (value.length) {
  9268. case 2:
  9269. gl.vertexAttrib2fv(programAttribute.location, value);
  9270. break;
  9271. case 3:
  9272. gl.vertexAttrib3fv(programAttribute.location, value);
  9273. break;
  9274. case 4:
  9275. gl.vertexAttrib4fv(programAttribute.location, value);
  9276. break;
  9277. default:
  9278. gl.vertexAttrib1fv(programAttribute.location, value);
  9279. }
  9280. }
  9281. }
  9282. }
  9283. }
  9284. disableUnusedAttributes();
  9285. }
  9286. function dispose() {
  9287. reset();
  9288. for (const geometryId in bindingStates) {
  9289. const programMap = bindingStates[geometryId];
  9290. for (const programId in programMap) {
  9291. const stateMap = programMap[programId];
  9292. for (const wireframe in stateMap) {
  9293. deleteVertexArrayObject(stateMap[wireframe].object);
  9294. delete stateMap[wireframe];
  9295. }
  9296. delete programMap[programId];
  9297. }
  9298. delete bindingStates[geometryId];
  9299. }
  9300. }
  9301. function releaseStatesOfGeometry(geometry) {
  9302. if (bindingStates[geometry.id] === undefined) return;
  9303. const programMap = bindingStates[geometry.id];
  9304. for (const programId in programMap) {
  9305. const stateMap = programMap[programId];
  9306. for (const wireframe in stateMap) {
  9307. deleteVertexArrayObject(stateMap[wireframe].object);
  9308. delete stateMap[wireframe];
  9309. }
  9310. delete programMap[programId];
  9311. }
  9312. delete bindingStates[geometry.id];
  9313. }
  9314. function releaseStatesOfProgram(program) {
  9315. for (const geometryId in bindingStates) {
  9316. const programMap = bindingStates[geometryId];
  9317. if (programMap[program.id] === undefined) continue;
  9318. const stateMap = programMap[program.id];
  9319. for (const wireframe in stateMap) {
  9320. deleteVertexArrayObject(stateMap[wireframe].object);
  9321. delete stateMap[wireframe];
  9322. }
  9323. delete programMap[program.id];
  9324. }
  9325. }
  9326. function reset() {
  9327. resetDefaultState();
  9328. forceUpdate = true;
  9329. if (currentState === defaultState) return;
  9330. currentState = defaultState;
  9331. bindVertexArrayObject(currentState.object);
  9332. }
  9333. // for backward-compatibility
  9334. function resetDefaultState() {
  9335. defaultState.geometry = null;
  9336. defaultState.program = null;
  9337. defaultState.wireframe = false;
  9338. }
  9339. return {
  9340. setup: setup,
  9341. reset: reset,
  9342. resetDefaultState: resetDefaultState,
  9343. dispose: dispose,
  9344. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9345. releaseStatesOfProgram: releaseStatesOfProgram,
  9346. initAttributes: initAttributes,
  9347. enableAttribute: enableAttribute,
  9348. disableUnusedAttributes: disableUnusedAttributes
  9349. };
  9350. }
  9351. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9352. const isWebGL2 = capabilities.isWebGL2;
  9353. let mode;
  9354. function setMode(value) {
  9355. mode = value;
  9356. }
  9357. function render(start, count) {
  9358. gl.drawArrays(mode, start, count);
  9359. info.update(count, mode, 1);
  9360. }
  9361. function renderInstances(start, count, primcount) {
  9362. if (primcount === 0) return;
  9363. let extension, methodName;
  9364. if (isWebGL2) {
  9365. extension = gl;
  9366. methodName = 'drawArraysInstanced';
  9367. } else {
  9368. extension = extensions.get('ANGLE_instanced_arrays');
  9369. methodName = 'drawArraysInstancedANGLE';
  9370. if (extension === null) {
  9371. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9372. return;
  9373. }
  9374. }
  9375. extension[methodName](mode, start, count, primcount);
  9376. info.update(count, mode, primcount);
  9377. }
  9378. //
  9379. this.setMode = setMode;
  9380. this.render = render;
  9381. this.renderInstances = renderInstances;
  9382. }
  9383. function WebGLCapabilities(gl, extensions, parameters) {
  9384. let maxAnisotropy;
  9385. function getMaxAnisotropy() {
  9386. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9387. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9388. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9389. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9390. } else {
  9391. maxAnisotropy = 0;
  9392. }
  9393. return maxAnisotropy;
  9394. }
  9395. function getMaxPrecision(precision) {
  9396. if (precision === 'highp') {
  9397. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9398. return 'highp';
  9399. }
  9400. precision = 'mediump';
  9401. }
  9402. if (precision === 'mediump') {
  9403. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9404. return 'mediump';
  9405. }
  9406. }
  9407. return 'lowp';
  9408. }
  9409. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9410. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9411. const maxPrecision = getMaxPrecision(precision);
  9412. if (maxPrecision !== precision) {
  9413. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9414. precision = maxPrecision;
  9415. }
  9416. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9417. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9418. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9419. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9420. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9421. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9422. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9423. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9424. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9425. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9426. const vertexTextures = maxVertexTextures > 0;
  9427. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9428. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9429. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9430. return {
  9431. isWebGL2: isWebGL2,
  9432. drawBuffers: drawBuffers,
  9433. getMaxAnisotropy: getMaxAnisotropy,
  9434. getMaxPrecision: getMaxPrecision,
  9435. precision: precision,
  9436. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9437. maxTextures: maxTextures,
  9438. maxVertexTextures: maxVertexTextures,
  9439. maxTextureSize: maxTextureSize,
  9440. maxCubemapSize: maxCubemapSize,
  9441. maxAttributes: maxAttributes,
  9442. maxVertexUniforms: maxVertexUniforms,
  9443. maxVaryings: maxVaryings,
  9444. maxFragmentUniforms: maxFragmentUniforms,
  9445. vertexTextures: vertexTextures,
  9446. floatFragmentTextures: floatFragmentTextures,
  9447. floatVertexTextures: floatVertexTextures,
  9448. maxSamples: maxSamples
  9449. };
  9450. }
  9451. function WebGLClipping(properties) {
  9452. const scope = this;
  9453. let globalState = null,
  9454. numGlobalPlanes = 0,
  9455. localClippingEnabled = false,
  9456. renderingShadows = false;
  9457. const plane = new Plane(),
  9458. viewNormalMatrix = new Matrix3(),
  9459. uniform = {
  9460. value: null,
  9461. needsUpdate: false
  9462. };
  9463. this.uniform = uniform;
  9464. this.numPlanes = 0;
  9465. this.numIntersection = 0;
  9466. this.init = function (planes, enableLocalClipping, camera) {
  9467. const enabled = planes.length !== 0 || enableLocalClipping ||
  9468. // enable state of previous frame - the clipping code has to
  9469. // run another frame in order to reset the state:
  9470. numGlobalPlanes !== 0 || localClippingEnabled;
  9471. localClippingEnabled = enableLocalClipping;
  9472. globalState = projectPlanes(planes, camera, 0);
  9473. numGlobalPlanes = planes.length;
  9474. return enabled;
  9475. };
  9476. this.beginShadows = function () {
  9477. renderingShadows = true;
  9478. projectPlanes(null);
  9479. };
  9480. this.endShadows = function () {
  9481. renderingShadows = false;
  9482. resetGlobalState();
  9483. };
  9484. this.setState = function (material, camera, useCache) {
  9485. const planes = material.clippingPlanes,
  9486. clipIntersection = material.clipIntersection,
  9487. clipShadows = material.clipShadows;
  9488. const materialProperties = properties.get(material);
  9489. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9490. // there's no local clipping
  9491. if (renderingShadows) {
  9492. // there's no global clipping
  9493. projectPlanes(null);
  9494. } else {
  9495. resetGlobalState();
  9496. }
  9497. } else {
  9498. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9499. lGlobal = nGlobal * 4;
  9500. let dstArray = materialProperties.clippingState || null;
  9501. uniform.value = dstArray; // ensure unique state
  9502. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9503. for (let i = 0; i !== lGlobal; ++i) {
  9504. dstArray[i] = globalState[i];
  9505. }
  9506. materialProperties.clippingState = dstArray;
  9507. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9508. this.numPlanes += nGlobal;
  9509. }
  9510. };
  9511. function resetGlobalState() {
  9512. if (uniform.value !== globalState) {
  9513. uniform.value = globalState;
  9514. uniform.needsUpdate = numGlobalPlanes > 0;
  9515. }
  9516. scope.numPlanes = numGlobalPlanes;
  9517. scope.numIntersection = 0;
  9518. }
  9519. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9520. const nPlanes = planes !== null ? planes.length : 0;
  9521. let dstArray = null;
  9522. if (nPlanes !== 0) {
  9523. dstArray = uniform.value;
  9524. if (skipTransform !== true || dstArray === null) {
  9525. const flatSize = dstOffset + nPlanes * 4,
  9526. viewMatrix = camera.matrixWorldInverse;
  9527. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9528. if (dstArray === null || dstArray.length < flatSize) {
  9529. dstArray = new Float32Array(flatSize);
  9530. }
  9531. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9532. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9533. plane.normal.toArray(dstArray, i4);
  9534. dstArray[i4 + 3] = plane.constant;
  9535. }
  9536. }
  9537. uniform.value = dstArray;
  9538. uniform.needsUpdate = true;
  9539. }
  9540. scope.numPlanes = nPlanes;
  9541. scope.numIntersection = 0;
  9542. return dstArray;
  9543. }
  9544. }
  9545. function WebGLCubeMaps(renderer) {
  9546. let cubemaps = new WeakMap();
  9547. function mapTextureMapping(texture, mapping) {
  9548. if (mapping === EquirectangularReflectionMapping) {
  9549. texture.mapping = CubeReflectionMapping;
  9550. } else if (mapping === EquirectangularRefractionMapping) {
  9551. texture.mapping = CubeRefractionMapping;
  9552. }
  9553. return texture;
  9554. }
  9555. function get(texture) {
  9556. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9557. const mapping = texture.mapping;
  9558. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9559. if (cubemaps.has(texture)) {
  9560. const cubemap = cubemaps.get(texture).texture;
  9561. return mapTextureMapping(cubemap, texture.mapping);
  9562. } else {
  9563. const image = texture.image;
  9564. if (image && image.height > 0) {
  9565. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9566. renderTarget.fromEquirectangularTexture(renderer, texture);
  9567. cubemaps.set(texture, renderTarget);
  9568. texture.addEventListener('dispose', onTextureDispose);
  9569. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9570. } else {
  9571. // image not yet ready. try the conversion next frame
  9572. return null;
  9573. }
  9574. }
  9575. }
  9576. }
  9577. return texture;
  9578. }
  9579. function onTextureDispose(event) {
  9580. const texture = event.target;
  9581. texture.removeEventListener('dispose', onTextureDispose);
  9582. const cubemap = cubemaps.get(texture);
  9583. if (cubemap !== undefined) {
  9584. cubemaps.delete(texture);
  9585. cubemap.dispose();
  9586. }
  9587. }
  9588. function dispose() {
  9589. cubemaps = new WeakMap();
  9590. }
  9591. return {
  9592. get: get,
  9593. dispose: dispose
  9594. };
  9595. }
  9596. class OrthographicCamera extends Camera {
  9597. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9598. super();
  9599. this.isOrthographicCamera = true;
  9600. this.type = 'OrthographicCamera';
  9601. this.zoom = 1;
  9602. this.view = null;
  9603. this.left = left;
  9604. this.right = right;
  9605. this.top = top;
  9606. this.bottom = bottom;
  9607. this.near = near;
  9608. this.far = far;
  9609. this.updateProjectionMatrix();
  9610. }
  9611. copy(source, recursive) {
  9612. super.copy(source, recursive);
  9613. this.left = source.left;
  9614. this.right = source.right;
  9615. this.top = source.top;
  9616. this.bottom = source.bottom;
  9617. this.near = source.near;
  9618. this.far = source.far;
  9619. this.zoom = source.zoom;
  9620. this.view = source.view === null ? null : Object.assign({}, source.view);
  9621. return this;
  9622. }
  9623. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9624. if (this.view === null) {
  9625. this.view = {
  9626. enabled: true,
  9627. fullWidth: 1,
  9628. fullHeight: 1,
  9629. offsetX: 0,
  9630. offsetY: 0,
  9631. width: 1,
  9632. height: 1
  9633. };
  9634. }
  9635. this.view.enabled = true;
  9636. this.view.fullWidth = fullWidth;
  9637. this.view.fullHeight = fullHeight;
  9638. this.view.offsetX = x;
  9639. this.view.offsetY = y;
  9640. this.view.width = width;
  9641. this.view.height = height;
  9642. this.updateProjectionMatrix();
  9643. }
  9644. clearViewOffset() {
  9645. if (this.view !== null) {
  9646. this.view.enabled = false;
  9647. }
  9648. this.updateProjectionMatrix();
  9649. }
  9650. updateProjectionMatrix() {
  9651. const dx = (this.right - this.left) / (2 * this.zoom);
  9652. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9653. const cx = (this.right + this.left) / 2;
  9654. const cy = (this.top + this.bottom) / 2;
  9655. let left = cx - dx;
  9656. let right = cx + dx;
  9657. let top = cy + dy;
  9658. let bottom = cy - dy;
  9659. if (this.view !== null && this.view.enabled) {
  9660. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9661. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9662. left += scaleW * this.view.offsetX;
  9663. right = left + scaleW * this.view.width;
  9664. top -= scaleH * this.view.offsetY;
  9665. bottom = top - scaleH * this.view.height;
  9666. }
  9667. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9668. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9669. }
  9670. toJSON(meta) {
  9671. const data = super.toJSON(meta);
  9672. data.object.zoom = this.zoom;
  9673. data.object.left = this.left;
  9674. data.object.right = this.right;
  9675. data.object.top = this.top;
  9676. data.object.bottom = this.bottom;
  9677. data.object.near = this.near;
  9678. data.object.far = this.far;
  9679. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9680. return data;
  9681. }
  9682. }
  9683. const LOD_MIN = 4;
  9684. // The standard deviations (radians) associated with the extra mips. These are
  9685. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9686. // geometric shadowing function. These sigma values squared must match the
  9687. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9688. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9689. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9690. // samples and exit early, but not recompile the shader.
  9691. const MAX_SAMPLES = 20;
  9692. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9693. const _clearColor = /*@__PURE__*/new Color();
  9694. let _oldTarget = null;
  9695. // Golden Ratio
  9696. const PHI = (1 + Math.sqrt(5)) / 2;
  9697. const INV_PHI = 1 / PHI;
  9698. // Vertices of a dodecahedron (except the opposites, which represent the
  9699. // same axis), used as axis directions evenly spread on a sphere.
  9700. const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  9701. /**
  9702. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9703. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9704. * blur to be quickly accessed based on material roughness. It is packed into a
  9705. * special CubeUV format that allows us to perform custom interpolation so that
  9706. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9707. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9708. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9709. * higher roughness levels. In this way we maintain resolution to smoothly
  9710. * interpolate diffuse lighting while limiting sampling computation.
  9711. *
  9712. * Paper: Fast, Accurate Image-Based Lighting
  9713. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9714. */
  9715. class PMREMGenerator {
  9716. constructor(renderer) {
  9717. this._renderer = renderer;
  9718. this._pingPongRenderTarget = null;
  9719. this._lodMax = 0;
  9720. this._cubeSize = 0;
  9721. this._lodPlanes = [];
  9722. this._sizeLods = [];
  9723. this._sigmas = [];
  9724. this._blurMaterial = null;
  9725. this._cubemapMaterial = null;
  9726. this._equirectMaterial = null;
  9727. this._compileMaterial(this._blurMaterial);
  9728. }
  9729. /**
  9730. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9731. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9732. * in radians to be applied to the scene before PMREM generation. Optional near
  9733. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9734. * is placed at the origin).
  9735. */
  9736. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9737. _oldTarget = this._renderer.getRenderTarget();
  9738. this._setSize(256);
  9739. const cubeUVRenderTarget = this._allocateTargets();
  9740. cubeUVRenderTarget.depthBuffer = true;
  9741. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9742. if (sigma > 0) {
  9743. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9744. }
  9745. this._applyPMREM(cubeUVRenderTarget);
  9746. this._cleanup(cubeUVRenderTarget);
  9747. return cubeUVRenderTarget;
  9748. }
  9749. /**
  9750. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9751. * or HDR. The ideal input image size is 1k (1024 x 512),
  9752. * as this matches best with the 256 x 256 cubemap output.
  9753. */
  9754. fromEquirectangular(equirectangular, renderTarget = null) {
  9755. return this._fromTexture(equirectangular, renderTarget);
  9756. }
  9757. /**
  9758. * Generates a PMREM from an cubemap texture, which can be either LDR
  9759. * or HDR. The ideal input cube size is 256 x 256,
  9760. * as this matches best with the 256 x 256 cubemap output.
  9761. */
  9762. fromCubemap(cubemap, renderTarget = null) {
  9763. return this._fromTexture(cubemap, renderTarget);
  9764. }
  9765. /**
  9766. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9767. * your texture's network fetch for increased concurrency.
  9768. */
  9769. compileCubemapShader() {
  9770. if (this._cubemapMaterial === null) {
  9771. this._cubemapMaterial = _getCubemapMaterial();
  9772. this._compileMaterial(this._cubemapMaterial);
  9773. }
  9774. }
  9775. /**
  9776. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9777. * your texture's network fetch for increased concurrency.
  9778. */
  9779. compileEquirectangularShader() {
  9780. if (this._equirectMaterial === null) {
  9781. this._equirectMaterial = _getEquirectMaterial();
  9782. this._compileMaterial(this._equirectMaterial);
  9783. }
  9784. }
  9785. /**
  9786. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9787. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9788. * one of them will cause any others to also become unusable.
  9789. */
  9790. dispose() {
  9791. this._dispose();
  9792. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9793. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9794. }
  9795. // private interface
  9796. _setSize(cubeSize) {
  9797. this._lodMax = Math.floor(Math.log2(cubeSize));
  9798. this._cubeSize = Math.pow(2, this._lodMax);
  9799. }
  9800. _dispose() {
  9801. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9802. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9803. for (let i = 0; i < this._lodPlanes.length; i++) {
  9804. this._lodPlanes[i].dispose();
  9805. }
  9806. }
  9807. _cleanup(outputTarget) {
  9808. this._renderer.setRenderTarget(_oldTarget);
  9809. outputTarget.scissorTest = false;
  9810. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9811. }
  9812. _fromTexture(texture, renderTarget) {
  9813. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9814. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9815. } else {
  9816. // Equirectangular
  9817. this._setSize(texture.image.width / 4);
  9818. }
  9819. _oldTarget = this._renderer.getRenderTarget();
  9820. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9821. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9822. this._applyPMREM(cubeUVRenderTarget);
  9823. this._cleanup(cubeUVRenderTarget);
  9824. return cubeUVRenderTarget;
  9825. }
  9826. _allocateTargets() {
  9827. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9828. const height = 4 * this._cubeSize;
  9829. const params = {
  9830. magFilter: LinearFilter,
  9831. minFilter: LinearFilter,
  9832. generateMipmaps: false,
  9833. type: HalfFloatType,
  9834. format: RGBAFormat,
  9835. encoding: LinearEncoding,
  9836. depthBuffer: false
  9837. };
  9838. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9839. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9840. if (this._pingPongRenderTarget !== null) {
  9841. this._dispose();
  9842. }
  9843. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9844. const {
  9845. _lodMax
  9846. } = this;
  9847. ({
  9848. sizeLods: this._sizeLods,
  9849. lodPlanes: this._lodPlanes,
  9850. sigmas: this._sigmas
  9851. } = _createPlanes(_lodMax));
  9852. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9853. }
  9854. return cubeUVRenderTarget;
  9855. }
  9856. _compileMaterial(material) {
  9857. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9858. this._renderer.compile(tmpMesh, _flatCamera);
  9859. }
  9860. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9861. const fov = 90;
  9862. const aspect = 1;
  9863. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9864. const upSign = [1, -1, 1, 1, 1, 1];
  9865. const forwardSign = [1, 1, 1, -1, -1, -1];
  9866. const renderer = this._renderer;
  9867. const originalAutoClear = renderer.autoClear;
  9868. const toneMapping = renderer.toneMapping;
  9869. renderer.getClearColor(_clearColor);
  9870. renderer.toneMapping = NoToneMapping;
  9871. renderer.autoClear = false;
  9872. const backgroundMaterial = new MeshBasicMaterial({
  9873. name: 'PMREM.Background',
  9874. side: BackSide,
  9875. depthWrite: false,
  9876. depthTest: false
  9877. });
  9878. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9879. let useSolidColor = false;
  9880. const background = scene.background;
  9881. if (background) {
  9882. if (background.isColor) {
  9883. backgroundMaterial.color.copy(background);
  9884. scene.background = null;
  9885. useSolidColor = true;
  9886. }
  9887. } else {
  9888. backgroundMaterial.color.copy(_clearColor);
  9889. useSolidColor = true;
  9890. }
  9891. for (let i = 0; i < 6; i++) {
  9892. const col = i % 3;
  9893. if (col === 0) {
  9894. cubeCamera.up.set(0, upSign[i], 0);
  9895. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9896. } else if (col === 1) {
  9897. cubeCamera.up.set(0, 0, upSign[i]);
  9898. cubeCamera.lookAt(0, forwardSign[i], 0);
  9899. } else {
  9900. cubeCamera.up.set(0, upSign[i], 0);
  9901. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9902. }
  9903. const size = this._cubeSize;
  9904. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9905. renderer.setRenderTarget(cubeUVRenderTarget);
  9906. if (useSolidColor) {
  9907. renderer.render(backgroundBox, cubeCamera);
  9908. }
  9909. renderer.render(scene, cubeCamera);
  9910. }
  9911. backgroundBox.geometry.dispose();
  9912. backgroundBox.material.dispose();
  9913. renderer.toneMapping = toneMapping;
  9914. renderer.autoClear = originalAutoClear;
  9915. scene.background = background;
  9916. }
  9917. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9918. const renderer = this._renderer;
  9919. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9920. if (isCubeTexture) {
  9921. if (this._cubemapMaterial === null) {
  9922. this._cubemapMaterial = _getCubemapMaterial();
  9923. }
  9924. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9925. } else {
  9926. if (this._equirectMaterial === null) {
  9927. this._equirectMaterial = _getEquirectMaterial();
  9928. }
  9929. }
  9930. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9931. const mesh = new Mesh(this._lodPlanes[0], material);
  9932. const uniforms = material.uniforms;
  9933. uniforms['envMap'].value = texture;
  9934. const size = this._cubeSize;
  9935. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9936. renderer.setRenderTarget(cubeUVRenderTarget);
  9937. renderer.render(mesh, _flatCamera);
  9938. }
  9939. _applyPMREM(cubeUVRenderTarget) {
  9940. const renderer = this._renderer;
  9941. const autoClear = renderer.autoClear;
  9942. renderer.autoClear = false;
  9943. for (let i = 1; i < this._lodPlanes.length; i++) {
  9944. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9945. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9946. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9947. }
  9948. renderer.autoClear = autoClear;
  9949. }
  9950. /**
  9951. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9952. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9953. * the blur latitudinally (around the poles), and then longitudinally (towards
  9954. * the poles) to approximate the orthogonally-separable blur. It is least
  9955. * accurate at the poles, but still does a decent job.
  9956. */
  9957. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9958. const pingPongRenderTarget = this._pingPongRenderTarget;
  9959. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9960. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9961. }
  9962. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9963. const renderer = this._renderer;
  9964. const blurMaterial = this._blurMaterial;
  9965. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9966. console.error('blur direction must be either latitudinal or longitudinal!');
  9967. }
  9968. // Number of standard deviations at which to cut off the discrete approximation.
  9969. const STANDARD_DEVIATIONS = 3;
  9970. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9971. const blurUniforms = blurMaterial.uniforms;
  9972. const pixels = this._sizeLods[lodIn] - 1;
  9973. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9974. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9975. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9976. if (samples > MAX_SAMPLES) {
  9977. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9978. }
  9979. const weights = [];
  9980. let sum = 0;
  9981. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9982. const x = i / sigmaPixels;
  9983. const weight = Math.exp(-x * x / 2);
  9984. weights.push(weight);
  9985. if (i === 0) {
  9986. sum += weight;
  9987. } else if (i < samples) {
  9988. sum += 2 * weight;
  9989. }
  9990. }
  9991. for (let i = 0; i < weights.length; i++) {
  9992. weights[i] = weights[i] / sum;
  9993. }
  9994. blurUniforms['envMap'].value = targetIn.texture;
  9995. blurUniforms['samples'].value = samples;
  9996. blurUniforms['weights'].value = weights;
  9997. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9998. if (poleAxis) {
  9999. blurUniforms['poleAxis'].value = poleAxis;
  10000. }
  10001. const {
  10002. _lodMax
  10003. } = this;
  10004. blurUniforms['dTheta'].value = radiansPerPixel;
  10005. blurUniforms['mipInt'].value = _lodMax - lodIn;
  10006. const outputSize = this._sizeLods[lodOut];
  10007. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  10008. const y = 4 * (this._cubeSize - outputSize);
  10009. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  10010. renderer.setRenderTarget(targetOut);
  10011. renderer.render(blurMesh, _flatCamera);
  10012. }
  10013. }
  10014. function _createPlanes(lodMax) {
  10015. const lodPlanes = [];
  10016. const sizeLods = [];
  10017. const sigmas = [];
  10018. let lod = lodMax;
  10019. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10020. for (let i = 0; i < totalLods; i++) {
  10021. const sizeLod = Math.pow(2, lod);
  10022. sizeLods.push(sizeLod);
  10023. let sigma = 1.0 / sizeLod;
  10024. if (i > lodMax - LOD_MIN) {
  10025. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  10026. } else if (i === 0) {
  10027. sigma = 0;
  10028. }
  10029. sigmas.push(sigma);
  10030. const texelSize = 1.0 / (sizeLod - 2);
  10031. const min = -texelSize;
  10032. const max = 1 + texelSize;
  10033. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  10034. const cubeFaces = 6;
  10035. const vertices = 6;
  10036. const positionSize = 3;
  10037. const uvSize = 2;
  10038. const faceIndexSize = 1;
  10039. const position = new Float32Array(positionSize * vertices * cubeFaces);
  10040. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  10041. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  10042. for (let face = 0; face < cubeFaces; face++) {
  10043. const x = face % 3 * 2 / 3 - 1;
  10044. const y = face > 2 ? 0 : -1;
  10045. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  10046. position.set(coordinates, positionSize * vertices * face);
  10047. uv.set(uv1, uvSize * vertices * face);
  10048. const fill = [face, face, face, face, face, face];
  10049. faceIndex.set(fill, faceIndexSize * vertices * face);
  10050. }
  10051. const planes = new BufferGeometry();
  10052. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  10053. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  10054. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  10055. lodPlanes.push(planes);
  10056. if (lod > LOD_MIN) {
  10057. lod--;
  10058. }
  10059. }
  10060. return {
  10061. lodPlanes,
  10062. sizeLods,
  10063. sigmas
  10064. };
  10065. }
  10066. function _createRenderTarget(width, height, params) {
  10067. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  10068. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10069. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10070. cubeUVRenderTarget.scissorTest = true;
  10071. return cubeUVRenderTarget;
  10072. }
  10073. function _setViewport(target, x, y, width, height) {
  10074. target.viewport.set(x, y, width, height);
  10075. target.scissor.set(x, y, width, height);
  10076. }
  10077. function _getBlurShader(lodMax, width, height) {
  10078. const weights = new Float32Array(MAX_SAMPLES);
  10079. const poleAxis = new Vector3(0, 1, 0);
  10080. const shaderMaterial = new ShaderMaterial({
  10081. name: 'SphericalGaussianBlur',
  10082. defines: {
  10083. 'n': MAX_SAMPLES,
  10084. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10085. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10086. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  10087. },
  10088. uniforms: {
  10089. 'envMap': {
  10090. value: null
  10091. },
  10092. 'samples': {
  10093. value: 1
  10094. },
  10095. 'weights': {
  10096. value: weights
  10097. },
  10098. 'latitudinal': {
  10099. value: false
  10100. },
  10101. 'dTheta': {
  10102. value: 0
  10103. },
  10104. 'mipInt': {
  10105. value: 0
  10106. },
  10107. 'poleAxis': {
  10108. value: poleAxis
  10109. }
  10110. },
  10111. vertexShader: _getCommonVertexShader(),
  10112. fragmentShader: /* glsl */`
  10113. precision mediump float;
  10114. precision mediump int;
  10115. varying vec3 vOutputDirection;
  10116. uniform sampler2D envMap;
  10117. uniform int samples;
  10118. uniform float weights[ n ];
  10119. uniform bool latitudinal;
  10120. uniform float dTheta;
  10121. uniform float mipInt;
  10122. uniform vec3 poleAxis;
  10123. #define ENVMAP_TYPE_CUBE_UV
  10124. #include <cube_uv_reflection_fragment>
  10125. vec3 getSample( float theta, vec3 axis ) {
  10126. float cosTheta = cos( theta );
  10127. // Rodrigues' axis-angle rotation
  10128. vec3 sampleDirection = vOutputDirection * cosTheta
  10129. + cross( axis, vOutputDirection ) * sin( theta )
  10130. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10131. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10132. }
  10133. void main() {
  10134. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10135. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10136. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10137. }
  10138. axis = normalize( axis );
  10139. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10140. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10141. for ( int i = 1; i < n; i++ ) {
  10142. if ( i >= samples ) {
  10143. break;
  10144. }
  10145. float theta = dTheta * float( i );
  10146. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10147. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10148. }
  10149. }
  10150. `,
  10151. blending: NoBlending,
  10152. depthTest: false,
  10153. depthWrite: false
  10154. });
  10155. return shaderMaterial;
  10156. }
  10157. function _getEquirectMaterial() {
  10158. return new ShaderMaterial({
  10159. name: 'EquirectangularToCubeUV',
  10160. uniforms: {
  10161. 'envMap': {
  10162. value: null
  10163. }
  10164. },
  10165. vertexShader: _getCommonVertexShader(),
  10166. fragmentShader: /* glsl */`
  10167. precision mediump float;
  10168. precision mediump int;
  10169. varying vec3 vOutputDirection;
  10170. uniform sampler2D envMap;
  10171. #include <common>
  10172. void main() {
  10173. vec3 outputDirection = normalize( vOutputDirection );
  10174. vec2 uv = equirectUv( outputDirection );
  10175. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10176. }
  10177. `,
  10178. blending: NoBlending,
  10179. depthTest: false,
  10180. depthWrite: false
  10181. });
  10182. }
  10183. function _getCubemapMaterial() {
  10184. return new ShaderMaterial({
  10185. name: 'CubemapToCubeUV',
  10186. uniforms: {
  10187. 'envMap': {
  10188. value: null
  10189. },
  10190. 'flipEnvMap': {
  10191. value: -1
  10192. }
  10193. },
  10194. vertexShader: _getCommonVertexShader(),
  10195. fragmentShader: /* glsl */`
  10196. precision mediump float;
  10197. precision mediump int;
  10198. uniform float flipEnvMap;
  10199. varying vec3 vOutputDirection;
  10200. uniform samplerCube envMap;
  10201. void main() {
  10202. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10203. }
  10204. `,
  10205. blending: NoBlending,
  10206. depthTest: false,
  10207. depthWrite: false
  10208. });
  10209. }
  10210. function _getCommonVertexShader() {
  10211. return (/* glsl */`
  10212. precision mediump float;
  10213. precision mediump int;
  10214. attribute float faceIndex;
  10215. varying vec3 vOutputDirection;
  10216. // RH coordinate system; PMREM face-indexing convention
  10217. vec3 getDirection( vec2 uv, float face ) {
  10218. uv = 2.0 * uv - 1.0;
  10219. vec3 direction = vec3( uv, 1.0 );
  10220. if ( face == 0.0 ) {
  10221. direction = direction.zyx; // ( 1, v, u ) pos x
  10222. } else if ( face == 1.0 ) {
  10223. direction = direction.xzy;
  10224. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10225. } else if ( face == 2.0 ) {
  10226. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10227. } else if ( face == 3.0 ) {
  10228. direction = direction.zyx;
  10229. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10230. } else if ( face == 4.0 ) {
  10231. direction = direction.xzy;
  10232. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10233. } else if ( face == 5.0 ) {
  10234. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10235. }
  10236. return direction;
  10237. }
  10238. void main() {
  10239. vOutputDirection = getDirection( uv, faceIndex );
  10240. gl_Position = vec4( position, 1.0 );
  10241. }
  10242. `
  10243. );
  10244. }
  10245. function WebGLCubeUVMaps(renderer) {
  10246. let cubeUVmaps = new WeakMap();
  10247. let pmremGenerator = null;
  10248. function get(texture) {
  10249. if (texture && texture.isTexture) {
  10250. const mapping = texture.mapping;
  10251. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10252. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10253. // equirect/cube map to cubeUV conversion
  10254. if (isEquirectMap || isCubeMap) {
  10255. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10256. texture.needsPMREMUpdate = false;
  10257. let renderTarget = cubeUVmaps.get(texture);
  10258. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10259. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10260. cubeUVmaps.set(texture, renderTarget);
  10261. return renderTarget.texture;
  10262. } else {
  10263. if (cubeUVmaps.has(texture)) {
  10264. return cubeUVmaps.get(texture).texture;
  10265. } else {
  10266. const image = texture.image;
  10267. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10268. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10269. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10270. cubeUVmaps.set(texture, renderTarget);
  10271. texture.addEventListener('dispose', onTextureDispose);
  10272. return renderTarget.texture;
  10273. } else {
  10274. // image not yet ready. try the conversion next frame
  10275. return null;
  10276. }
  10277. }
  10278. }
  10279. }
  10280. }
  10281. return texture;
  10282. }
  10283. function isCubeTextureComplete(image) {
  10284. let count = 0;
  10285. const length = 6;
  10286. for (let i = 0; i < length; i++) {
  10287. if (image[i] !== undefined) count++;
  10288. }
  10289. return count === length;
  10290. }
  10291. function onTextureDispose(event) {
  10292. const texture = event.target;
  10293. texture.removeEventListener('dispose', onTextureDispose);
  10294. const cubemapUV = cubeUVmaps.get(texture);
  10295. if (cubemapUV !== undefined) {
  10296. cubeUVmaps.delete(texture);
  10297. cubemapUV.dispose();
  10298. }
  10299. }
  10300. function dispose() {
  10301. cubeUVmaps = new WeakMap();
  10302. if (pmremGenerator !== null) {
  10303. pmremGenerator.dispose();
  10304. pmremGenerator = null;
  10305. }
  10306. }
  10307. return {
  10308. get: get,
  10309. dispose: dispose
  10310. };
  10311. }
  10312. function WebGLExtensions(gl) {
  10313. const extensions = {};
  10314. function getExtension(name) {
  10315. if (extensions[name] !== undefined) {
  10316. return extensions[name];
  10317. }
  10318. let extension;
  10319. switch (name) {
  10320. case 'WEBGL_depth_texture':
  10321. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10322. break;
  10323. case 'EXT_texture_filter_anisotropic':
  10324. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10325. break;
  10326. case 'WEBGL_compressed_texture_s3tc':
  10327. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10328. break;
  10329. case 'WEBGL_compressed_texture_pvrtc':
  10330. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10331. break;
  10332. default:
  10333. extension = gl.getExtension(name);
  10334. }
  10335. extensions[name] = extension;
  10336. return extension;
  10337. }
  10338. return {
  10339. has: function (name) {
  10340. return getExtension(name) !== null;
  10341. },
  10342. init: function (capabilities) {
  10343. if (capabilities.isWebGL2) {
  10344. getExtension('EXT_color_buffer_float');
  10345. } else {
  10346. getExtension('WEBGL_depth_texture');
  10347. getExtension('OES_texture_float');
  10348. getExtension('OES_texture_half_float');
  10349. getExtension('OES_texture_half_float_linear');
  10350. getExtension('OES_standard_derivatives');
  10351. getExtension('OES_element_index_uint');
  10352. getExtension('OES_vertex_array_object');
  10353. getExtension('ANGLE_instanced_arrays');
  10354. }
  10355. getExtension('OES_texture_float_linear');
  10356. getExtension('EXT_color_buffer_half_float');
  10357. getExtension('WEBGL_multisampled_render_to_texture');
  10358. },
  10359. get: function (name) {
  10360. const extension = getExtension(name);
  10361. if (extension === null) {
  10362. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10363. }
  10364. return extension;
  10365. }
  10366. };
  10367. }
  10368. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10369. const geometries = {};
  10370. const wireframeAttributes = new WeakMap();
  10371. function onGeometryDispose(event) {
  10372. const geometry = event.target;
  10373. if (geometry.index !== null) {
  10374. attributes.remove(geometry.index);
  10375. }
  10376. for (const name in geometry.attributes) {
  10377. attributes.remove(geometry.attributes[name]);
  10378. }
  10379. geometry.removeEventListener('dispose', onGeometryDispose);
  10380. delete geometries[geometry.id];
  10381. const attribute = wireframeAttributes.get(geometry);
  10382. if (attribute) {
  10383. attributes.remove(attribute);
  10384. wireframeAttributes.delete(geometry);
  10385. }
  10386. bindingStates.releaseStatesOfGeometry(geometry);
  10387. if (geometry.isInstancedBufferGeometry === true) {
  10388. delete geometry._maxInstanceCount;
  10389. }
  10390. //
  10391. info.memory.geometries--;
  10392. }
  10393. function get(object, geometry) {
  10394. if (geometries[geometry.id] === true) return geometry;
  10395. geometry.addEventListener('dispose', onGeometryDispose);
  10396. geometries[geometry.id] = true;
  10397. info.memory.geometries++;
  10398. return geometry;
  10399. }
  10400. function update(geometry) {
  10401. const geometryAttributes = geometry.attributes;
  10402. // Updating index buffer in VAO now. See WebGLBindingStates.
  10403. for (const name in geometryAttributes) {
  10404. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10405. }
  10406. // morph targets
  10407. const morphAttributes = geometry.morphAttributes;
  10408. for (const name in morphAttributes) {
  10409. const array = morphAttributes[name];
  10410. for (let i = 0, l = array.length; i < l; i++) {
  10411. attributes.update(array[i], gl.ARRAY_BUFFER);
  10412. }
  10413. }
  10414. }
  10415. function updateWireframeAttribute(geometry) {
  10416. const indices = [];
  10417. const geometryIndex = geometry.index;
  10418. const geometryPosition = geometry.attributes.position;
  10419. let version = 0;
  10420. if (geometryIndex !== null) {
  10421. const array = geometryIndex.array;
  10422. version = geometryIndex.version;
  10423. for (let i = 0, l = array.length; i < l; i += 3) {
  10424. const a = array[i + 0];
  10425. const b = array[i + 1];
  10426. const c = array[i + 2];
  10427. indices.push(a, b, b, c, c, a);
  10428. }
  10429. } else {
  10430. const array = geometryPosition.array;
  10431. version = geometryPosition.version;
  10432. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10433. const a = i + 0;
  10434. const b = i + 1;
  10435. const c = i + 2;
  10436. indices.push(a, b, b, c, c, a);
  10437. }
  10438. }
  10439. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10440. attribute.version = version;
  10441. // Updating index buffer in VAO now. See WebGLBindingStates
  10442. //
  10443. const previousAttribute = wireframeAttributes.get(geometry);
  10444. if (previousAttribute) attributes.remove(previousAttribute);
  10445. //
  10446. wireframeAttributes.set(geometry, attribute);
  10447. }
  10448. function getWireframeAttribute(geometry) {
  10449. const currentAttribute = wireframeAttributes.get(geometry);
  10450. if (currentAttribute) {
  10451. const geometryIndex = geometry.index;
  10452. if (geometryIndex !== null) {
  10453. // if the attribute is obsolete, create a new one
  10454. if (currentAttribute.version < geometryIndex.version) {
  10455. updateWireframeAttribute(geometry);
  10456. }
  10457. }
  10458. } else {
  10459. updateWireframeAttribute(geometry);
  10460. }
  10461. return wireframeAttributes.get(geometry);
  10462. }
  10463. return {
  10464. get: get,
  10465. update: update,
  10466. getWireframeAttribute: getWireframeAttribute
  10467. };
  10468. }
  10469. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10470. const isWebGL2 = capabilities.isWebGL2;
  10471. let mode;
  10472. function setMode(value) {
  10473. mode = value;
  10474. }
  10475. let type, bytesPerElement;
  10476. function setIndex(value) {
  10477. type = value.type;
  10478. bytesPerElement = value.bytesPerElement;
  10479. }
  10480. function render(start, count) {
  10481. gl.drawElements(mode, count, type, start * bytesPerElement);
  10482. info.update(count, mode, 1);
  10483. }
  10484. function renderInstances(start, count, primcount) {
  10485. if (primcount === 0) return;
  10486. let extension, methodName;
  10487. if (isWebGL2) {
  10488. extension = gl;
  10489. methodName = 'drawElementsInstanced';
  10490. } else {
  10491. extension = extensions.get('ANGLE_instanced_arrays');
  10492. methodName = 'drawElementsInstancedANGLE';
  10493. if (extension === null) {
  10494. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10495. return;
  10496. }
  10497. }
  10498. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10499. info.update(count, mode, primcount);
  10500. }
  10501. //
  10502. this.setMode = setMode;
  10503. this.setIndex = setIndex;
  10504. this.render = render;
  10505. this.renderInstances = renderInstances;
  10506. }
  10507. function WebGLInfo(gl) {
  10508. const memory = {
  10509. geometries: 0,
  10510. textures: 0
  10511. };
  10512. const render = {
  10513. frame: 0,
  10514. calls: 0,
  10515. triangles: 0,
  10516. points: 0,
  10517. lines: 0
  10518. };
  10519. function update(count, mode, instanceCount) {
  10520. render.calls++;
  10521. switch (mode) {
  10522. case gl.TRIANGLES:
  10523. render.triangles += instanceCount * (count / 3);
  10524. break;
  10525. case gl.LINES:
  10526. render.lines += instanceCount * (count / 2);
  10527. break;
  10528. case gl.LINE_STRIP:
  10529. render.lines += instanceCount * (count - 1);
  10530. break;
  10531. case gl.LINE_LOOP:
  10532. render.lines += instanceCount * count;
  10533. break;
  10534. case gl.POINTS:
  10535. render.points += instanceCount * count;
  10536. break;
  10537. default:
  10538. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10539. break;
  10540. }
  10541. }
  10542. function reset() {
  10543. render.frame++;
  10544. render.calls = 0;
  10545. render.triangles = 0;
  10546. render.points = 0;
  10547. render.lines = 0;
  10548. }
  10549. return {
  10550. memory: memory,
  10551. render: render,
  10552. programs: null,
  10553. autoReset: true,
  10554. reset: reset,
  10555. update: update
  10556. };
  10557. }
  10558. function numericalSort(a, b) {
  10559. return a[0] - b[0];
  10560. }
  10561. function absNumericalSort(a, b) {
  10562. return Math.abs(b[1]) - Math.abs(a[1]);
  10563. }
  10564. function WebGLMorphtargets(gl, capabilities, textures) {
  10565. const influencesList = {};
  10566. const morphInfluences = new Float32Array(8);
  10567. const morphTextures = new WeakMap();
  10568. const morph = new Vector4();
  10569. const workInfluences = [];
  10570. for (let i = 0; i < 8; i++) {
  10571. workInfluences[i] = [i, 0];
  10572. }
  10573. function update(object, geometry, material, program) {
  10574. const objectInfluences = object.morphTargetInfluences;
  10575. if (capabilities.isWebGL2 === true) {
  10576. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10577. // into an array of data textures. Each layer represents a single morph target.
  10578. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10579. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10580. let entry = morphTextures.get(geometry);
  10581. if (entry === undefined || entry.count !== morphTargetsCount) {
  10582. if (entry !== undefined) entry.texture.dispose();
  10583. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10584. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10585. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10586. const morphTargets = geometry.morphAttributes.position || [];
  10587. const morphNormals = geometry.morphAttributes.normal || [];
  10588. const morphColors = geometry.morphAttributes.color || [];
  10589. let vertexDataCount = 0;
  10590. if (hasMorphPosition === true) vertexDataCount = 1;
  10591. if (hasMorphNormals === true) vertexDataCount = 2;
  10592. if (hasMorphColors === true) vertexDataCount = 3;
  10593. let width = geometry.attributes.position.count * vertexDataCount;
  10594. let height = 1;
  10595. if (width > capabilities.maxTextureSize) {
  10596. height = Math.ceil(width / capabilities.maxTextureSize);
  10597. width = capabilities.maxTextureSize;
  10598. }
  10599. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10600. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10601. texture.type = FloatType;
  10602. texture.needsUpdate = true;
  10603. // fill buffer
  10604. const vertexDataStride = vertexDataCount * 4;
  10605. for (let i = 0; i < morphTargetsCount; i++) {
  10606. const morphTarget = morphTargets[i];
  10607. const morphNormal = morphNormals[i];
  10608. const morphColor = morphColors[i];
  10609. const offset = width * height * 4 * i;
  10610. for (let j = 0; j < morphTarget.count; j++) {
  10611. const stride = j * vertexDataStride;
  10612. if (hasMorphPosition === true) {
  10613. morph.fromBufferAttribute(morphTarget, j);
  10614. buffer[offset + stride + 0] = morph.x;
  10615. buffer[offset + stride + 1] = morph.y;
  10616. buffer[offset + stride + 2] = morph.z;
  10617. buffer[offset + stride + 3] = 0;
  10618. }
  10619. if (hasMorphNormals === true) {
  10620. morph.fromBufferAttribute(morphNormal, j);
  10621. buffer[offset + stride + 4] = morph.x;
  10622. buffer[offset + stride + 5] = morph.y;
  10623. buffer[offset + stride + 6] = morph.z;
  10624. buffer[offset + stride + 7] = 0;
  10625. }
  10626. if (hasMorphColors === true) {
  10627. morph.fromBufferAttribute(morphColor, j);
  10628. buffer[offset + stride + 8] = morph.x;
  10629. buffer[offset + stride + 9] = morph.y;
  10630. buffer[offset + stride + 10] = morph.z;
  10631. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10632. }
  10633. }
  10634. }
  10635. entry = {
  10636. count: morphTargetsCount,
  10637. texture: texture,
  10638. size: new Vector2(width, height)
  10639. };
  10640. morphTextures.set(geometry, entry);
  10641. function disposeTexture() {
  10642. texture.dispose();
  10643. morphTextures.delete(geometry);
  10644. geometry.removeEventListener('dispose', disposeTexture);
  10645. }
  10646. geometry.addEventListener('dispose', disposeTexture);
  10647. }
  10648. //
  10649. let morphInfluencesSum = 0;
  10650. for (let i = 0; i < objectInfluences.length; i++) {
  10651. morphInfluencesSum += objectInfluences[i];
  10652. }
  10653. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10654. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10655. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10656. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10657. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10658. } else {
  10659. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10660. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10661. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10662. let influences = influencesList[geometry.id];
  10663. if (influences === undefined || influences.length !== length) {
  10664. // initialise list
  10665. influences = [];
  10666. for (let i = 0; i < length; i++) {
  10667. influences[i] = [i, 0];
  10668. }
  10669. influencesList[geometry.id] = influences;
  10670. }
  10671. // Collect influences
  10672. for (let i = 0; i < length; i++) {
  10673. const influence = influences[i];
  10674. influence[0] = i;
  10675. influence[1] = objectInfluences[i];
  10676. }
  10677. influences.sort(absNumericalSort);
  10678. for (let i = 0; i < 8; i++) {
  10679. if (i < length && influences[i][1]) {
  10680. workInfluences[i][0] = influences[i][0];
  10681. workInfluences[i][1] = influences[i][1];
  10682. } else {
  10683. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10684. workInfluences[i][1] = 0;
  10685. }
  10686. }
  10687. workInfluences.sort(numericalSort);
  10688. const morphTargets = geometry.morphAttributes.position;
  10689. const morphNormals = geometry.morphAttributes.normal;
  10690. let morphInfluencesSum = 0;
  10691. for (let i = 0; i < 8; i++) {
  10692. const influence = workInfluences[i];
  10693. const index = influence[0];
  10694. const value = influence[1];
  10695. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10696. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10697. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10698. }
  10699. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10700. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10701. }
  10702. morphInfluences[i] = value;
  10703. morphInfluencesSum += value;
  10704. } else {
  10705. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10706. geometry.deleteAttribute('morphTarget' + i);
  10707. }
  10708. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10709. geometry.deleteAttribute('morphNormal' + i);
  10710. }
  10711. morphInfluences[i] = 0;
  10712. }
  10713. }
  10714. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10715. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10716. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10717. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10718. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10719. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10720. }
  10721. }
  10722. return {
  10723. update: update
  10724. };
  10725. }
  10726. function WebGLObjects(gl, geometries, attributes, info) {
  10727. let updateMap = new WeakMap();
  10728. function update(object) {
  10729. const frame = info.render.frame;
  10730. const geometry = object.geometry;
  10731. const buffergeometry = geometries.get(object, geometry);
  10732. // Update once per frame
  10733. if (updateMap.get(buffergeometry) !== frame) {
  10734. geometries.update(buffergeometry);
  10735. updateMap.set(buffergeometry, frame);
  10736. }
  10737. if (object.isInstancedMesh) {
  10738. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10739. object.addEventListener('dispose', onInstancedMeshDispose);
  10740. }
  10741. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10742. if (object.instanceColor !== null) {
  10743. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10744. }
  10745. }
  10746. return buffergeometry;
  10747. }
  10748. function dispose() {
  10749. updateMap = new WeakMap();
  10750. }
  10751. function onInstancedMeshDispose(event) {
  10752. const instancedMesh = event.target;
  10753. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10754. attributes.remove(instancedMesh.instanceMatrix);
  10755. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10756. }
  10757. return {
  10758. update: update,
  10759. dispose: dispose
  10760. };
  10761. }
  10762. /**
  10763. * Uniforms of a program.
  10764. * Those form a tree structure with a special top-level container for the root,
  10765. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10766. *
  10767. *
  10768. * Properties of inner nodes including the top-level container:
  10769. *
  10770. * .seq - array of nested uniforms
  10771. * .map - nested uniforms by name
  10772. *
  10773. *
  10774. * Methods of all nodes except the top-level container:
  10775. *
  10776. * .setValue( gl, value, [textures] )
  10777. *
  10778. * uploads a uniform value(s)
  10779. * the 'textures' parameter is needed for sampler uniforms
  10780. *
  10781. *
  10782. * Static methods of the top-level container (textures factorizations):
  10783. *
  10784. * .upload( gl, seq, values, textures )
  10785. *
  10786. * sets uniforms in 'seq' to 'values[id].value'
  10787. *
  10788. * .seqWithValue( seq, values ) : filteredSeq
  10789. *
  10790. * filters 'seq' entries with corresponding entry in values
  10791. *
  10792. *
  10793. * Methods of the top-level container (textures factorizations):
  10794. *
  10795. * .setValue( gl, name, value, textures )
  10796. *
  10797. * sets uniform with name 'name' to 'value'
  10798. *
  10799. * .setOptional( gl, obj, prop )
  10800. *
  10801. * like .set for an optional property of the object
  10802. *
  10803. */
  10804. const emptyTexture = /*@__PURE__*/new Texture();
  10805. const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture();
  10806. const empty3dTexture = /*@__PURE__*/new Data3DTexture();
  10807. const emptyCubeTexture = /*@__PURE__*/new CubeTexture();
  10808. // --- Utilities ---
  10809. // Array Caches (provide typed arrays for temporary by size)
  10810. const arrayCacheF32 = [];
  10811. const arrayCacheI32 = [];
  10812. // Float32Array caches used for uploading Matrix uniforms
  10813. const mat4array = new Float32Array(16);
  10814. const mat3array = new Float32Array(9);
  10815. const mat2array = new Float32Array(4);
  10816. // Flattening for arrays of vectors and matrices
  10817. function flatten(array, nBlocks, blockSize) {
  10818. const firstElem = array[0];
  10819. if (firstElem <= 0 || firstElem > 0) return array;
  10820. // unoptimized: ! isNaN( firstElem )
  10821. // see http://jacksondunstan.com/articles/983
  10822. const n = nBlocks * blockSize;
  10823. let r = arrayCacheF32[n];
  10824. if (r === undefined) {
  10825. r = new Float32Array(n);
  10826. arrayCacheF32[n] = r;
  10827. }
  10828. if (nBlocks !== 0) {
  10829. firstElem.toArray(r, 0);
  10830. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10831. offset += blockSize;
  10832. array[i].toArray(r, offset);
  10833. }
  10834. }
  10835. return r;
  10836. }
  10837. function arraysEqual(a, b) {
  10838. if (a.length !== b.length) return false;
  10839. for (let i = 0, l = a.length; i < l; i++) {
  10840. if (a[i] !== b[i]) return false;
  10841. }
  10842. return true;
  10843. }
  10844. function copyArray(a, b) {
  10845. for (let i = 0, l = b.length; i < l; i++) {
  10846. a[i] = b[i];
  10847. }
  10848. }
  10849. // Texture unit allocation
  10850. function allocTexUnits(textures, n) {
  10851. let r = arrayCacheI32[n];
  10852. if (r === undefined) {
  10853. r = new Int32Array(n);
  10854. arrayCacheI32[n] = r;
  10855. }
  10856. for (let i = 0; i !== n; ++i) {
  10857. r[i] = textures.allocateTextureUnit();
  10858. }
  10859. return r;
  10860. }
  10861. // --- Setters ---
  10862. // Note: Defining these methods externally, because they come in a bunch
  10863. // and this way their names minify.
  10864. // Single scalar
  10865. function setValueV1f(gl, v) {
  10866. const cache = this.cache;
  10867. if (cache[0] === v) return;
  10868. gl.uniform1f(this.addr, v);
  10869. cache[0] = v;
  10870. }
  10871. // Single float vector (from flat array or THREE.VectorN)
  10872. function setValueV2f(gl, v) {
  10873. const cache = this.cache;
  10874. if (v.x !== undefined) {
  10875. if (cache[0] !== v.x || cache[1] !== v.y) {
  10876. gl.uniform2f(this.addr, v.x, v.y);
  10877. cache[0] = v.x;
  10878. cache[1] = v.y;
  10879. }
  10880. } else {
  10881. if (arraysEqual(cache, v)) return;
  10882. gl.uniform2fv(this.addr, v);
  10883. copyArray(cache, v);
  10884. }
  10885. }
  10886. function setValueV3f(gl, v) {
  10887. const cache = this.cache;
  10888. if (v.x !== undefined) {
  10889. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10890. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10891. cache[0] = v.x;
  10892. cache[1] = v.y;
  10893. cache[2] = v.z;
  10894. }
  10895. } else if (v.r !== undefined) {
  10896. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10897. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10898. cache[0] = v.r;
  10899. cache[1] = v.g;
  10900. cache[2] = v.b;
  10901. }
  10902. } else {
  10903. if (arraysEqual(cache, v)) return;
  10904. gl.uniform3fv(this.addr, v);
  10905. copyArray(cache, v);
  10906. }
  10907. }
  10908. function setValueV4f(gl, v) {
  10909. const cache = this.cache;
  10910. if (v.x !== undefined) {
  10911. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10912. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10913. cache[0] = v.x;
  10914. cache[1] = v.y;
  10915. cache[2] = v.z;
  10916. cache[3] = v.w;
  10917. }
  10918. } else {
  10919. if (arraysEqual(cache, v)) return;
  10920. gl.uniform4fv(this.addr, v);
  10921. copyArray(cache, v);
  10922. }
  10923. }
  10924. // Single matrix (from flat array or THREE.MatrixN)
  10925. function setValueM2(gl, v) {
  10926. const cache = this.cache;
  10927. const elements = v.elements;
  10928. if (elements === undefined) {
  10929. if (arraysEqual(cache, v)) return;
  10930. gl.uniformMatrix2fv(this.addr, false, v);
  10931. copyArray(cache, v);
  10932. } else {
  10933. if (arraysEqual(cache, elements)) return;
  10934. mat2array.set(elements);
  10935. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10936. copyArray(cache, elements);
  10937. }
  10938. }
  10939. function setValueM3(gl, v) {
  10940. const cache = this.cache;
  10941. const elements = v.elements;
  10942. if (elements === undefined) {
  10943. if (arraysEqual(cache, v)) return;
  10944. gl.uniformMatrix3fv(this.addr, false, v);
  10945. copyArray(cache, v);
  10946. } else {
  10947. if (arraysEqual(cache, elements)) return;
  10948. mat3array.set(elements);
  10949. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10950. copyArray(cache, elements);
  10951. }
  10952. }
  10953. function setValueM4(gl, v) {
  10954. const cache = this.cache;
  10955. const elements = v.elements;
  10956. if (elements === undefined) {
  10957. if (arraysEqual(cache, v)) return;
  10958. gl.uniformMatrix4fv(this.addr, false, v);
  10959. copyArray(cache, v);
  10960. } else {
  10961. if (arraysEqual(cache, elements)) return;
  10962. mat4array.set(elements);
  10963. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10964. copyArray(cache, elements);
  10965. }
  10966. }
  10967. // Single integer / boolean
  10968. function setValueV1i(gl, v) {
  10969. const cache = this.cache;
  10970. if (cache[0] === v) return;
  10971. gl.uniform1i(this.addr, v);
  10972. cache[0] = v;
  10973. }
  10974. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10975. function setValueV2i(gl, v) {
  10976. const cache = this.cache;
  10977. if (v.x !== undefined) {
  10978. if (cache[0] !== v.x || cache[1] !== v.y) {
  10979. gl.uniform2i(this.addr, v.x, v.y);
  10980. cache[0] = v.x;
  10981. cache[1] = v.y;
  10982. }
  10983. } else {
  10984. if (arraysEqual(cache, v)) return;
  10985. gl.uniform2iv(this.addr, v);
  10986. copyArray(cache, v);
  10987. }
  10988. }
  10989. function setValueV3i(gl, v) {
  10990. const cache = this.cache;
  10991. if (v.x !== undefined) {
  10992. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10993. gl.uniform3i(this.addr, v.x, v.y, v.z);
  10994. cache[0] = v.x;
  10995. cache[1] = v.y;
  10996. cache[2] = v.z;
  10997. }
  10998. } else {
  10999. if (arraysEqual(cache, v)) return;
  11000. gl.uniform3iv(this.addr, v);
  11001. copyArray(cache, v);
  11002. }
  11003. }
  11004. function setValueV4i(gl, v) {
  11005. const cache = this.cache;
  11006. if (v.x !== undefined) {
  11007. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11008. gl.uniform4i(this.addr, v.x, v.y, v.z, v.w);
  11009. cache[0] = v.x;
  11010. cache[1] = v.y;
  11011. cache[2] = v.z;
  11012. cache[3] = v.w;
  11013. }
  11014. } else {
  11015. if (arraysEqual(cache, v)) return;
  11016. gl.uniform4iv(this.addr, v);
  11017. copyArray(cache, v);
  11018. }
  11019. }
  11020. // Single unsigned integer
  11021. function setValueV1ui(gl, v) {
  11022. const cache = this.cache;
  11023. if (cache[0] === v) return;
  11024. gl.uniform1ui(this.addr, v);
  11025. cache[0] = v;
  11026. }
  11027. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11028. function setValueV2ui(gl, v) {
  11029. const cache = this.cache;
  11030. if (v.x !== undefined) {
  11031. if (cache[0] !== v.x || cache[1] !== v.y) {
  11032. gl.uniform2ui(this.addr, v.x, v.y);
  11033. cache[0] = v.x;
  11034. cache[1] = v.y;
  11035. }
  11036. } else {
  11037. if (arraysEqual(cache, v)) return;
  11038. gl.uniform2uiv(this.addr, v);
  11039. copyArray(cache, v);
  11040. }
  11041. }
  11042. function setValueV3ui(gl, v) {
  11043. const cache = this.cache;
  11044. if (v.x !== undefined) {
  11045. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11046. gl.uniform3ui(this.addr, v.x, v.y, v.z);
  11047. cache[0] = v.x;
  11048. cache[1] = v.y;
  11049. cache[2] = v.z;
  11050. }
  11051. } else {
  11052. if (arraysEqual(cache, v)) return;
  11053. gl.uniform3uiv(this.addr, v);
  11054. copyArray(cache, v);
  11055. }
  11056. }
  11057. function setValueV4ui(gl, v) {
  11058. const cache = this.cache;
  11059. if (v.x !== undefined) {
  11060. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11061. gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w);
  11062. cache[0] = v.x;
  11063. cache[1] = v.y;
  11064. cache[2] = v.z;
  11065. cache[3] = v.w;
  11066. }
  11067. } else {
  11068. if (arraysEqual(cache, v)) return;
  11069. gl.uniform4uiv(this.addr, v);
  11070. copyArray(cache, v);
  11071. }
  11072. }
  11073. // Single texture (2D / Cube)
  11074. function setValueT1(gl, v, textures) {
  11075. const cache = this.cache;
  11076. const unit = textures.allocateTextureUnit();
  11077. if (cache[0] !== unit) {
  11078. gl.uniform1i(this.addr, unit);
  11079. cache[0] = unit;
  11080. }
  11081. textures.setTexture2D(v || emptyTexture, unit);
  11082. }
  11083. function setValueT3D1(gl, v, textures) {
  11084. const cache = this.cache;
  11085. const unit = textures.allocateTextureUnit();
  11086. if (cache[0] !== unit) {
  11087. gl.uniform1i(this.addr, unit);
  11088. cache[0] = unit;
  11089. }
  11090. textures.setTexture3D(v || empty3dTexture, unit);
  11091. }
  11092. function setValueT6(gl, v, textures) {
  11093. const cache = this.cache;
  11094. const unit = textures.allocateTextureUnit();
  11095. if (cache[0] !== unit) {
  11096. gl.uniform1i(this.addr, unit);
  11097. cache[0] = unit;
  11098. }
  11099. textures.setTextureCube(v || emptyCubeTexture, unit);
  11100. }
  11101. function setValueT2DArray1(gl, v, textures) {
  11102. const cache = this.cache;
  11103. const unit = textures.allocateTextureUnit();
  11104. if (cache[0] !== unit) {
  11105. gl.uniform1i(this.addr, unit);
  11106. cache[0] = unit;
  11107. }
  11108. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  11109. }
  11110. // Helper to pick the right setter for the singular case
  11111. function getSingularSetter(type) {
  11112. switch (type) {
  11113. case 0x1406:
  11114. return setValueV1f;
  11115. // FLOAT
  11116. case 0x8b50:
  11117. return setValueV2f;
  11118. // _VEC2
  11119. case 0x8b51:
  11120. return setValueV3f;
  11121. // _VEC3
  11122. case 0x8b52:
  11123. return setValueV4f;
  11124. // _VEC4
  11125. case 0x8b5a:
  11126. return setValueM2;
  11127. // _MAT2
  11128. case 0x8b5b:
  11129. return setValueM3;
  11130. // _MAT3
  11131. case 0x8b5c:
  11132. return setValueM4;
  11133. // _MAT4
  11134. case 0x1404:
  11135. case 0x8b56:
  11136. return setValueV1i;
  11137. // INT, BOOL
  11138. case 0x8b53:
  11139. case 0x8b57:
  11140. return setValueV2i;
  11141. // _VEC2
  11142. case 0x8b54:
  11143. case 0x8b58:
  11144. return setValueV3i;
  11145. // _VEC3
  11146. case 0x8b55:
  11147. case 0x8b59:
  11148. return setValueV4i;
  11149. // _VEC4
  11150. case 0x1405:
  11151. return setValueV1ui;
  11152. // UINT
  11153. case 0x8dc6:
  11154. return setValueV2ui;
  11155. // _VEC2
  11156. case 0x8dc7:
  11157. return setValueV3ui;
  11158. // _VEC3
  11159. case 0x8dc8:
  11160. return setValueV4ui;
  11161. // _VEC4
  11162. case 0x8b5e: // SAMPLER_2D
  11163. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11164. case 0x8dca: // INT_SAMPLER_2D
  11165. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11166. case 0x8b62:
  11167. // SAMPLER_2D_SHADOW
  11168. return setValueT1;
  11169. case 0x8b5f: // SAMPLER_3D
  11170. case 0x8dcb: // INT_SAMPLER_3D
  11171. case 0x8dd3:
  11172. // UNSIGNED_INT_SAMPLER_3D
  11173. return setValueT3D1;
  11174. case 0x8b60: // SAMPLER_CUBE
  11175. case 0x8dcc: // INT_SAMPLER_CUBE
  11176. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11177. case 0x8dc5:
  11178. // SAMPLER_CUBE_SHADOW
  11179. return setValueT6;
  11180. case 0x8dc1: // SAMPLER_2D_ARRAY
  11181. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11182. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11183. case 0x8dc4:
  11184. // SAMPLER_2D_ARRAY_SHADOW
  11185. return setValueT2DArray1;
  11186. }
  11187. }
  11188. // Array of scalars
  11189. function setValueV1fArray(gl, v) {
  11190. gl.uniform1fv(this.addr, v);
  11191. }
  11192. // Array of vectors (from flat array or array of THREE.VectorN)
  11193. function setValueV2fArray(gl, v) {
  11194. const data = flatten(v, this.size, 2);
  11195. gl.uniform2fv(this.addr, data);
  11196. }
  11197. function setValueV3fArray(gl, v) {
  11198. const data = flatten(v, this.size, 3);
  11199. gl.uniform3fv(this.addr, data);
  11200. }
  11201. function setValueV4fArray(gl, v) {
  11202. const data = flatten(v, this.size, 4);
  11203. gl.uniform4fv(this.addr, data);
  11204. }
  11205. // Array of matrices (from flat array or array of THREE.MatrixN)
  11206. function setValueM2Array(gl, v) {
  11207. const data = flatten(v, this.size, 4);
  11208. gl.uniformMatrix2fv(this.addr, false, data);
  11209. }
  11210. function setValueM3Array(gl, v) {
  11211. const data = flatten(v, this.size, 9);
  11212. gl.uniformMatrix3fv(this.addr, false, data);
  11213. }
  11214. function setValueM4Array(gl, v) {
  11215. const data = flatten(v, this.size, 16);
  11216. gl.uniformMatrix4fv(this.addr, false, data);
  11217. }
  11218. // Array of integer / boolean
  11219. function setValueV1iArray(gl, v) {
  11220. gl.uniform1iv(this.addr, v);
  11221. }
  11222. // Array of integer / boolean vectors (from flat array)
  11223. function setValueV2iArray(gl, v) {
  11224. gl.uniform2iv(this.addr, v);
  11225. }
  11226. function setValueV3iArray(gl, v) {
  11227. gl.uniform3iv(this.addr, v);
  11228. }
  11229. function setValueV4iArray(gl, v) {
  11230. gl.uniform4iv(this.addr, v);
  11231. }
  11232. // Array of unsigned integer
  11233. function setValueV1uiArray(gl, v) {
  11234. gl.uniform1uiv(this.addr, v);
  11235. }
  11236. // Array of unsigned integer vectors (from flat array)
  11237. function setValueV2uiArray(gl, v) {
  11238. gl.uniform2uiv(this.addr, v);
  11239. }
  11240. function setValueV3uiArray(gl, v) {
  11241. gl.uniform3uiv(this.addr, v);
  11242. }
  11243. function setValueV4uiArray(gl, v) {
  11244. gl.uniform4uiv(this.addr, v);
  11245. }
  11246. // Array of textures (2D / 3D / Cube / 2DArray)
  11247. function setValueT1Array(gl, v, textures) {
  11248. const cache = this.cache;
  11249. const n = v.length;
  11250. const units = allocTexUnits(textures, n);
  11251. if (!arraysEqual(cache, units)) {
  11252. gl.uniform1iv(this.addr, units);
  11253. copyArray(cache, units);
  11254. }
  11255. for (let i = 0; i !== n; ++i) {
  11256. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  11257. }
  11258. }
  11259. function setValueT3DArray(gl, v, textures) {
  11260. const cache = this.cache;
  11261. const n = v.length;
  11262. const units = allocTexUnits(textures, n);
  11263. if (!arraysEqual(cache, units)) {
  11264. gl.uniform1iv(this.addr, units);
  11265. copyArray(cache, units);
  11266. }
  11267. for (let i = 0; i !== n; ++i) {
  11268. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  11269. }
  11270. }
  11271. function setValueT6Array(gl, v, textures) {
  11272. const cache = this.cache;
  11273. const n = v.length;
  11274. const units = allocTexUnits(textures, n);
  11275. if (!arraysEqual(cache, units)) {
  11276. gl.uniform1iv(this.addr, units);
  11277. copyArray(cache, units);
  11278. }
  11279. for (let i = 0; i !== n; ++i) {
  11280. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11281. }
  11282. }
  11283. function setValueT2DArrayArray(gl, v, textures) {
  11284. const cache = this.cache;
  11285. const n = v.length;
  11286. const units = allocTexUnits(textures, n);
  11287. if (!arraysEqual(cache, units)) {
  11288. gl.uniform1iv(this.addr, units);
  11289. copyArray(cache, units);
  11290. }
  11291. for (let i = 0; i !== n; ++i) {
  11292. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11293. }
  11294. }
  11295. // Helper to pick the right setter for a pure (bottom-level) array
  11296. function getPureArraySetter(type) {
  11297. switch (type) {
  11298. case 0x1406:
  11299. return setValueV1fArray;
  11300. // FLOAT
  11301. case 0x8b50:
  11302. return setValueV2fArray;
  11303. // _VEC2
  11304. case 0x8b51:
  11305. return setValueV3fArray;
  11306. // _VEC3
  11307. case 0x8b52:
  11308. return setValueV4fArray;
  11309. // _VEC4
  11310. case 0x8b5a:
  11311. return setValueM2Array;
  11312. // _MAT2
  11313. case 0x8b5b:
  11314. return setValueM3Array;
  11315. // _MAT3
  11316. case 0x8b5c:
  11317. return setValueM4Array;
  11318. // _MAT4
  11319. case 0x1404:
  11320. case 0x8b56:
  11321. return setValueV1iArray;
  11322. // INT, BOOL
  11323. case 0x8b53:
  11324. case 0x8b57:
  11325. return setValueV2iArray;
  11326. // _VEC2
  11327. case 0x8b54:
  11328. case 0x8b58:
  11329. return setValueV3iArray;
  11330. // _VEC3
  11331. case 0x8b55:
  11332. case 0x8b59:
  11333. return setValueV4iArray;
  11334. // _VEC4
  11335. case 0x1405:
  11336. return setValueV1uiArray;
  11337. // UINT
  11338. case 0x8dc6:
  11339. return setValueV2uiArray;
  11340. // _VEC2
  11341. case 0x8dc7:
  11342. return setValueV3uiArray;
  11343. // _VEC3
  11344. case 0x8dc8:
  11345. return setValueV4uiArray;
  11346. // _VEC4
  11347. case 0x8b5e: // SAMPLER_2D
  11348. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11349. case 0x8dca: // INT_SAMPLER_2D
  11350. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11351. case 0x8b62:
  11352. // SAMPLER_2D_SHADOW
  11353. return setValueT1Array;
  11354. case 0x8b5f: // SAMPLER_3D
  11355. case 0x8dcb: // INT_SAMPLER_3D
  11356. case 0x8dd3:
  11357. // UNSIGNED_INT_SAMPLER_3D
  11358. return setValueT3DArray;
  11359. case 0x8b60: // SAMPLER_CUBE
  11360. case 0x8dcc: // INT_SAMPLER_CUBE
  11361. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11362. case 0x8dc5:
  11363. // SAMPLER_CUBE_SHADOW
  11364. return setValueT6Array;
  11365. case 0x8dc1: // SAMPLER_2D_ARRAY
  11366. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11367. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11368. case 0x8dc4:
  11369. // SAMPLER_2D_ARRAY_SHADOW
  11370. return setValueT2DArrayArray;
  11371. }
  11372. }
  11373. // --- Uniform Classes ---
  11374. class SingleUniform {
  11375. constructor(id, activeInfo, addr) {
  11376. this.id = id;
  11377. this.addr = addr;
  11378. this.cache = [];
  11379. this.setValue = getSingularSetter(activeInfo.type);
  11380. // this.path = activeInfo.name; // DEBUG
  11381. }
  11382. }
  11383. class PureArrayUniform {
  11384. constructor(id, activeInfo, addr) {
  11385. this.id = id;
  11386. this.addr = addr;
  11387. this.cache = [];
  11388. this.size = activeInfo.size;
  11389. this.setValue = getPureArraySetter(activeInfo.type);
  11390. // this.path = activeInfo.name; // DEBUG
  11391. }
  11392. }
  11393. class StructuredUniform {
  11394. constructor(id) {
  11395. this.id = id;
  11396. this.seq = [];
  11397. this.map = {};
  11398. }
  11399. setValue(gl, value, textures) {
  11400. const seq = this.seq;
  11401. for (let i = 0, n = seq.length; i !== n; ++i) {
  11402. const u = seq[i];
  11403. u.setValue(gl, value[u.id], textures);
  11404. }
  11405. }
  11406. }
  11407. // --- Top-level ---
  11408. // Parser - builds up the property tree from the path strings
  11409. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11410. // extracts
  11411. // - the identifier (member name or array index)
  11412. // - followed by an optional right bracket (found when array index)
  11413. // - followed by an optional left bracket or dot (type of subscript)
  11414. //
  11415. // Note: These portions can be read in a non-overlapping fashion and
  11416. // allow straightforward parsing of the hierarchy that WebGL encodes
  11417. // in the uniform names.
  11418. function addUniform(container, uniformObject) {
  11419. container.seq.push(uniformObject);
  11420. container.map[uniformObject.id] = uniformObject;
  11421. }
  11422. function parseUniform(activeInfo, addr, container) {
  11423. const path = activeInfo.name,
  11424. pathLength = path.length;
  11425. // reset RegExp object, because of the early exit of a previous run
  11426. RePathPart.lastIndex = 0;
  11427. while (true) {
  11428. const match = RePathPart.exec(path),
  11429. matchEnd = RePathPart.lastIndex;
  11430. let id = match[1];
  11431. const idIsIndex = match[2] === ']',
  11432. subscript = match[3];
  11433. if (idIsIndex) id = id | 0; // convert to integer
  11434. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11435. // bare name or "pure" bottom-level array "[0]" suffix
  11436. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11437. break;
  11438. } else {
  11439. // step into inner node / create it in case it doesn't exist
  11440. const map = container.map;
  11441. let next = map[id];
  11442. if (next === undefined) {
  11443. next = new StructuredUniform(id);
  11444. addUniform(container, next);
  11445. }
  11446. container = next;
  11447. }
  11448. }
  11449. }
  11450. // Root Container
  11451. class WebGLUniforms {
  11452. constructor(gl, program) {
  11453. this.seq = [];
  11454. this.map = {};
  11455. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11456. for (let i = 0; i < n; ++i) {
  11457. const info = gl.getActiveUniform(program, i),
  11458. addr = gl.getUniformLocation(program, info.name);
  11459. parseUniform(info, addr, this);
  11460. }
  11461. }
  11462. setValue(gl, name, value, textures) {
  11463. const u = this.map[name];
  11464. if (u !== undefined) u.setValue(gl, value, textures);
  11465. }
  11466. setOptional(gl, object, name) {
  11467. const v = object[name];
  11468. if (v !== undefined) this.setValue(gl, name, v);
  11469. }
  11470. static upload(gl, seq, values, textures) {
  11471. for (let i = 0, n = seq.length; i !== n; ++i) {
  11472. const u = seq[i],
  11473. v = values[u.id];
  11474. if (v.needsUpdate !== false) {
  11475. // note: always updating when .needsUpdate is undefined
  11476. u.setValue(gl, v.value, textures);
  11477. }
  11478. }
  11479. }
  11480. static seqWithValue(seq, values) {
  11481. const r = [];
  11482. for (let i = 0, n = seq.length; i !== n; ++i) {
  11483. const u = seq[i];
  11484. if (u.id in values) r.push(u);
  11485. }
  11486. return r;
  11487. }
  11488. }
  11489. function WebGLShader(gl, type, string) {
  11490. const shader = gl.createShader(type);
  11491. gl.shaderSource(shader, string);
  11492. gl.compileShader(shader);
  11493. return shader;
  11494. }
  11495. let programIdCount = 0;
  11496. function handleSource(string, errorLine) {
  11497. const lines = string.split('\n');
  11498. const lines2 = [];
  11499. const from = Math.max(errorLine - 6, 0);
  11500. const to = Math.min(errorLine + 6, lines.length);
  11501. for (let i = from; i < to; i++) {
  11502. const line = i + 1;
  11503. lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`);
  11504. }
  11505. return lines2.join('\n');
  11506. }
  11507. function getEncodingComponents(encoding) {
  11508. switch (encoding) {
  11509. case LinearEncoding:
  11510. return ['Linear', '( value )'];
  11511. case sRGBEncoding:
  11512. return ['sRGB', '( value )'];
  11513. default:
  11514. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11515. return ['Linear', '( value )'];
  11516. }
  11517. }
  11518. function getShaderErrors(gl, shader, type) {
  11519. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11520. const errors = gl.getShaderInfoLog(shader).trim();
  11521. if (status && errors === '') return '';
  11522. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11523. if (errorMatches) {
  11524. // --enable-privileged-webgl-extension
  11525. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11526. const errorLine = parseInt(errorMatches[1]);
  11527. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11528. } else {
  11529. return errors;
  11530. }
  11531. }
  11532. function getTexelEncodingFunction(functionName, encoding) {
  11533. const components = getEncodingComponents(encoding);
  11534. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11535. }
  11536. function getToneMappingFunction(functionName, toneMapping) {
  11537. let toneMappingName;
  11538. switch (toneMapping) {
  11539. case LinearToneMapping:
  11540. toneMappingName = 'Linear';
  11541. break;
  11542. case ReinhardToneMapping:
  11543. toneMappingName = 'Reinhard';
  11544. break;
  11545. case CineonToneMapping:
  11546. toneMappingName = 'OptimizedCineon';
  11547. break;
  11548. case ACESFilmicToneMapping:
  11549. toneMappingName = 'ACESFilmic';
  11550. break;
  11551. case CustomToneMapping:
  11552. toneMappingName = 'Custom';
  11553. break;
  11554. default:
  11555. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11556. toneMappingName = 'Linear';
  11557. }
  11558. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11559. }
  11560. function generateExtensions(parameters) {
  11561. const chunks = [parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11562. return chunks.filter(filterEmptyLine).join('\n');
  11563. }
  11564. function generateDefines(defines) {
  11565. const chunks = [];
  11566. for (const name in defines) {
  11567. const value = defines[name];
  11568. if (value === false) continue;
  11569. chunks.push('#define ' + name + ' ' + value);
  11570. }
  11571. return chunks.join('\n');
  11572. }
  11573. function fetchAttributeLocations(gl, program) {
  11574. const attributes = {};
  11575. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11576. for (let i = 0; i < n; i++) {
  11577. const info = gl.getActiveAttrib(program, i);
  11578. const name = info.name;
  11579. let locationSize = 1;
  11580. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11581. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11582. if (info.type === gl.FLOAT_MAT4) locationSize = 4;
  11583. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11584. attributes[name] = {
  11585. type: info.type,
  11586. location: gl.getAttribLocation(program, name),
  11587. locationSize: locationSize
  11588. };
  11589. }
  11590. return attributes;
  11591. }
  11592. function filterEmptyLine(string) {
  11593. return string !== '';
  11594. }
  11595. function replaceLightNums(string, parameters) {
  11596. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11597. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11598. }
  11599. function replaceClippingPlaneNums(string, parameters) {
  11600. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11601. }
  11602. // Resolve Includes
  11603. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11604. function resolveIncludes(string) {
  11605. return string.replace(includePattern, includeReplacer);
  11606. }
  11607. function includeReplacer(match, include) {
  11608. const string = ShaderChunk[include];
  11609. if (string === undefined) {
  11610. throw new Error('Can not resolve #include <' + include + '>');
  11611. }
  11612. return resolveIncludes(string);
  11613. }
  11614. // Unroll Loops
  11615. 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;
  11616. function unrollLoops(string) {
  11617. return string.replace(unrollLoopPattern, loopReplacer);
  11618. }
  11619. function loopReplacer(match, start, end, snippet) {
  11620. let string = '';
  11621. for (let i = parseInt(start); i < parseInt(end); i++) {
  11622. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11623. }
  11624. return string;
  11625. }
  11626. //
  11627. function generatePrecision(parameters) {
  11628. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11629. if (parameters.precision === 'highp') {
  11630. precisionstring += '\n#define HIGH_PRECISION';
  11631. } else if (parameters.precision === 'mediump') {
  11632. precisionstring += '\n#define MEDIUM_PRECISION';
  11633. } else if (parameters.precision === 'lowp') {
  11634. precisionstring += '\n#define LOW_PRECISION';
  11635. }
  11636. return precisionstring;
  11637. }
  11638. function generateShadowMapTypeDefine(parameters) {
  11639. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11640. if (parameters.shadowMapType === PCFShadowMap) {
  11641. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11642. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11643. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11644. } else if (parameters.shadowMapType === VSMShadowMap) {
  11645. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11646. }
  11647. return shadowMapTypeDefine;
  11648. }
  11649. function generateEnvMapTypeDefine(parameters) {
  11650. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11651. if (parameters.envMap) {
  11652. switch (parameters.envMapMode) {
  11653. case CubeReflectionMapping:
  11654. case CubeRefractionMapping:
  11655. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11656. break;
  11657. case CubeUVReflectionMapping:
  11658. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11659. break;
  11660. }
  11661. }
  11662. return envMapTypeDefine;
  11663. }
  11664. function generateEnvMapModeDefine(parameters) {
  11665. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11666. if (parameters.envMap) {
  11667. switch (parameters.envMapMode) {
  11668. case CubeRefractionMapping:
  11669. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11670. break;
  11671. }
  11672. }
  11673. return envMapModeDefine;
  11674. }
  11675. function generateEnvMapBlendingDefine(parameters) {
  11676. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11677. if (parameters.envMap) {
  11678. switch (parameters.combine) {
  11679. case MultiplyOperation:
  11680. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11681. break;
  11682. case MixOperation:
  11683. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11684. break;
  11685. case AddOperation:
  11686. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11687. break;
  11688. }
  11689. }
  11690. return envMapBlendingDefine;
  11691. }
  11692. function generateCubeUVSize(parameters) {
  11693. const imageHeight = parameters.envMapCubeUVHeight;
  11694. if (imageHeight === null) return null;
  11695. const maxMip = Math.log2(imageHeight) - 2;
  11696. const texelHeight = 1.0 / imageHeight;
  11697. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11698. return {
  11699. texelWidth,
  11700. texelHeight,
  11701. maxMip
  11702. };
  11703. }
  11704. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11705. // TODO Send this event to Three.js DevTools
  11706. // console.log( 'WebGLProgram', cacheKey );
  11707. const gl = renderer.getContext();
  11708. const defines = parameters.defines;
  11709. let vertexShader = parameters.vertexShader;
  11710. let fragmentShader = parameters.fragmentShader;
  11711. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11712. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11713. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11714. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11715. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11716. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11717. const customDefines = generateDefines(defines);
  11718. const program = gl.createProgram();
  11719. let prefixVertex, prefixFragment;
  11720. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11721. if (parameters.isRawShaderMaterial) {
  11722. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11723. if (prefixVertex.length > 0) {
  11724. prefixVertex += '\n';
  11725. }
  11726. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11727. if (prefixFragment.length > 0) {
  11728. prefixFragment += '\n';
  11729. }
  11730. } else {
  11731. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphColors && parameters.isWebGL2 ? '#define USE_MORPHCOLORS' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11732. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescence ? '#define USE_IRIDESCENCE' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '',
  11733. // this code is required here because it is used by the toneMapping() function defined below
  11734. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'],
  11735. // this code is required here because it is used by the various encoding/decoding function defined below
  11736. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11737. }
  11738. vertexShader = resolveIncludes(vertexShader);
  11739. vertexShader = replaceLightNums(vertexShader, parameters);
  11740. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11741. fragmentShader = resolveIncludes(fragmentShader);
  11742. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11743. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11744. vertexShader = unrollLoops(vertexShader);
  11745. fragmentShader = unrollLoops(fragmentShader);
  11746. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11747. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11748. versionString = '#version 300 es\n';
  11749. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11750. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11751. }
  11752. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11753. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11754. // console.log( '*VERTEX*', vertexGlsl );
  11755. // console.log( '*FRAGMENT*', fragmentGlsl );
  11756. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11757. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11758. gl.attachShader(program, glVertexShader);
  11759. gl.attachShader(program, glFragmentShader);
  11760. // Force a particular attribute to index 0.
  11761. if (parameters.index0AttributeName !== undefined) {
  11762. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11763. } else if (parameters.morphTargets === true) {
  11764. // programs with morphTargets displace position out of attribute 0
  11765. gl.bindAttribLocation(program, 0, 'position');
  11766. }
  11767. gl.linkProgram(program);
  11768. // check for link errors
  11769. if (renderer.debug.checkShaderErrors) {
  11770. const programLog = gl.getProgramInfoLog(program).trim();
  11771. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11772. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11773. let runnable = true;
  11774. let haveDiagnostics = true;
  11775. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11776. runnable = false;
  11777. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11778. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11779. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11780. } else if (programLog !== '') {
  11781. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11782. } else if (vertexLog === '' || fragmentLog === '') {
  11783. haveDiagnostics = false;
  11784. }
  11785. if (haveDiagnostics) {
  11786. this.diagnostics = {
  11787. runnable: runnable,
  11788. programLog: programLog,
  11789. vertexShader: {
  11790. log: vertexLog,
  11791. prefix: prefixVertex
  11792. },
  11793. fragmentShader: {
  11794. log: fragmentLog,
  11795. prefix: prefixFragment
  11796. }
  11797. };
  11798. }
  11799. }
  11800. // Clean up
  11801. // Crashes in iOS9 and iOS10. #18402
  11802. // gl.detachShader( program, glVertexShader );
  11803. // gl.detachShader( program, glFragmentShader );
  11804. gl.deleteShader(glVertexShader);
  11805. gl.deleteShader(glFragmentShader);
  11806. // set up caching for uniform locations
  11807. let cachedUniforms;
  11808. this.getUniforms = function () {
  11809. if (cachedUniforms === undefined) {
  11810. cachedUniforms = new WebGLUniforms(gl, program);
  11811. }
  11812. return cachedUniforms;
  11813. };
  11814. // set up caching for attribute locations
  11815. let cachedAttributes;
  11816. this.getAttributes = function () {
  11817. if (cachedAttributes === undefined) {
  11818. cachedAttributes = fetchAttributeLocations(gl, program);
  11819. }
  11820. return cachedAttributes;
  11821. };
  11822. // free resource
  11823. this.destroy = function () {
  11824. bindingStates.releaseStatesOfProgram(this);
  11825. gl.deleteProgram(program);
  11826. this.program = undefined;
  11827. };
  11828. //
  11829. this.name = parameters.shaderName;
  11830. this.id = programIdCount++;
  11831. this.cacheKey = cacheKey;
  11832. this.usedTimes = 1;
  11833. this.program = program;
  11834. this.vertexShader = glVertexShader;
  11835. this.fragmentShader = glFragmentShader;
  11836. return this;
  11837. }
  11838. let _id = 0;
  11839. class WebGLShaderCache {
  11840. constructor() {
  11841. this.shaderCache = new Map();
  11842. this.materialCache = new Map();
  11843. }
  11844. update(material) {
  11845. const vertexShader = material.vertexShader;
  11846. const fragmentShader = material.fragmentShader;
  11847. const vertexShaderStage = this._getShaderStage(vertexShader);
  11848. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11849. const materialShaders = this._getShaderCacheForMaterial(material);
  11850. if (materialShaders.has(vertexShaderStage) === false) {
  11851. materialShaders.add(vertexShaderStage);
  11852. vertexShaderStage.usedTimes++;
  11853. }
  11854. if (materialShaders.has(fragmentShaderStage) === false) {
  11855. materialShaders.add(fragmentShaderStage);
  11856. fragmentShaderStage.usedTimes++;
  11857. }
  11858. return this;
  11859. }
  11860. remove(material) {
  11861. const materialShaders = this.materialCache.get(material);
  11862. for (const shaderStage of materialShaders) {
  11863. shaderStage.usedTimes--;
  11864. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11865. }
  11866. this.materialCache.delete(material);
  11867. return this;
  11868. }
  11869. getVertexShaderID(material) {
  11870. return this._getShaderStage(material.vertexShader).id;
  11871. }
  11872. getFragmentShaderID(material) {
  11873. return this._getShaderStage(material.fragmentShader).id;
  11874. }
  11875. dispose() {
  11876. this.shaderCache.clear();
  11877. this.materialCache.clear();
  11878. }
  11879. _getShaderCacheForMaterial(material) {
  11880. const cache = this.materialCache;
  11881. let set = cache.get(material);
  11882. if (set === undefined) {
  11883. set = new Set();
  11884. cache.set(material, set);
  11885. }
  11886. return set;
  11887. }
  11888. _getShaderStage(code) {
  11889. const cache = this.shaderCache;
  11890. let stage = cache.get(code);
  11891. if (stage === undefined) {
  11892. stage = new WebGLShaderStage(code);
  11893. cache.set(code, stage);
  11894. }
  11895. return stage;
  11896. }
  11897. }
  11898. class WebGLShaderStage {
  11899. constructor(code) {
  11900. this.id = _id++;
  11901. this.code = code;
  11902. this.usedTimes = 0;
  11903. }
  11904. }
  11905. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11906. const _programLayers = new Layers();
  11907. const _customShaders = new WebGLShaderCache();
  11908. const programs = [];
  11909. const isWebGL2 = capabilities.isWebGL2;
  11910. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11911. const vertexTextures = capabilities.vertexTextures;
  11912. let precision = capabilities.precision;
  11913. const shaderIDs = {
  11914. MeshDepthMaterial: 'depth',
  11915. MeshDistanceMaterial: 'distanceRGBA',
  11916. MeshNormalMaterial: 'normal',
  11917. MeshBasicMaterial: 'basic',
  11918. MeshLambertMaterial: 'lambert',
  11919. MeshPhongMaterial: 'phong',
  11920. MeshToonMaterial: 'toon',
  11921. MeshStandardMaterial: 'physical',
  11922. MeshPhysicalMaterial: 'physical',
  11923. MeshMatcapMaterial: 'matcap',
  11924. LineBasicMaterial: 'basic',
  11925. LineDashedMaterial: 'dashed',
  11926. PointsMaterial: 'points',
  11927. ShadowMaterial: 'shadow',
  11928. SpriteMaterial: 'sprite'
  11929. };
  11930. function getParameters(material, lights, shadows, scene, object) {
  11931. const fog = scene.fog;
  11932. const geometry = object.geometry;
  11933. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11934. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11935. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11936. const shaderID = shaderIDs[material.type];
  11937. // heuristics to create shader parameters according to lights in the scene
  11938. // (not to blow over maxLights budget)
  11939. if (material.precision !== null) {
  11940. precision = capabilities.getMaxPrecision(material.precision);
  11941. if (precision !== material.precision) {
  11942. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11943. }
  11944. }
  11945. //
  11946. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11947. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11948. let morphTextureStride = 0;
  11949. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11950. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11951. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3;
  11952. //
  11953. let vertexShader, fragmentShader;
  11954. let customVertexShaderID, customFragmentShaderID;
  11955. if (shaderID) {
  11956. const shader = ShaderLib[shaderID];
  11957. vertexShader = shader.vertexShader;
  11958. fragmentShader = shader.fragmentShader;
  11959. } else {
  11960. vertexShader = material.vertexShader;
  11961. fragmentShader = material.fragmentShader;
  11962. _customShaders.update(material);
  11963. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11964. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11965. }
  11966. const currentRenderTarget = renderer.getRenderTarget();
  11967. const useAlphaTest = material.alphaTest > 0;
  11968. const useClearcoat = material.clearcoat > 0;
  11969. const useIridescence = material.iridescence > 0;
  11970. const parameters = {
  11971. isWebGL2: isWebGL2,
  11972. shaderID: shaderID,
  11973. shaderName: material.type,
  11974. vertexShader: vertexShader,
  11975. fragmentShader: fragmentShader,
  11976. defines: material.defines,
  11977. customVertexShaderID: customVertexShaderID,
  11978. customFragmentShaderID: customFragmentShaderID,
  11979. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11980. glslVersion: material.glslVersion,
  11981. precision: precision,
  11982. instancing: object.isInstancedMesh === true,
  11983. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11984. supportsVertexTextures: vertexTextures,
  11985. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11986. map: !!material.map,
  11987. matcap: !!material.matcap,
  11988. envMap: !!envMap,
  11989. envMapMode: envMap && envMap.mapping,
  11990. envMapCubeUVHeight: envMapCubeUVHeight,
  11991. lightMap: !!material.lightMap,
  11992. aoMap: !!material.aoMap,
  11993. emissiveMap: !!material.emissiveMap,
  11994. bumpMap: !!material.bumpMap,
  11995. normalMap: !!material.normalMap,
  11996. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11997. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11998. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  11999. clearcoat: useClearcoat,
  12000. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  12001. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  12002. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  12003. iridescence: useIridescence,
  12004. iridescenceMap: useIridescence && !!material.iridescenceMap,
  12005. iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap,
  12006. displacementMap: !!material.displacementMap,
  12007. roughnessMap: !!material.roughnessMap,
  12008. metalnessMap: !!material.metalnessMap,
  12009. specularMap: !!material.specularMap,
  12010. specularIntensityMap: !!material.specularIntensityMap,
  12011. specularColorMap: !!material.specularColorMap,
  12012. opaque: material.transparent === false && material.blending === NormalBlending,
  12013. alphaMap: !!material.alphaMap,
  12014. alphaTest: useAlphaTest,
  12015. gradientMap: !!material.gradientMap,
  12016. sheen: material.sheen > 0,
  12017. sheenColorMap: !!material.sheenColorMap,
  12018. sheenRoughnessMap: !!material.sheenRoughnessMap,
  12019. transmission: material.transmission > 0,
  12020. transmissionMap: !!material.transmissionMap,
  12021. thicknessMap: !!material.thicknessMap,
  12022. combine: material.combine,
  12023. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  12024. vertexColors: material.vertexColors,
  12025. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12026. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  12027. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  12028. fog: !!fog,
  12029. useFog: material.fog === true,
  12030. fogExp2: fog && fog.isFogExp2,
  12031. flatShading: !!material.flatShading,
  12032. sizeAttenuation: material.sizeAttenuation,
  12033. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12034. skinning: object.isSkinnedMesh === true,
  12035. morphTargets: geometry.morphAttributes.position !== undefined,
  12036. morphNormals: geometry.morphAttributes.normal !== undefined,
  12037. morphColors: geometry.morphAttributes.color !== undefined,
  12038. morphTargetsCount: morphTargetsCount,
  12039. morphTextureStride: morphTextureStride,
  12040. numDirLights: lights.directional.length,
  12041. numPointLights: lights.point.length,
  12042. numSpotLights: lights.spot.length,
  12043. numSpotLightMaps: lights.spotLightMap.length,
  12044. numRectAreaLights: lights.rectArea.length,
  12045. numHemiLights: lights.hemi.length,
  12046. numDirLightShadows: lights.directionalShadowMap.length,
  12047. numPointLightShadows: lights.pointShadowMap.length,
  12048. numSpotLightShadows: lights.spotShadowMap.length,
  12049. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12050. numClippingPlanes: clipping.numPlanes,
  12051. numClipIntersection: clipping.numIntersection,
  12052. dithering: material.dithering,
  12053. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12054. shadowMapType: renderer.shadowMap.type,
  12055. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12056. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12057. premultipliedAlpha: material.premultipliedAlpha,
  12058. doubleSided: material.side === DoubleSide,
  12059. flipSided: material.side === BackSide,
  12060. useDepthPacking: !!material.depthPacking,
  12061. depthPacking: material.depthPacking || 0,
  12062. index0AttributeName: material.index0AttributeName,
  12063. extensionDerivatives: material.extensions && material.extensions.derivatives,
  12064. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  12065. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  12066. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  12067. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  12068. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  12069. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  12070. customProgramCacheKey: material.customProgramCacheKey()
  12071. };
  12072. return parameters;
  12073. }
  12074. function getProgramCacheKey(parameters) {
  12075. const array = [];
  12076. if (parameters.shaderID) {
  12077. array.push(parameters.shaderID);
  12078. } else {
  12079. array.push(parameters.customVertexShaderID);
  12080. array.push(parameters.customFragmentShaderID);
  12081. }
  12082. if (parameters.defines !== undefined) {
  12083. for (const name in parameters.defines) {
  12084. array.push(name);
  12085. array.push(parameters.defines[name]);
  12086. }
  12087. }
  12088. if (parameters.isRawShaderMaterial === false) {
  12089. getProgramCacheKeyParameters(array, parameters);
  12090. getProgramCacheKeyBooleans(array, parameters);
  12091. array.push(renderer.outputEncoding);
  12092. }
  12093. array.push(parameters.customProgramCacheKey);
  12094. return array.join();
  12095. }
  12096. function getProgramCacheKeyParameters(array, parameters) {
  12097. array.push(parameters.precision);
  12098. array.push(parameters.outputEncoding);
  12099. array.push(parameters.envMapMode);
  12100. array.push(parameters.envMapCubeUVHeight);
  12101. array.push(parameters.combine);
  12102. array.push(parameters.vertexUvs);
  12103. array.push(parameters.fogExp2);
  12104. array.push(parameters.sizeAttenuation);
  12105. array.push(parameters.morphTargetsCount);
  12106. array.push(parameters.morphAttributeCount);
  12107. array.push(parameters.numDirLights);
  12108. array.push(parameters.numPointLights);
  12109. array.push(parameters.numSpotLights);
  12110. array.push(parameters.numSpotLightMaps);
  12111. array.push(parameters.numHemiLights);
  12112. array.push(parameters.numRectAreaLights);
  12113. array.push(parameters.numDirLightShadows);
  12114. array.push(parameters.numPointLightShadows);
  12115. array.push(parameters.numSpotLightShadows);
  12116. array.push(parameters.numSpotLightShadowsWithMaps);
  12117. array.push(parameters.shadowMapType);
  12118. array.push(parameters.toneMapping);
  12119. array.push(parameters.numClippingPlanes);
  12120. array.push(parameters.numClipIntersection);
  12121. array.push(parameters.depthPacking);
  12122. }
  12123. function getProgramCacheKeyBooleans(array, parameters) {
  12124. _programLayers.disableAll();
  12125. if (parameters.isWebGL2) _programLayers.enable(0);
  12126. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  12127. if (parameters.instancing) _programLayers.enable(2);
  12128. if (parameters.instancingColor) _programLayers.enable(3);
  12129. if (parameters.map) _programLayers.enable(4);
  12130. if (parameters.matcap) _programLayers.enable(5);
  12131. if (parameters.envMap) _programLayers.enable(6);
  12132. if (parameters.lightMap) _programLayers.enable(7);
  12133. if (parameters.aoMap) _programLayers.enable(8);
  12134. if (parameters.emissiveMap) _programLayers.enable(9);
  12135. if (parameters.bumpMap) _programLayers.enable(10);
  12136. if (parameters.normalMap) _programLayers.enable(11);
  12137. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  12138. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  12139. if (parameters.clearcoat) _programLayers.enable(14);
  12140. if (parameters.clearcoatMap) _programLayers.enable(15);
  12141. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  12142. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  12143. if (parameters.iridescence) _programLayers.enable(18);
  12144. if (parameters.iridescenceMap) _programLayers.enable(19);
  12145. if (parameters.iridescenceThicknessMap) _programLayers.enable(20);
  12146. if (parameters.displacementMap) _programLayers.enable(21);
  12147. if (parameters.specularMap) _programLayers.enable(22);
  12148. if (parameters.roughnessMap) _programLayers.enable(23);
  12149. if (parameters.metalnessMap) _programLayers.enable(24);
  12150. if (parameters.gradientMap) _programLayers.enable(25);
  12151. if (parameters.alphaMap) _programLayers.enable(26);
  12152. if (parameters.alphaTest) _programLayers.enable(27);
  12153. if (parameters.vertexColors) _programLayers.enable(28);
  12154. if (parameters.vertexAlphas) _programLayers.enable(29);
  12155. if (parameters.vertexUvs) _programLayers.enable(30);
  12156. if (parameters.vertexTangents) _programLayers.enable(31);
  12157. if (parameters.uvsVertexOnly) _programLayers.enable(32);
  12158. array.push(_programLayers.mask);
  12159. _programLayers.disableAll();
  12160. if (parameters.fog) _programLayers.enable(0);
  12161. if (parameters.useFog) _programLayers.enable(1);
  12162. if (parameters.flatShading) _programLayers.enable(2);
  12163. if (parameters.logarithmicDepthBuffer) _programLayers.enable(3);
  12164. if (parameters.skinning) _programLayers.enable(4);
  12165. if (parameters.morphTargets) _programLayers.enable(5);
  12166. if (parameters.morphNormals) _programLayers.enable(6);
  12167. if (parameters.morphColors) _programLayers.enable(7);
  12168. if (parameters.premultipliedAlpha) _programLayers.enable(8);
  12169. if (parameters.shadowMapEnabled) _programLayers.enable(9);
  12170. if (parameters.physicallyCorrectLights) _programLayers.enable(10);
  12171. if (parameters.doubleSided) _programLayers.enable(11);
  12172. if (parameters.flipSided) _programLayers.enable(12);
  12173. if (parameters.useDepthPacking) _programLayers.enable(13);
  12174. if (parameters.dithering) _programLayers.enable(14);
  12175. if (parameters.specularIntensityMap) _programLayers.enable(15);
  12176. if (parameters.specularColorMap) _programLayers.enable(16);
  12177. if (parameters.transmission) _programLayers.enable(17);
  12178. if (parameters.transmissionMap) _programLayers.enable(18);
  12179. if (parameters.thicknessMap) _programLayers.enable(19);
  12180. if (parameters.sheen) _programLayers.enable(20);
  12181. if (parameters.sheenColorMap) _programLayers.enable(21);
  12182. if (parameters.sheenRoughnessMap) _programLayers.enable(22);
  12183. if (parameters.decodeVideoTexture) _programLayers.enable(23);
  12184. if (parameters.opaque) _programLayers.enable(24);
  12185. array.push(_programLayers.mask);
  12186. }
  12187. function getUniforms(material) {
  12188. const shaderID = shaderIDs[material.type];
  12189. let uniforms;
  12190. if (shaderID) {
  12191. const shader = ShaderLib[shaderID];
  12192. uniforms = UniformsUtils.clone(shader.uniforms);
  12193. } else {
  12194. uniforms = material.uniforms;
  12195. }
  12196. return uniforms;
  12197. }
  12198. function acquireProgram(parameters, cacheKey) {
  12199. let program;
  12200. // Check if code has been already compiled
  12201. for (let p = 0, pl = programs.length; p < pl; p++) {
  12202. const preexistingProgram = programs[p];
  12203. if (preexistingProgram.cacheKey === cacheKey) {
  12204. program = preexistingProgram;
  12205. ++program.usedTimes;
  12206. break;
  12207. }
  12208. }
  12209. if (program === undefined) {
  12210. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  12211. programs.push(program);
  12212. }
  12213. return program;
  12214. }
  12215. function releaseProgram(program) {
  12216. if (--program.usedTimes === 0) {
  12217. // Remove from unordered set
  12218. const i = programs.indexOf(program);
  12219. programs[i] = programs[programs.length - 1];
  12220. programs.pop();
  12221. // Free WebGL resources
  12222. program.destroy();
  12223. }
  12224. }
  12225. function releaseShaderCache(material) {
  12226. _customShaders.remove(material);
  12227. }
  12228. function dispose() {
  12229. _customShaders.dispose();
  12230. }
  12231. return {
  12232. getParameters: getParameters,
  12233. getProgramCacheKey: getProgramCacheKey,
  12234. getUniforms: getUniforms,
  12235. acquireProgram: acquireProgram,
  12236. releaseProgram: releaseProgram,
  12237. releaseShaderCache: releaseShaderCache,
  12238. // Exposed for resource monitoring & error feedback via renderer.info:
  12239. programs: programs,
  12240. dispose: dispose
  12241. };
  12242. }
  12243. function WebGLProperties() {
  12244. let properties = new WeakMap();
  12245. function get(object) {
  12246. let map = properties.get(object);
  12247. if (map === undefined) {
  12248. map = {};
  12249. properties.set(object, map);
  12250. }
  12251. return map;
  12252. }
  12253. function remove(object) {
  12254. properties.delete(object);
  12255. }
  12256. function update(object, key, value) {
  12257. properties.get(object)[key] = value;
  12258. }
  12259. function dispose() {
  12260. properties = new WeakMap();
  12261. }
  12262. return {
  12263. get: get,
  12264. remove: remove,
  12265. update: update,
  12266. dispose: dispose
  12267. };
  12268. }
  12269. function painterSortStable(a, b) {
  12270. if (a.groupOrder !== b.groupOrder) {
  12271. return a.groupOrder - b.groupOrder;
  12272. } else if (a.renderOrder !== b.renderOrder) {
  12273. return a.renderOrder - b.renderOrder;
  12274. } else if (a.material.id !== b.material.id) {
  12275. return a.material.id - b.material.id;
  12276. } else if (a.z !== b.z) {
  12277. return a.z - b.z;
  12278. } else {
  12279. return a.id - b.id;
  12280. }
  12281. }
  12282. function reversePainterSortStable(a, b) {
  12283. if (a.groupOrder !== b.groupOrder) {
  12284. return a.groupOrder - b.groupOrder;
  12285. } else if (a.renderOrder !== b.renderOrder) {
  12286. return a.renderOrder - b.renderOrder;
  12287. } else if (a.z !== b.z) {
  12288. return b.z - a.z;
  12289. } else {
  12290. return a.id - b.id;
  12291. }
  12292. }
  12293. function WebGLRenderList() {
  12294. const renderItems = [];
  12295. let renderItemsIndex = 0;
  12296. const opaque = [];
  12297. const transmissive = [];
  12298. const transparent = [];
  12299. function init() {
  12300. renderItemsIndex = 0;
  12301. opaque.length = 0;
  12302. transmissive.length = 0;
  12303. transparent.length = 0;
  12304. }
  12305. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12306. let renderItem = renderItems[renderItemsIndex];
  12307. if (renderItem === undefined) {
  12308. renderItem = {
  12309. id: object.id,
  12310. object: object,
  12311. geometry: geometry,
  12312. material: material,
  12313. groupOrder: groupOrder,
  12314. renderOrder: object.renderOrder,
  12315. z: z,
  12316. group: group
  12317. };
  12318. renderItems[renderItemsIndex] = renderItem;
  12319. } else {
  12320. renderItem.id = object.id;
  12321. renderItem.object = object;
  12322. renderItem.geometry = geometry;
  12323. renderItem.material = material;
  12324. renderItem.groupOrder = groupOrder;
  12325. renderItem.renderOrder = object.renderOrder;
  12326. renderItem.z = z;
  12327. renderItem.group = group;
  12328. }
  12329. renderItemsIndex++;
  12330. return renderItem;
  12331. }
  12332. function push(object, geometry, material, groupOrder, z, group) {
  12333. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12334. if (material.transmission > 0.0) {
  12335. transmissive.push(renderItem);
  12336. } else if (material.transparent === true) {
  12337. transparent.push(renderItem);
  12338. } else {
  12339. opaque.push(renderItem);
  12340. }
  12341. }
  12342. function unshift(object, geometry, material, groupOrder, z, group) {
  12343. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12344. if (material.transmission > 0.0) {
  12345. transmissive.unshift(renderItem);
  12346. } else if (material.transparent === true) {
  12347. transparent.unshift(renderItem);
  12348. } else {
  12349. opaque.unshift(renderItem);
  12350. }
  12351. }
  12352. function sort(customOpaqueSort, customTransparentSort) {
  12353. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12354. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12355. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12356. }
  12357. function finish() {
  12358. // Clear references from inactive renderItems in the list
  12359. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12360. const renderItem = renderItems[i];
  12361. if (renderItem.id === null) break;
  12362. renderItem.id = null;
  12363. renderItem.object = null;
  12364. renderItem.geometry = null;
  12365. renderItem.material = null;
  12366. renderItem.group = null;
  12367. }
  12368. }
  12369. return {
  12370. opaque: opaque,
  12371. transmissive: transmissive,
  12372. transparent: transparent,
  12373. init: init,
  12374. push: push,
  12375. unshift: unshift,
  12376. finish: finish,
  12377. sort: sort
  12378. };
  12379. }
  12380. function WebGLRenderLists() {
  12381. let lists = new WeakMap();
  12382. function get(scene, renderCallDepth) {
  12383. const listArray = lists.get(scene);
  12384. let list;
  12385. if (listArray === undefined) {
  12386. list = new WebGLRenderList();
  12387. lists.set(scene, [list]);
  12388. } else {
  12389. if (renderCallDepth >= listArray.length) {
  12390. list = new WebGLRenderList();
  12391. listArray.push(list);
  12392. } else {
  12393. list = listArray[renderCallDepth];
  12394. }
  12395. }
  12396. return list;
  12397. }
  12398. function dispose() {
  12399. lists = new WeakMap();
  12400. }
  12401. return {
  12402. get: get,
  12403. dispose: dispose
  12404. };
  12405. }
  12406. function UniformsCache() {
  12407. const lights = {};
  12408. return {
  12409. get: function (light) {
  12410. if (lights[light.id] !== undefined) {
  12411. return lights[light.id];
  12412. }
  12413. let uniforms;
  12414. switch (light.type) {
  12415. case 'DirectionalLight':
  12416. uniforms = {
  12417. direction: new Vector3(),
  12418. color: new Color()
  12419. };
  12420. break;
  12421. case 'SpotLight':
  12422. uniforms = {
  12423. position: new Vector3(),
  12424. direction: new Vector3(),
  12425. color: new Color(),
  12426. distance: 0,
  12427. coneCos: 0,
  12428. penumbraCos: 0,
  12429. decay: 0
  12430. };
  12431. break;
  12432. case 'PointLight':
  12433. uniforms = {
  12434. position: new Vector3(),
  12435. color: new Color(),
  12436. distance: 0,
  12437. decay: 0
  12438. };
  12439. break;
  12440. case 'HemisphereLight':
  12441. uniforms = {
  12442. direction: new Vector3(),
  12443. skyColor: new Color(),
  12444. groundColor: new Color()
  12445. };
  12446. break;
  12447. case 'RectAreaLight':
  12448. uniforms = {
  12449. color: new Color(),
  12450. position: new Vector3(),
  12451. halfWidth: new Vector3(),
  12452. halfHeight: new Vector3()
  12453. };
  12454. break;
  12455. }
  12456. lights[light.id] = uniforms;
  12457. return uniforms;
  12458. }
  12459. };
  12460. }
  12461. function ShadowUniformsCache() {
  12462. const lights = {};
  12463. return {
  12464. get: function (light) {
  12465. if (lights[light.id] !== undefined) {
  12466. return lights[light.id];
  12467. }
  12468. let uniforms;
  12469. switch (light.type) {
  12470. case 'DirectionalLight':
  12471. uniforms = {
  12472. shadowBias: 0,
  12473. shadowNormalBias: 0,
  12474. shadowRadius: 1,
  12475. shadowMapSize: new Vector2()
  12476. };
  12477. break;
  12478. case 'SpotLight':
  12479. uniforms = {
  12480. shadowBias: 0,
  12481. shadowNormalBias: 0,
  12482. shadowRadius: 1,
  12483. shadowMapSize: new Vector2()
  12484. };
  12485. break;
  12486. case 'PointLight':
  12487. uniforms = {
  12488. shadowBias: 0,
  12489. shadowNormalBias: 0,
  12490. shadowRadius: 1,
  12491. shadowMapSize: new Vector2(),
  12492. shadowCameraNear: 1,
  12493. shadowCameraFar: 1000
  12494. };
  12495. break;
  12496. // TODO (abelnation): set RectAreaLight shadow uniforms
  12497. }
  12498. lights[light.id] = uniforms;
  12499. return uniforms;
  12500. }
  12501. };
  12502. }
  12503. let nextVersion = 0;
  12504. function shadowCastingAndTexturingLightsFirst(lightA, lightB) {
  12505. return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0);
  12506. }
  12507. function WebGLLights(extensions, capabilities) {
  12508. const cache = new UniformsCache();
  12509. const shadowCache = ShadowUniformsCache();
  12510. const state = {
  12511. version: 0,
  12512. hash: {
  12513. directionalLength: -1,
  12514. pointLength: -1,
  12515. spotLength: -1,
  12516. rectAreaLength: -1,
  12517. hemiLength: -1,
  12518. numDirectionalShadows: -1,
  12519. numPointShadows: -1,
  12520. numSpotShadows: -1,
  12521. numSpotMaps: -1
  12522. },
  12523. ambient: [0, 0, 0],
  12524. probe: [],
  12525. directional: [],
  12526. directionalShadow: [],
  12527. directionalShadowMap: [],
  12528. directionalShadowMatrix: [],
  12529. spot: [],
  12530. spotLightMap: [],
  12531. spotShadow: [],
  12532. spotShadowMap: [],
  12533. spotLightMatrix: [],
  12534. rectArea: [],
  12535. rectAreaLTC1: null,
  12536. rectAreaLTC2: null,
  12537. point: [],
  12538. pointShadow: [],
  12539. pointShadowMap: [],
  12540. pointShadowMatrix: [],
  12541. hemi: [],
  12542. numSpotLightShadowsWithMaps: 0
  12543. };
  12544. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12545. const vector3 = new Vector3();
  12546. const matrix4 = new Matrix4();
  12547. const matrix42 = new Matrix4();
  12548. function setup(lights, physicallyCorrectLights) {
  12549. let r = 0,
  12550. g = 0,
  12551. b = 0;
  12552. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12553. let directionalLength = 0;
  12554. let pointLength = 0;
  12555. let spotLength = 0;
  12556. let rectAreaLength = 0;
  12557. let hemiLength = 0;
  12558. let numDirectionalShadows = 0;
  12559. let numPointShadows = 0;
  12560. let numSpotShadows = 0;
  12561. let numSpotMaps = 0;
  12562. let numSpotShadowsWithMaps = 0;
  12563. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12564. lights.sort(shadowCastingAndTexturingLightsFirst);
  12565. // artist-friendly light intensity scaling factor
  12566. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12567. for (let i = 0, l = lights.length; i < l; i++) {
  12568. const light = lights[i];
  12569. const color = light.color;
  12570. const intensity = light.intensity;
  12571. const distance = light.distance;
  12572. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12573. if (light.isAmbientLight) {
  12574. r += color.r * intensity * scaleFactor;
  12575. g += color.g * intensity * scaleFactor;
  12576. b += color.b * intensity * scaleFactor;
  12577. } else if (light.isLightProbe) {
  12578. for (let j = 0; j < 9; j++) {
  12579. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12580. }
  12581. } else if (light.isDirectionalLight) {
  12582. const uniforms = cache.get(light);
  12583. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12584. if (light.castShadow) {
  12585. const shadow = light.shadow;
  12586. const shadowUniforms = shadowCache.get(light);
  12587. shadowUniforms.shadowBias = shadow.bias;
  12588. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12589. shadowUniforms.shadowRadius = shadow.radius;
  12590. shadowUniforms.shadowMapSize = shadow.mapSize;
  12591. state.directionalShadow[directionalLength] = shadowUniforms;
  12592. state.directionalShadowMap[directionalLength] = shadowMap;
  12593. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12594. numDirectionalShadows++;
  12595. }
  12596. state.directional[directionalLength] = uniforms;
  12597. directionalLength++;
  12598. } else if (light.isSpotLight) {
  12599. const uniforms = cache.get(light);
  12600. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12601. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12602. uniforms.distance = distance;
  12603. uniforms.coneCos = Math.cos(light.angle);
  12604. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12605. uniforms.decay = light.decay;
  12606. state.spot[spotLength] = uniforms;
  12607. const shadow = light.shadow;
  12608. if (light.map) {
  12609. state.spotLightMap[numSpotMaps] = light.map;
  12610. numSpotMaps++;
  12611. // make sure the lightMatrix is up to date
  12612. // TODO : do it if required only
  12613. shadow.updateMatrices(light);
  12614. if (light.castShadow) numSpotShadowsWithMaps++;
  12615. }
  12616. state.spotLightMatrix[spotLength] = shadow.matrix;
  12617. if (light.castShadow) {
  12618. const shadowUniforms = shadowCache.get(light);
  12619. shadowUniforms.shadowBias = shadow.bias;
  12620. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12621. shadowUniforms.shadowRadius = shadow.radius;
  12622. shadowUniforms.shadowMapSize = shadow.mapSize;
  12623. state.spotShadow[spotLength] = shadowUniforms;
  12624. state.spotShadowMap[spotLength] = shadowMap;
  12625. numSpotShadows++;
  12626. }
  12627. spotLength++;
  12628. } else if (light.isRectAreaLight) {
  12629. const uniforms = cache.get(light);
  12630. uniforms.color.copy(color).multiplyScalar(intensity);
  12631. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12632. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12633. state.rectArea[rectAreaLength] = uniforms;
  12634. rectAreaLength++;
  12635. } else if (light.isPointLight) {
  12636. const uniforms = cache.get(light);
  12637. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12638. uniforms.distance = light.distance;
  12639. uniforms.decay = light.decay;
  12640. if (light.castShadow) {
  12641. const shadow = light.shadow;
  12642. const shadowUniforms = shadowCache.get(light);
  12643. shadowUniforms.shadowBias = shadow.bias;
  12644. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12645. shadowUniforms.shadowRadius = shadow.radius;
  12646. shadowUniforms.shadowMapSize = shadow.mapSize;
  12647. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12648. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12649. state.pointShadow[pointLength] = shadowUniforms;
  12650. state.pointShadowMap[pointLength] = shadowMap;
  12651. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12652. numPointShadows++;
  12653. }
  12654. state.point[pointLength] = uniforms;
  12655. pointLength++;
  12656. } else if (light.isHemisphereLight) {
  12657. const uniforms = cache.get(light);
  12658. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12659. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12660. state.hemi[hemiLength] = uniforms;
  12661. hemiLength++;
  12662. }
  12663. }
  12664. if (rectAreaLength > 0) {
  12665. if (capabilities.isWebGL2) {
  12666. // WebGL 2
  12667. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12668. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12669. } else {
  12670. // WebGL 1
  12671. if (extensions.has('OES_texture_float_linear') === true) {
  12672. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12673. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12674. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12675. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12676. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12677. } else {
  12678. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12679. }
  12680. }
  12681. }
  12682. state.ambient[0] = r;
  12683. state.ambient[1] = g;
  12684. state.ambient[2] = b;
  12685. const hash = state.hash;
  12686. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps) {
  12687. state.directional.length = directionalLength;
  12688. state.spot.length = spotLength;
  12689. state.rectArea.length = rectAreaLength;
  12690. state.point.length = pointLength;
  12691. state.hemi.length = hemiLength;
  12692. state.directionalShadow.length = numDirectionalShadows;
  12693. state.directionalShadowMap.length = numDirectionalShadows;
  12694. state.pointShadow.length = numPointShadows;
  12695. state.pointShadowMap.length = numPointShadows;
  12696. state.spotShadow.length = numSpotShadows;
  12697. state.spotShadowMap.length = numSpotShadows;
  12698. state.directionalShadowMatrix.length = numDirectionalShadows;
  12699. state.pointShadowMatrix.length = numPointShadows;
  12700. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12701. state.spotLightMap.length = numSpotMaps;
  12702. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12703. hash.directionalLength = directionalLength;
  12704. hash.pointLength = pointLength;
  12705. hash.spotLength = spotLength;
  12706. hash.rectAreaLength = rectAreaLength;
  12707. hash.hemiLength = hemiLength;
  12708. hash.numDirectionalShadows = numDirectionalShadows;
  12709. hash.numPointShadows = numPointShadows;
  12710. hash.numSpotShadows = numSpotShadows;
  12711. hash.numSpotMaps = numSpotMaps;
  12712. state.version = nextVersion++;
  12713. }
  12714. }
  12715. function setupView(lights, camera) {
  12716. let directionalLength = 0;
  12717. let pointLength = 0;
  12718. let spotLength = 0;
  12719. let rectAreaLength = 0;
  12720. let hemiLength = 0;
  12721. const viewMatrix = camera.matrixWorldInverse;
  12722. for (let i = 0, l = lights.length; i < l; i++) {
  12723. const light = lights[i];
  12724. if (light.isDirectionalLight) {
  12725. const uniforms = state.directional[directionalLength];
  12726. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12727. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12728. uniforms.direction.sub(vector3);
  12729. uniforms.direction.transformDirection(viewMatrix);
  12730. directionalLength++;
  12731. } else if (light.isSpotLight) {
  12732. const uniforms = state.spot[spotLength];
  12733. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12734. uniforms.position.applyMatrix4(viewMatrix);
  12735. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12736. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12737. uniforms.direction.sub(vector3);
  12738. uniforms.direction.transformDirection(viewMatrix);
  12739. spotLength++;
  12740. } else if (light.isRectAreaLight) {
  12741. const uniforms = state.rectArea[rectAreaLength];
  12742. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12743. uniforms.position.applyMatrix4(viewMatrix);
  12744. // extract local rotation of light to derive width/height half vectors
  12745. matrix42.identity();
  12746. matrix4.copy(light.matrixWorld);
  12747. matrix4.premultiply(viewMatrix);
  12748. matrix42.extractRotation(matrix4);
  12749. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12750. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12751. uniforms.halfWidth.applyMatrix4(matrix42);
  12752. uniforms.halfHeight.applyMatrix4(matrix42);
  12753. rectAreaLength++;
  12754. } else if (light.isPointLight) {
  12755. const uniforms = state.point[pointLength];
  12756. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12757. uniforms.position.applyMatrix4(viewMatrix);
  12758. pointLength++;
  12759. } else if (light.isHemisphereLight) {
  12760. const uniforms = state.hemi[hemiLength];
  12761. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12762. uniforms.direction.transformDirection(viewMatrix);
  12763. hemiLength++;
  12764. }
  12765. }
  12766. }
  12767. return {
  12768. setup: setup,
  12769. setupView: setupView,
  12770. state: state
  12771. };
  12772. }
  12773. function WebGLRenderState(extensions, capabilities) {
  12774. const lights = new WebGLLights(extensions, capabilities);
  12775. const lightsArray = [];
  12776. const shadowsArray = [];
  12777. function init() {
  12778. lightsArray.length = 0;
  12779. shadowsArray.length = 0;
  12780. }
  12781. function pushLight(light) {
  12782. lightsArray.push(light);
  12783. }
  12784. function pushShadow(shadowLight) {
  12785. shadowsArray.push(shadowLight);
  12786. }
  12787. function setupLights(physicallyCorrectLights) {
  12788. lights.setup(lightsArray, physicallyCorrectLights);
  12789. }
  12790. function setupLightsView(camera) {
  12791. lights.setupView(lightsArray, camera);
  12792. }
  12793. const state = {
  12794. lightsArray: lightsArray,
  12795. shadowsArray: shadowsArray,
  12796. lights: lights
  12797. };
  12798. return {
  12799. init: init,
  12800. state: state,
  12801. setupLights: setupLights,
  12802. setupLightsView: setupLightsView,
  12803. pushLight: pushLight,
  12804. pushShadow: pushShadow
  12805. };
  12806. }
  12807. function WebGLRenderStates(extensions, capabilities) {
  12808. let renderStates = new WeakMap();
  12809. function get(scene, renderCallDepth = 0) {
  12810. const renderStateArray = renderStates.get(scene);
  12811. let renderState;
  12812. if (renderStateArray === undefined) {
  12813. renderState = new WebGLRenderState(extensions, capabilities);
  12814. renderStates.set(scene, [renderState]);
  12815. } else {
  12816. if (renderCallDepth >= renderStateArray.length) {
  12817. renderState = new WebGLRenderState(extensions, capabilities);
  12818. renderStateArray.push(renderState);
  12819. } else {
  12820. renderState = renderStateArray[renderCallDepth];
  12821. }
  12822. }
  12823. return renderState;
  12824. }
  12825. function dispose() {
  12826. renderStates = new WeakMap();
  12827. }
  12828. return {
  12829. get: get,
  12830. dispose: dispose
  12831. };
  12832. }
  12833. class MeshDepthMaterial extends Material {
  12834. constructor(parameters) {
  12835. super();
  12836. this.isMeshDepthMaterial = true;
  12837. this.type = 'MeshDepthMaterial';
  12838. this.depthPacking = BasicDepthPacking;
  12839. this.map = null;
  12840. this.alphaMap = null;
  12841. this.displacementMap = null;
  12842. this.displacementScale = 1;
  12843. this.displacementBias = 0;
  12844. this.wireframe = false;
  12845. this.wireframeLinewidth = 1;
  12846. this.setValues(parameters);
  12847. }
  12848. copy(source) {
  12849. super.copy(source);
  12850. this.depthPacking = source.depthPacking;
  12851. this.map = source.map;
  12852. this.alphaMap = source.alphaMap;
  12853. this.displacementMap = source.displacementMap;
  12854. this.displacementScale = source.displacementScale;
  12855. this.displacementBias = source.displacementBias;
  12856. this.wireframe = source.wireframe;
  12857. this.wireframeLinewidth = source.wireframeLinewidth;
  12858. return this;
  12859. }
  12860. }
  12861. class MeshDistanceMaterial extends Material {
  12862. constructor(parameters) {
  12863. super();
  12864. this.isMeshDistanceMaterial = true;
  12865. this.type = 'MeshDistanceMaterial';
  12866. this.referencePosition = new Vector3();
  12867. this.nearDistance = 1;
  12868. this.farDistance = 1000;
  12869. this.map = null;
  12870. this.alphaMap = null;
  12871. this.displacementMap = null;
  12872. this.displacementScale = 1;
  12873. this.displacementBias = 0;
  12874. this.setValues(parameters);
  12875. }
  12876. copy(source) {
  12877. super.copy(source);
  12878. this.referencePosition.copy(source.referencePosition);
  12879. this.nearDistance = source.nearDistance;
  12880. this.farDistance = source.farDistance;
  12881. this.map = source.map;
  12882. this.alphaMap = source.alphaMap;
  12883. this.displacementMap = source.displacementMap;
  12884. this.displacementScale = source.displacementScale;
  12885. this.displacementBias = source.displacementBias;
  12886. return this;
  12887. }
  12888. }
  12889. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12890. 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}";
  12891. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12892. let _frustum = new Frustum();
  12893. const _shadowMapSize = new Vector2(),
  12894. _viewportSize = new Vector2(),
  12895. _viewport = new Vector4(),
  12896. _depthMaterial = new MeshDepthMaterial({
  12897. depthPacking: RGBADepthPacking
  12898. }),
  12899. _distanceMaterial = new MeshDistanceMaterial(),
  12900. _materialCache = {},
  12901. _maxTextureSize = _capabilities.maxTextureSize;
  12902. const shadowSide = {
  12903. 0: BackSide,
  12904. 1: FrontSide,
  12905. 2: DoubleSide
  12906. };
  12907. const shadowMaterialVertical = new ShaderMaterial({
  12908. defines: {
  12909. VSM_SAMPLES: 8
  12910. },
  12911. uniforms: {
  12912. shadow_pass: {
  12913. value: null
  12914. },
  12915. resolution: {
  12916. value: new Vector2()
  12917. },
  12918. radius: {
  12919. value: 4.0
  12920. }
  12921. },
  12922. vertexShader: vertex,
  12923. fragmentShader: fragment
  12924. });
  12925. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12926. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12927. const fullScreenTri = new BufferGeometry();
  12928. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12929. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12930. const scope = this;
  12931. this.enabled = false;
  12932. this.autoUpdate = true;
  12933. this.needsUpdate = false;
  12934. this.type = PCFShadowMap;
  12935. this.render = function (lights, scene, camera) {
  12936. if (scope.enabled === false) return;
  12937. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12938. if (lights.length === 0) return;
  12939. const currentRenderTarget = _renderer.getRenderTarget();
  12940. const activeCubeFace = _renderer.getActiveCubeFace();
  12941. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12942. const _state = _renderer.state;
  12943. // Set GL state for depth map.
  12944. _state.setBlending(NoBlending);
  12945. _state.buffers.color.setClear(1, 1, 1, 1);
  12946. _state.buffers.depth.setTest(true);
  12947. _state.setScissorTest(false);
  12948. // render depth map
  12949. for (let i = 0, il = lights.length; i < il; i++) {
  12950. const light = lights[i];
  12951. const shadow = light.shadow;
  12952. if (shadow === undefined) {
  12953. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12954. continue;
  12955. }
  12956. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12957. _shadowMapSize.copy(shadow.mapSize);
  12958. const shadowFrameExtents = shadow.getFrameExtents();
  12959. _shadowMapSize.multiply(shadowFrameExtents);
  12960. _viewportSize.copy(shadow.mapSize);
  12961. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12962. if (_shadowMapSize.x > _maxTextureSize) {
  12963. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12964. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12965. shadow.mapSize.x = _viewportSize.x;
  12966. }
  12967. if (_shadowMapSize.y > _maxTextureSize) {
  12968. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12969. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12970. shadow.mapSize.y = _viewportSize.y;
  12971. }
  12972. }
  12973. if (shadow.map === null) {
  12974. const pars = this.type !== VSMShadowMap ? {
  12975. minFilter: NearestFilter,
  12976. magFilter: NearestFilter
  12977. } : {};
  12978. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12979. shadow.map.texture.name = light.name + '.shadowMap';
  12980. shadow.camera.updateProjectionMatrix();
  12981. }
  12982. _renderer.setRenderTarget(shadow.map);
  12983. _renderer.clear();
  12984. const viewportCount = shadow.getViewportCount();
  12985. for (let vp = 0; vp < viewportCount; vp++) {
  12986. const viewport = shadow.getViewport(vp);
  12987. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12988. _state.viewport(_viewport);
  12989. shadow.updateMatrices(light, vp);
  12990. _frustum = shadow.getFrustum();
  12991. renderObject(scene, camera, shadow.camera, light, this.type);
  12992. }
  12993. // do blur pass for VSM
  12994. if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
  12995. VSMPass(shadow, camera);
  12996. }
  12997. shadow.needsUpdate = false;
  12998. }
  12999. scope.needsUpdate = false;
  13000. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13001. };
  13002. function VSMPass(shadow, camera) {
  13003. const geometry = _objects.update(fullScreenMesh);
  13004. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  13005. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13006. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13007. shadowMaterialVertical.needsUpdate = true;
  13008. shadowMaterialHorizontal.needsUpdate = true;
  13009. }
  13010. if (shadow.mapPass === null) {
  13011. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  13012. }
  13013. // vertical pass
  13014. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13015. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13016. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13017. _renderer.setRenderTarget(shadow.mapPass);
  13018. _renderer.clear();
  13019. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null);
  13020. // horizontal pass
  13021. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13022. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13023. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13024. _renderer.setRenderTarget(shadow.map);
  13025. _renderer.clear();
  13026. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  13027. }
  13028. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13029. let result = null;
  13030. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  13031. if (customMaterial !== undefined) {
  13032. result = customMaterial;
  13033. } else {
  13034. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  13035. }
  13036. if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) {
  13037. // in this case we need a unique material instance reflecting the
  13038. // appropriate state
  13039. const keyA = result.uuid,
  13040. keyB = material.uuid;
  13041. let materialsForVariant = _materialCache[keyA];
  13042. if (materialsForVariant === undefined) {
  13043. materialsForVariant = {};
  13044. _materialCache[keyA] = materialsForVariant;
  13045. }
  13046. let cachedMaterial = materialsForVariant[keyB];
  13047. if (cachedMaterial === undefined) {
  13048. cachedMaterial = result.clone();
  13049. materialsForVariant[keyB] = cachedMaterial;
  13050. }
  13051. result = cachedMaterial;
  13052. }
  13053. result.visible = material.visible;
  13054. result.wireframe = material.wireframe;
  13055. if (type === VSMShadowMap) {
  13056. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  13057. } else {
  13058. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  13059. }
  13060. result.alphaMap = material.alphaMap;
  13061. result.alphaTest = material.alphaTest;
  13062. result.map = material.map;
  13063. result.clipShadows = material.clipShadows;
  13064. result.clippingPlanes = material.clippingPlanes;
  13065. result.clipIntersection = material.clipIntersection;
  13066. result.displacementMap = material.displacementMap;
  13067. result.displacementScale = material.displacementScale;
  13068. result.displacementBias = material.displacementBias;
  13069. result.wireframeLinewidth = material.wireframeLinewidth;
  13070. result.linewidth = material.linewidth;
  13071. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  13072. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13073. result.nearDistance = shadowCameraNear;
  13074. result.farDistance = shadowCameraFar;
  13075. }
  13076. return result;
  13077. }
  13078. function renderObject(object, camera, shadowCamera, light, type) {
  13079. if (object.visible === false) return;
  13080. const visible = object.layers.test(camera.layers);
  13081. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13082. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13083. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13084. const geometry = _objects.update(object);
  13085. const material = object.material;
  13086. if (Array.isArray(material)) {
  13087. const groups = geometry.groups;
  13088. for (let k = 0, kl = groups.length; k < kl; k++) {
  13089. const group = groups[k];
  13090. const groupMaterial = material[group.materialIndex];
  13091. if (groupMaterial && groupMaterial.visible) {
  13092. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13093. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13094. }
  13095. }
  13096. } else if (material.visible) {
  13097. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13098. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13099. }
  13100. }
  13101. }
  13102. const children = object.children;
  13103. for (let i = 0, l = children.length; i < l; i++) {
  13104. renderObject(children[i], camera, shadowCamera, light, type);
  13105. }
  13106. }
  13107. }
  13108. function WebGLState(gl, extensions, capabilities) {
  13109. const isWebGL2 = capabilities.isWebGL2;
  13110. function ColorBuffer() {
  13111. let locked = false;
  13112. const color = new Vector4();
  13113. let currentColorMask = null;
  13114. const currentColorClear = new Vector4(0, 0, 0, 0);
  13115. return {
  13116. setMask: function (colorMask) {
  13117. if (currentColorMask !== colorMask && !locked) {
  13118. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13119. currentColorMask = colorMask;
  13120. }
  13121. },
  13122. setLocked: function (lock) {
  13123. locked = lock;
  13124. },
  13125. setClear: function (r, g, b, a, premultipliedAlpha) {
  13126. if (premultipliedAlpha === true) {
  13127. r *= a;
  13128. g *= a;
  13129. b *= a;
  13130. }
  13131. color.set(r, g, b, a);
  13132. if (currentColorClear.equals(color) === false) {
  13133. gl.clearColor(r, g, b, a);
  13134. currentColorClear.copy(color);
  13135. }
  13136. },
  13137. reset: function () {
  13138. locked = false;
  13139. currentColorMask = null;
  13140. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13141. }
  13142. };
  13143. }
  13144. function DepthBuffer() {
  13145. let locked = false;
  13146. let currentDepthMask = null;
  13147. let currentDepthFunc = null;
  13148. let currentDepthClear = null;
  13149. return {
  13150. setTest: function (depthTest) {
  13151. if (depthTest) {
  13152. enable(gl.DEPTH_TEST);
  13153. } else {
  13154. disable(gl.DEPTH_TEST);
  13155. }
  13156. },
  13157. setMask: function (depthMask) {
  13158. if (currentDepthMask !== depthMask && !locked) {
  13159. gl.depthMask(depthMask);
  13160. currentDepthMask = depthMask;
  13161. }
  13162. },
  13163. setFunc: function (depthFunc) {
  13164. if (currentDepthFunc !== depthFunc) {
  13165. switch (depthFunc) {
  13166. case NeverDepth:
  13167. gl.depthFunc(gl.NEVER);
  13168. break;
  13169. case AlwaysDepth:
  13170. gl.depthFunc(gl.ALWAYS);
  13171. break;
  13172. case LessDepth:
  13173. gl.depthFunc(gl.LESS);
  13174. break;
  13175. case LessEqualDepth:
  13176. gl.depthFunc(gl.LEQUAL);
  13177. break;
  13178. case EqualDepth:
  13179. gl.depthFunc(gl.EQUAL);
  13180. break;
  13181. case GreaterEqualDepth:
  13182. gl.depthFunc(gl.GEQUAL);
  13183. break;
  13184. case GreaterDepth:
  13185. gl.depthFunc(gl.GREATER);
  13186. break;
  13187. case NotEqualDepth:
  13188. gl.depthFunc(gl.NOTEQUAL);
  13189. break;
  13190. default:
  13191. gl.depthFunc(gl.LEQUAL);
  13192. }
  13193. currentDepthFunc = depthFunc;
  13194. }
  13195. },
  13196. setLocked: function (lock) {
  13197. locked = lock;
  13198. },
  13199. setClear: function (depth) {
  13200. if (currentDepthClear !== depth) {
  13201. gl.clearDepth(depth);
  13202. currentDepthClear = depth;
  13203. }
  13204. },
  13205. reset: function () {
  13206. locked = false;
  13207. currentDepthMask = null;
  13208. currentDepthFunc = null;
  13209. currentDepthClear = null;
  13210. }
  13211. };
  13212. }
  13213. function StencilBuffer() {
  13214. let locked = false;
  13215. let currentStencilMask = null;
  13216. let currentStencilFunc = null;
  13217. let currentStencilRef = null;
  13218. let currentStencilFuncMask = null;
  13219. let currentStencilFail = null;
  13220. let currentStencilZFail = null;
  13221. let currentStencilZPass = null;
  13222. let currentStencilClear = null;
  13223. return {
  13224. setTest: function (stencilTest) {
  13225. if (!locked) {
  13226. if (stencilTest) {
  13227. enable(gl.STENCIL_TEST);
  13228. } else {
  13229. disable(gl.STENCIL_TEST);
  13230. }
  13231. }
  13232. },
  13233. setMask: function (stencilMask) {
  13234. if (currentStencilMask !== stencilMask && !locked) {
  13235. gl.stencilMask(stencilMask);
  13236. currentStencilMask = stencilMask;
  13237. }
  13238. },
  13239. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13240. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13241. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13242. currentStencilFunc = stencilFunc;
  13243. currentStencilRef = stencilRef;
  13244. currentStencilFuncMask = stencilMask;
  13245. }
  13246. },
  13247. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13248. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13249. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13250. currentStencilFail = stencilFail;
  13251. currentStencilZFail = stencilZFail;
  13252. currentStencilZPass = stencilZPass;
  13253. }
  13254. },
  13255. setLocked: function (lock) {
  13256. locked = lock;
  13257. },
  13258. setClear: function (stencil) {
  13259. if (currentStencilClear !== stencil) {
  13260. gl.clearStencil(stencil);
  13261. currentStencilClear = stencil;
  13262. }
  13263. },
  13264. reset: function () {
  13265. locked = false;
  13266. currentStencilMask = null;
  13267. currentStencilFunc = null;
  13268. currentStencilRef = null;
  13269. currentStencilFuncMask = null;
  13270. currentStencilFail = null;
  13271. currentStencilZFail = null;
  13272. currentStencilZPass = null;
  13273. currentStencilClear = null;
  13274. }
  13275. };
  13276. }
  13277. //
  13278. const colorBuffer = new ColorBuffer();
  13279. const depthBuffer = new DepthBuffer();
  13280. const stencilBuffer = new StencilBuffer();
  13281. const uboBindings = new WeakMap();
  13282. const uboProgamMap = new WeakMap();
  13283. let enabledCapabilities = {};
  13284. let currentBoundFramebuffers = {};
  13285. let currentDrawbuffers = new WeakMap();
  13286. let defaultDrawbuffers = [];
  13287. let currentProgram = null;
  13288. let currentBlendingEnabled = false;
  13289. let currentBlending = null;
  13290. let currentBlendEquation = null;
  13291. let currentBlendSrc = null;
  13292. let currentBlendDst = null;
  13293. let currentBlendEquationAlpha = null;
  13294. let currentBlendSrcAlpha = null;
  13295. let currentBlendDstAlpha = null;
  13296. let currentPremultipledAlpha = false;
  13297. let currentFlipSided = null;
  13298. let currentCullFace = null;
  13299. let currentLineWidth = null;
  13300. let currentPolygonOffsetFactor = null;
  13301. let currentPolygonOffsetUnits = null;
  13302. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13303. let lineWidthAvailable = false;
  13304. let version = 0;
  13305. const glVersion = gl.getParameter(gl.VERSION);
  13306. if (glVersion.indexOf('WebGL') !== -1) {
  13307. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13308. lineWidthAvailable = version >= 1.0;
  13309. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13310. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13311. lineWidthAvailable = version >= 2.0;
  13312. }
  13313. let currentTextureSlot = null;
  13314. let currentBoundTextures = {};
  13315. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13316. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13317. const currentScissor = new Vector4().fromArray(scissorParam);
  13318. const currentViewport = new Vector4().fromArray(viewportParam);
  13319. function createTexture(type, target, count) {
  13320. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13321. const texture = gl.createTexture();
  13322. gl.bindTexture(type, texture);
  13323. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13324. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13325. for (let i = 0; i < count; i++) {
  13326. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13327. }
  13328. return texture;
  13329. }
  13330. const emptyTextures = {};
  13331. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13332. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6);
  13333. // init
  13334. colorBuffer.setClear(0, 0, 0, 1);
  13335. depthBuffer.setClear(1);
  13336. stencilBuffer.setClear(0);
  13337. enable(gl.DEPTH_TEST);
  13338. depthBuffer.setFunc(LessEqualDepth);
  13339. setFlipSided(false);
  13340. setCullFace(CullFaceBack);
  13341. enable(gl.CULL_FACE);
  13342. setBlending(NoBlending);
  13343. //
  13344. function enable(id) {
  13345. if (enabledCapabilities[id] !== true) {
  13346. gl.enable(id);
  13347. enabledCapabilities[id] = true;
  13348. }
  13349. }
  13350. function disable(id) {
  13351. if (enabledCapabilities[id] !== false) {
  13352. gl.disable(id);
  13353. enabledCapabilities[id] = false;
  13354. }
  13355. }
  13356. function bindFramebuffer(target, framebuffer) {
  13357. if (currentBoundFramebuffers[target] !== framebuffer) {
  13358. gl.bindFramebuffer(target, framebuffer);
  13359. currentBoundFramebuffers[target] = framebuffer;
  13360. if (isWebGL2) {
  13361. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13362. if (target === gl.DRAW_FRAMEBUFFER) {
  13363. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13364. }
  13365. if (target === gl.FRAMEBUFFER) {
  13366. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13367. }
  13368. }
  13369. return true;
  13370. }
  13371. return false;
  13372. }
  13373. function drawBuffers(renderTarget, framebuffer) {
  13374. let drawBuffers = defaultDrawbuffers;
  13375. let needsUpdate = false;
  13376. if (renderTarget) {
  13377. drawBuffers = currentDrawbuffers.get(framebuffer);
  13378. if (drawBuffers === undefined) {
  13379. drawBuffers = [];
  13380. currentDrawbuffers.set(framebuffer, drawBuffers);
  13381. }
  13382. if (renderTarget.isWebGLMultipleRenderTargets) {
  13383. const textures = renderTarget.texture;
  13384. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13385. for (let i = 0, il = textures.length; i < il; i++) {
  13386. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13387. }
  13388. drawBuffers.length = textures.length;
  13389. needsUpdate = true;
  13390. }
  13391. } else {
  13392. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13393. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13394. needsUpdate = true;
  13395. }
  13396. }
  13397. } else {
  13398. if (drawBuffers[0] !== gl.BACK) {
  13399. drawBuffers[0] = gl.BACK;
  13400. needsUpdate = true;
  13401. }
  13402. }
  13403. if (needsUpdate) {
  13404. if (capabilities.isWebGL2) {
  13405. gl.drawBuffers(drawBuffers);
  13406. } else {
  13407. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13408. }
  13409. }
  13410. }
  13411. function useProgram(program) {
  13412. if (currentProgram !== program) {
  13413. gl.useProgram(program);
  13414. currentProgram = program;
  13415. return true;
  13416. }
  13417. return false;
  13418. }
  13419. const equationToGL = {
  13420. [AddEquation]: gl.FUNC_ADD,
  13421. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13422. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13423. };
  13424. if (isWebGL2) {
  13425. equationToGL[MinEquation] = gl.MIN;
  13426. equationToGL[MaxEquation] = gl.MAX;
  13427. } else {
  13428. const extension = extensions.get('EXT_blend_minmax');
  13429. if (extension !== null) {
  13430. equationToGL[MinEquation] = extension.MIN_EXT;
  13431. equationToGL[MaxEquation] = extension.MAX_EXT;
  13432. }
  13433. }
  13434. const factorToGL = {
  13435. [ZeroFactor]: gl.ZERO,
  13436. [OneFactor]: gl.ONE,
  13437. [SrcColorFactor]: gl.SRC_COLOR,
  13438. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13439. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13440. [DstColorFactor]: gl.DST_COLOR,
  13441. [DstAlphaFactor]: gl.DST_ALPHA,
  13442. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13443. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13444. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13445. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13446. };
  13447. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13448. if (blending === NoBlending) {
  13449. if (currentBlendingEnabled === true) {
  13450. disable(gl.BLEND);
  13451. currentBlendingEnabled = false;
  13452. }
  13453. return;
  13454. }
  13455. if (currentBlendingEnabled === false) {
  13456. enable(gl.BLEND);
  13457. currentBlendingEnabled = true;
  13458. }
  13459. if (blending !== CustomBlending) {
  13460. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13461. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13462. gl.blendEquation(gl.FUNC_ADD);
  13463. currentBlendEquation = AddEquation;
  13464. currentBlendEquationAlpha = AddEquation;
  13465. }
  13466. if (premultipliedAlpha) {
  13467. switch (blending) {
  13468. case NormalBlending:
  13469. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13470. break;
  13471. case AdditiveBlending:
  13472. gl.blendFunc(gl.ONE, gl.ONE);
  13473. break;
  13474. case SubtractiveBlending:
  13475. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13476. break;
  13477. case MultiplyBlending:
  13478. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13479. break;
  13480. default:
  13481. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13482. break;
  13483. }
  13484. } else {
  13485. switch (blending) {
  13486. case NormalBlending:
  13487. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13488. break;
  13489. case AdditiveBlending:
  13490. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13491. break;
  13492. case SubtractiveBlending:
  13493. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13494. break;
  13495. case MultiplyBlending:
  13496. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13497. break;
  13498. default:
  13499. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13500. break;
  13501. }
  13502. }
  13503. currentBlendSrc = null;
  13504. currentBlendDst = null;
  13505. currentBlendSrcAlpha = null;
  13506. currentBlendDstAlpha = null;
  13507. currentBlending = blending;
  13508. currentPremultipledAlpha = premultipliedAlpha;
  13509. }
  13510. return;
  13511. }
  13512. // custom blending
  13513. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13514. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13515. blendDstAlpha = blendDstAlpha || blendDst;
  13516. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13517. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13518. currentBlendEquation = blendEquation;
  13519. currentBlendEquationAlpha = blendEquationAlpha;
  13520. }
  13521. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13522. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13523. currentBlendSrc = blendSrc;
  13524. currentBlendDst = blendDst;
  13525. currentBlendSrcAlpha = blendSrcAlpha;
  13526. currentBlendDstAlpha = blendDstAlpha;
  13527. }
  13528. currentBlending = blending;
  13529. currentPremultipledAlpha = false;
  13530. }
  13531. function setMaterial(material, frontFaceCW) {
  13532. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13533. let flipSided = material.side === BackSide;
  13534. if (frontFaceCW) flipSided = !flipSided;
  13535. setFlipSided(flipSided);
  13536. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  13537. depthBuffer.setFunc(material.depthFunc);
  13538. depthBuffer.setTest(material.depthTest);
  13539. depthBuffer.setMask(material.depthWrite);
  13540. colorBuffer.setMask(material.colorWrite);
  13541. const stencilWrite = material.stencilWrite;
  13542. stencilBuffer.setTest(stencilWrite);
  13543. if (stencilWrite) {
  13544. stencilBuffer.setMask(material.stencilWriteMask);
  13545. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13546. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13547. }
  13548. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13549. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13550. }
  13551. //
  13552. function setFlipSided(flipSided) {
  13553. if (currentFlipSided !== flipSided) {
  13554. if (flipSided) {
  13555. gl.frontFace(gl.CW);
  13556. } else {
  13557. gl.frontFace(gl.CCW);
  13558. }
  13559. currentFlipSided = flipSided;
  13560. }
  13561. }
  13562. function setCullFace(cullFace) {
  13563. if (cullFace !== CullFaceNone) {
  13564. enable(gl.CULL_FACE);
  13565. if (cullFace !== currentCullFace) {
  13566. if (cullFace === CullFaceBack) {
  13567. gl.cullFace(gl.BACK);
  13568. } else if (cullFace === CullFaceFront) {
  13569. gl.cullFace(gl.FRONT);
  13570. } else {
  13571. gl.cullFace(gl.FRONT_AND_BACK);
  13572. }
  13573. }
  13574. } else {
  13575. disable(gl.CULL_FACE);
  13576. }
  13577. currentCullFace = cullFace;
  13578. }
  13579. function setLineWidth(width) {
  13580. if (width !== currentLineWidth) {
  13581. if (lineWidthAvailable) gl.lineWidth(width);
  13582. currentLineWidth = width;
  13583. }
  13584. }
  13585. function setPolygonOffset(polygonOffset, factor, units) {
  13586. if (polygonOffset) {
  13587. enable(gl.POLYGON_OFFSET_FILL);
  13588. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13589. gl.polygonOffset(factor, units);
  13590. currentPolygonOffsetFactor = factor;
  13591. currentPolygonOffsetUnits = units;
  13592. }
  13593. } else {
  13594. disable(gl.POLYGON_OFFSET_FILL);
  13595. }
  13596. }
  13597. function setScissorTest(scissorTest) {
  13598. if (scissorTest) {
  13599. enable(gl.SCISSOR_TEST);
  13600. } else {
  13601. disable(gl.SCISSOR_TEST);
  13602. }
  13603. }
  13604. // texture
  13605. function activeTexture(webglSlot) {
  13606. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13607. if (currentTextureSlot !== webglSlot) {
  13608. gl.activeTexture(webglSlot);
  13609. currentTextureSlot = webglSlot;
  13610. }
  13611. }
  13612. function bindTexture(webglType, webglTexture, webglSlot) {
  13613. if (webglSlot === undefined) {
  13614. if (currentTextureSlot === null) {
  13615. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13616. } else {
  13617. webglSlot = currentTextureSlot;
  13618. }
  13619. }
  13620. let boundTexture = currentBoundTextures[webglSlot];
  13621. if (boundTexture === undefined) {
  13622. boundTexture = {
  13623. type: undefined,
  13624. texture: undefined
  13625. };
  13626. currentBoundTextures[webglSlot] = boundTexture;
  13627. }
  13628. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13629. if (currentTextureSlot !== webglSlot) {
  13630. gl.activeTexture(webglSlot);
  13631. currentTextureSlot = webglSlot;
  13632. }
  13633. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13634. boundTexture.type = webglType;
  13635. boundTexture.texture = webglTexture;
  13636. }
  13637. }
  13638. function unbindTexture() {
  13639. const boundTexture = currentBoundTextures[currentTextureSlot];
  13640. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13641. gl.bindTexture(boundTexture.type, null);
  13642. boundTexture.type = undefined;
  13643. boundTexture.texture = undefined;
  13644. }
  13645. }
  13646. function compressedTexImage2D() {
  13647. try {
  13648. gl.compressedTexImage2D.apply(gl, arguments);
  13649. } catch (error) {
  13650. console.error('THREE.WebGLState:', error);
  13651. }
  13652. }
  13653. function compressedTexImage3D() {
  13654. try {
  13655. gl.compressedTexImage3D.apply(gl, arguments);
  13656. } catch (error) {
  13657. console.error('THREE.WebGLState:', error);
  13658. }
  13659. }
  13660. function texSubImage2D() {
  13661. try {
  13662. gl.texSubImage2D.apply(gl, arguments);
  13663. } catch (error) {
  13664. console.error('THREE.WebGLState:', error);
  13665. }
  13666. }
  13667. function texSubImage3D() {
  13668. try {
  13669. gl.texSubImage3D.apply(gl, arguments);
  13670. } catch (error) {
  13671. console.error('THREE.WebGLState:', error);
  13672. }
  13673. }
  13674. function compressedTexSubImage2D() {
  13675. try {
  13676. gl.compressedTexSubImage2D.apply(gl, arguments);
  13677. } catch (error) {
  13678. console.error('THREE.WebGLState:', error);
  13679. }
  13680. }
  13681. function compressedTexSubImage3D() {
  13682. try {
  13683. gl.compressedTexSubImage3D.apply(gl, arguments);
  13684. } catch (error) {
  13685. console.error('THREE.WebGLState:', error);
  13686. }
  13687. }
  13688. function texStorage2D() {
  13689. try {
  13690. gl.texStorage2D.apply(gl, arguments);
  13691. } catch (error) {
  13692. console.error('THREE.WebGLState:', error);
  13693. }
  13694. }
  13695. function texStorage3D() {
  13696. try {
  13697. gl.texStorage3D.apply(gl, arguments);
  13698. } catch (error) {
  13699. console.error('THREE.WebGLState:', error);
  13700. }
  13701. }
  13702. function texImage2D() {
  13703. try {
  13704. gl.texImage2D.apply(gl, arguments);
  13705. } catch (error) {
  13706. console.error('THREE.WebGLState:', error);
  13707. }
  13708. }
  13709. function texImage3D() {
  13710. try {
  13711. gl.texImage3D.apply(gl, arguments);
  13712. } catch (error) {
  13713. console.error('THREE.WebGLState:', error);
  13714. }
  13715. }
  13716. //
  13717. function scissor(scissor) {
  13718. if (currentScissor.equals(scissor) === false) {
  13719. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13720. currentScissor.copy(scissor);
  13721. }
  13722. }
  13723. function viewport(viewport) {
  13724. if (currentViewport.equals(viewport) === false) {
  13725. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13726. currentViewport.copy(viewport);
  13727. }
  13728. }
  13729. function updateUBOMapping(uniformsGroup, program) {
  13730. let mapping = uboProgamMap.get(program);
  13731. if (mapping === undefined) {
  13732. mapping = new WeakMap();
  13733. uboProgamMap.set(program, mapping);
  13734. }
  13735. let blockIndex = mapping.get(uniformsGroup);
  13736. if (blockIndex === undefined) {
  13737. blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
  13738. mapping.set(uniformsGroup, blockIndex);
  13739. }
  13740. }
  13741. function uniformBlockBinding(uniformsGroup, program) {
  13742. const mapping = uboProgamMap.get(program);
  13743. const blockIndex = mapping.get(uniformsGroup);
  13744. if (uboBindings.get(uniformsGroup) !== blockIndex) {
  13745. // bind shader specific block index to global block point
  13746. gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
  13747. uboBindings.set(uniformsGroup, blockIndex);
  13748. }
  13749. }
  13750. //
  13751. function reset() {
  13752. // reset state
  13753. gl.disable(gl.BLEND);
  13754. gl.disable(gl.CULL_FACE);
  13755. gl.disable(gl.DEPTH_TEST);
  13756. gl.disable(gl.POLYGON_OFFSET_FILL);
  13757. gl.disable(gl.SCISSOR_TEST);
  13758. gl.disable(gl.STENCIL_TEST);
  13759. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13760. gl.blendEquation(gl.FUNC_ADD);
  13761. gl.blendFunc(gl.ONE, gl.ZERO);
  13762. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13763. gl.colorMask(true, true, true, true);
  13764. gl.clearColor(0, 0, 0, 0);
  13765. gl.depthMask(true);
  13766. gl.depthFunc(gl.LESS);
  13767. gl.clearDepth(1);
  13768. gl.stencilMask(0xffffffff);
  13769. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13770. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13771. gl.clearStencil(0);
  13772. gl.cullFace(gl.BACK);
  13773. gl.frontFace(gl.CCW);
  13774. gl.polygonOffset(0, 0);
  13775. gl.activeTexture(gl.TEXTURE0);
  13776. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13777. if (isWebGL2 === true) {
  13778. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13779. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13780. }
  13781. gl.useProgram(null);
  13782. gl.lineWidth(1);
  13783. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13784. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  13785. // reset internals
  13786. enabledCapabilities = {};
  13787. currentTextureSlot = null;
  13788. currentBoundTextures = {};
  13789. currentBoundFramebuffers = {};
  13790. currentDrawbuffers = new WeakMap();
  13791. defaultDrawbuffers = [];
  13792. currentProgram = null;
  13793. currentBlendingEnabled = false;
  13794. currentBlending = null;
  13795. currentBlendEquation = null;
  13796. currentBlendSrc = null;
  13797. currentBlendDst = null;
  13798. currentBlendEquationAlpha = null;
  13799. currentBlendSrcAlpha = null;
  13800. currentBlendDstAlpha = null;
  13801. currentPremultipledAlpha = false;
  13802. currentFlipSided = null;
  13803. currentCullFace = null;
  13804. currentLineWidth = null;
  13805. currentPolygonOffsetFactor = null;
  13806. currentPolygonOffsetUnits = null;
  13807. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13808. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13809. colorBuffer.reset();
  13810. depthBuffer.reset();
  13811. stencilBuffer.reset();
  13812. }
  13813. return {
  13814. buffers: {
  13815. color: colorBuffer,
  13816. depth: depthBuffer,
  13817. stencil: stencilBuffer
  13818. },
  13819. enable: enable,
  13820. disable: disable,
  13821. bindFramebuffer: bindFramebuffer,
  13822. drawBuffers: drawBuffers,
  13823. useProgram: useProgram,
  13824. setBlending: setBlending,
  13825. setMaterial: setMaterial,
  13826. setFlipSided: setFlipSided,
  13827. setCullFace: setCullFace,
  13828. setLineWidth: setLineWidth,
  13829. setPolygonOffset: setPolygonOffset,
  13830. setScissorTest: setScissorTest,
  13831. activeTexture: activeTexture,
  13832. bindTexture: bindTexture,
  13833. unbindTexture: unbindTexture,
  13834. compressedTexImage2D: compressedTexImage2D,
  13835. compressedTexImage3D: compressedTexImage3D,
  13836. texImage2D: texImage2D,
  13837. texImage3D: texImage3D,
  13838. updateUBOMapping: updateUBOMapping,
  13839. uniformBlockBinding: uniformBlockBinding,
  13840. texStorage2D: texStorage2D,
  13841. texStorage3D: texStorage3D,
  13842. texSubImage2D: texSubImage2D,
  13843. texSubImage3D: texSubImage3D,
  13844. compressedTexSubImage2D: compressedTexSubImage2D,
  13845. compressedTexSubImage3D: compressedTexSubImage3D,
  13846. scissor: scissor,
  13847. viewport: viewport,
  13848. reset: reset
  13849. };
  13850. }
  13851. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13852. const isWebGL2 = capabilities.isWebGL2;
  13853. const maxTextures = capabilities.maxTextures;
  13854. const maxCubemapSize = capabilities.maxCubemapSize;
  13855. const maxTextureSize = capabilities.maxTextureSize;
  13856. const maxSamples = capabilities.maxSamples;
  13857. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13858. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test(navigator.userAgent);
  13859. const _videoTextures = new WeakMap();
  13860. let _canvas;
  13861. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13862. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13863. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13864. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13865. let useOffscreenCanvas = false;
  13866. try {
  13867. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13868. // eslint-disable-next-line compat/compat
  13869. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13870. } catch (err) {
  13871. // Ignore any errors
  13872. }
  13873. function createCanvas(width, height) {
  13874. // Use OffscreenCanvas when available. Specially needed in web workers
  13875. return useOffscreenCanvas ?
  13876. // eslint-disable-next-line compat/compat
  13877. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13878. }
  13879. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13880. let scale = 1;
  13881. // handle case if texture exceeds max size
  13882. if (image.width > maxSize || image.height > maxSize) {
  13883. scale = maxSize / Math.max(image.width, image.height);
  13884. }
  13885. // only perform resize if necessary
  13886. if (scale < 1 || needsPowerOfTwo === true) {
  13887. // only perform resize for certain image types
  13888. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13889. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13890. const width = floor(scale * image.width);
  13891. const height = floor(scale * image.height);
  13892. if (_canvas === undefined) _canvas = createCanvas(width, height);
  13893. // cube textures can't reuse the same canvas
  13894. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13895. canvas.width = width;
  13896. canvas.height = height;
  13897. const context = canvas.getContext('2d');
  13898. context.drawImage(image, 0, 0, width, height);
  13899. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13900. return canvas;
  13901. } else {
  13902. if ('data' in image) {
  13903. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13904. }
  13905. return image;
  13906. }
  13907. }
  13908. return image;
  13909. }
  13910. function isPowerOfTwo$1(image) {
  13911. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13912. }
  13913. function textureNeedsPowerOfTwo(texture) {
  13914. if (isWebGL2) return false;
  13915. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13916. }
  13917. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13918. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13919. }
  13920. function generateMipmap(target) {
  13921. _gl.generateMipmap(target);
  13922. }
  13923. function getInternalFormat(internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false) {
  13924. if (isWebGL2 === false) return glFormat;
  13925. if (internalFormatName !== null) {
  13926. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13927. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13928. }
  13929. let internalFormat = glFormat;
  13930. if (glFormat === _gl.RED) {
  13931. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13932. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13933. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13934. }
  13935. if (glFormat === _gl.RG) {
  13936. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13937. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13938. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13939. }
  13940. if (glFormat === _gl.RGBA) {
  13941. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13942. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13943. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && forceLinearEncoding === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13944. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13945. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13946. }
  13947. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13948. extensions.get('EXT_color_buffer_float');
  13949. }
  13950. return internalFormat;
  13951. }
  13952. function getMipLevels(texture, image, supportsMips) {
  13953. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13954. return Math.log2(Math.max(image.width, image.height)) + 1;
  13955. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13956. // user-defined mipmaps
  13957. return texture.mipmaps.length;
  13958. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13959. return image.mipmaps.length;
  13960. } else {
  13961. // texture without mipmaps (only base level)
  13962. return 1;
  13963. }
  13964. }
  13965. // Fallback filters for non-power-of-2 textures
  13966. function filterFallback(f) {
  13967. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13968. return _gl.NEAREST;
  13969. }
  13970. return _gl.LINEAR;
  13971. }
  13972. //
  13973. function onTextureDispose(event) {
  13974. const texture = event.target;
  13975. texture.removeEventListener('dispose', onTextureDispose);
  13976. deallocateTexture(texture);
  13977. if (texture.isVideoTexture) {
  13978. _videoTextures.delete(texture);
  13979. }
  13980. }
  13981. function onRenderTargetDispose(event) {
  13982. const renderTarget = event.target;
  13983. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13984. deallocateRenderTarget(renderTarget);
  13985. }
  13986. //
  13987. function deallocateTexture(texture) {
  13988. const textureProperties = properties.get(texture);
  13989. if (textureProperties.__webglInit === undefined) return;
  13990. // check if it's necessary to remove the WebGLTexture object
  13991. const source = texture.source;
  13992. const webglTextures = _sources.get(source);
  13993. if (webglTextures) {
  13994. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13995. webglTexture.usedTimes--;
  13996. // the WebGLTexture object is not used anymore, remove it
  13997. if (webglTexture.usedTimes === 0) {
  13998. deleteTexture(texture);
  13999. }
  14000. // remove the weak map entry if no WebGLTexture uses the source anymore
  14001. if (Object.keys(webglTextures).length === 0) {
  14002. _sources.delete(source);
  14003. }
  14004. }
  14005. properties.remove(texture);
  14006. }
  14007. function deleteTexture(texture) {
  14008. const textureProperties = properties.get(texture);
  14009. _gl.deleteTexture(textureProperties.__webglTexture);
  14010. const source = texture.source;
  14011. const webglTextures = _sources.get(source);
  14012. delete webglTextures[textureProperties.__cacheKey];
  14013. info.memory.textures--;
  14014. }
  14015. function deallocateRenderTarget(renderTarget) {
  14016. const texture = renderTarget.texture;
  14017. const renderTargetProperties = properties.get(renderTarget);
  14018. const textureProperties = properties.get(texture);
  14019. if (textureProperties.__webglTexture !== undefined) {
  14020. _gl.deleteTexture(textureProperties.__webglTexture);
  14021. info.memory.textures--;
  14022. }
  14023. if (renderTarget.depthTexture) {
  14024. renderTarget.depthTexture.dispose();
  14025. }
  14026. if (renderTarget.isWebGLCubeRenderTarget) {
  14027. for (let i = 0; i < 6; i++) {
  14028. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14029. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14030. }
  14031. } else {
  14032. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14033. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14034. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  14035. if (renderTargetProperties.__webglColorRenderbuffer) {
  14036. for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) {
  14037. if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]);
  14038. }
  14039. }
  14040. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  14041. }
  14042. if (renderTarget.isWebGLMultipleRenderTargets) {
  14043. for (let i = 0, il = texture.length; i < il; i++) {
  14044. const attachmentProperties = properties.get(texture[i]);
  14045. if (attachmentProperties.__webglTexture) {
  14046. _gl.deleteTexture(attachmentProperties.__webglTexture);
  14047. info.memory.textures--;
  14048. }
  14049. properties.remove(texture[i]);
  14050. }
  14051. }
  14052. properties.remove(texture);
  14053. properties.remove(renderTarget);
  14054. }
  14055. //
  14056. let textureUnits = 0;
  14057. function resetTextureUnits() {
  14058. textureUnits = 0;
  14059. }
  14060. function allocateTextureUnit() {
  14061. const textureUnit = textureUnits;
  14062. if (textureUnit >= maxTextures) {
  14063. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  14064. }
  14065. textureUnits += 1;
  14066. return textureUnit;
  14067. }
  14068. function getTextureCacheKey(texture) {
  14069. const array = [];
  14070. array.push(texture.wrapS);
  14071. array.push(texture.wrapT);
  14072. array.push(texture.wrapR || 0);
  14073. array.push(texture.magFilter);
  14074. array.push(texture.minFilter);
  14075. array.push(texture.anisotropy);
  14076. array.push(texture.internalFormat);
  14077. array.push(texture.format);
  14078. array.push(texture.type);
  14079. array.push(texture.generateMipmaps);
  14080. array.push(texture.premultiplyAlpha);
  14081. array.push(texture.flipY);
  14082. array.push(texture.unpackAlignment);
  14083. array.push(texture.encoding);
  14084. return array.join();
  14085. }
  14086. //
  14087. function setTexture2D(texture, slot) {
  14088. const textureProperties = properties.get(texture);
  14089. if (texture.isVideoTexture) updateVideoTexture(texture);
  14090. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  14091. const image = texture.image;
  14092. if (image === null) {
  14093. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  14094. } else if (image.complete === false) {
  14095. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14096. } else {
  14097. uploadTexture(textureProperties, texture, slot);
  14098. return;
  14099. }
  14100. }
  14101. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14102. }
  14103. function setTexture2DArray(texture, slot) {
  14104. const textureProperties = properties.get(texture);
  14105. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14106. uploadTexture(textureProperties, texture, slot);
  14107. return;
  14108. }
  14109. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14110. }
  14111. function setTexture3D(texture, slot) {
  14112. const textureProperties = properties.get(texture);
  14113. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14114. uploadTexture(textureProperties, texture, slot);
  14115. return;
  14116. }
  14117. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14118. }
  14119. function setTextureCube(texture, slot) {
  14120. const textureProperties = properties.get(texture);
  14121. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14122. uploadCubeTexture(textureProperties, texture, slot);
  14123. return;
  14124. }
  14125. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14126. }
  14127. const wrappingToGL = {
  14128. [RepeatWrapping]: _gl.REPEAT,
  14129. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  14130. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  14131. };
  14132. const filterToGL = {
  14133. [NearestFilter]: _gl.NEAREST,
  14134. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  14135. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  14136. [LinearFilter]: _gl.LINEAR,
  14137. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  14138. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  14139. };
  14140. function setTextureParameters(textureType, texture, supportsMips) {
  14141. if (supportsMips) {
  14142. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  14143. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  14144. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  14145. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  14146. }
  14147. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  14148. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  14149. } else {
  14150. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  14151. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  14152. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  14153. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  14154. }
  14155. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14156. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14157. }
  14158. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  14159. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  14160. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14161. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14162. }
  14163. }
  14164. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  14165. const extension = extensions.get('EXT_texture_filter_anisotropic');
  14166. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  14167. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  14168. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14169. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14170. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14171. }
  14172. }
  14173. }
  14174. function initTexture(textureProperties, texture) {
  14175. let forceUpload = false;
  14176. if (textureProperties.__webglInit === undefined) {
  14177. textureProperties.__webglInit = true;
  14178. texture.addEventListener('dispose', onTextureDispose);
  14179. }
  14180. // create Source <-> WebGLTextures mapping if necessary
  14181. const source = texture.source;
  14182. let webglTextures = _sources.get(source);
  14183. if (webglTextures === undefined) {
  14184. webglTextures = {};
  14185. _sources.set(source, webglTextures);
  14186. }
  14187. // check if there is already a WebGLTexture object for the given texture parameters
  14188. const textureCacheKey = getTextureCacheKey(texture);
  14189. if (textureCacheKey !== textureProperties.__cacheKey) {
  14190. // if not, create a new instance of WebGLTexture
  14191. if (webglTextures[textureCacheKey] === undefined) {
  14192. // create new entry
  14193. webglTextures[textureCacheKey] = {
  14194. texture: _gl.createTexture(),
  14195. usedTimes: 0
  14196. };
  14197. info.memory.textures++;
  14198. // when a new instance of WebGLTexture was created, a texture upload is required
  14199. // even if the image contents are identical
  14200. forceUpload = true;
  14201. }
  14202. webglTextures[textureCacheKey].usedTimes++;
  14203. // every time the texture cache key changes, it's necessary to check if an instance of
  14204. // WebGLTexture can be deleted in order to avoid a memory leak.
  14205. const webglTexture = webglTextures[textureProperties.__cacheKey];
  14206. if (webglTexture !== undefined) {
  14207. webglTextures[textureProperties.__cacheKey].usedTimes--;
  14208. if (webglTexture.usedTimes === 0) {
  14209. deleteTexture(texture);
  14210. }
  14211. }
  14212. // store references to cache key and WebGLTexture object
  14213. textureProperties.__cacheKey = textureCacheKey;
  14214. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  14215. }
  14216. return forceUpload;
  14217. }
  14218. function uploadTexture(textureProperties, texture, slot) {
  14219. let textureType = _gl.TEXTURE_2D;
  14220. if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  14221. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  14222. const forceUpload = initTexture(textureProperties, texture);
  14223. const source = texture.source;
  14224. state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14225. const sourceProperties = properties.get(source);
  14226. if (source.version !== sourceProperties.__version || forceUpload === true) {
  14227. state.activeTexture(_gl.TEXTURE0 + slot);
  14228. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14229. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14230. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14231. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14232. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  14233. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  14234. image = verifyColorSpace(texture, image);
  14235. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14236. glFormat = utils.convert(texture.format, texture.encoding);
  14237. let glType = utils.convert(texture.type),
  14238. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  14239. setTextureParameters(textureType, texture, supportsMips);
  14240. let mipmap;
  14241. const mipmaps = texture.mipmaps;
  14242. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14243. const allocateMemory = sourceProperties.__version === undefined || forceUpload === true;
  14244. const levels = getMipLevels(texture, image, supportsMips);
  14245. if (texture.isDepthTexture) {
  14246. // populate depth texture with dummy data
  14247. glInternalFormat = _gl.DEPTH_COMPONENT;
  14248. if (isWebGL2) {
  14249. if (texture.type === FloatType) {
  14250. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14251. } else if (texture.type === UnsignedIntType) {
  14252. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14253. } else if (texture.type === UnsignedInt248Type) {
  14254. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14255. } else {
  14256. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14257. }
  14258. } else {
  14259. if (texture.type === FloatType) {
  14260. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  14261. }
  14262. }
  14263. // validation checks for WebGL 1
  14264. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  14265. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14266. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14267. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14268. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14269. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14270. texture.type = UnsignedIntType;
  14271. glType = utils.convert(texture.type);
  14272. }
  14273. }
  14274. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  14275. // Depth stencil textures need the DEPTH_STENCIL internal format
  14276. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14277. glInternalFormat = _gl.DEPTH_STENCIL;
  14278. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14279. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14280. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14281. if (texture.type !== UnsignedInt248Type) {
  14282. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14283. texture.type = UnsignedInt248Type;
  14284. glType = utils.convert(texture.type);
  14285. }
  14286. }
  14287. //
  14288. if (allocateMemory) {
  14289. if (useTexStorage) {
  14290. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  14291. } else {
  14292. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14293. }
  14294. }
  14295. } else if (texture.isDataTexture) {
  14296. // use manually created mipmaps if available
  14297. // if there are no manual mipmaps
  14298. // set 0 level mipmap and then use GL to generate other mipmap levels
  14299. if (mipmaps.length > 0 && supportsMips) {
  14300. if (useTexStorage && allocateMemory) {
  14301. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14302. }
  14303. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14304. mipmap = mipmaps[i];
  14305. if (useTexStorage) {
  14306. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14307. } else {
  14308. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14309. }
  14310. }
  14311. texture.generateMipmaps = false;
  14312. } else {
  14313. if (useTexStorage) {
  14314. if (allocateMemory) {
  14315. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14316. }
  14317. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  14318. } else {
  14319. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14320. }
  14321. }
  14322. } else if (texture.isCompressedTexture) {
  14323. if (texture.isCompressedArrayTexture) {
  14324. if (useTexStorage && allocateMemory) {
  14325. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth);
  14326. }
  14327. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14328. mipmap = mipmaps[i];
  14329. if (texture.format !== RGBAFormat) {
  14330. if (glFormat !== null) {
  14331. if (useTexStorage) {
  14332. state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0);
  14333. } else {
  14334. state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0);
  14335. }
  14336. } else {
  14337. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14338. }
  14339. } else {
  14340. if (useTexStorage) {
  14341. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data);
  14342. } else {
  14343. state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data);
  14344. }
  14345. }
  14346. }
  14347. } else {
  14348. if (useTexStorage && allocateMemory) {
  14349. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14350. }
  14351. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14352. mipmap = mipmaps[i];
  14353. if (texture.format !== RGBAFormat) {
  14354. if (glFormat !== null) {
  14355. if (useTexStorage) {
  14356. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14357. } else {
  14358. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14359. }
  14360. } else {
  14361. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14362. }
  14363. } else {
  14364. if (useTexStorage) {
  14365. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14366. } else {
  14367. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14368. }
  14369. }
  14370. }
  14371. }
  14372. } else if (texture.isDataArrayTexture) {
  14373. if (useTexStorage) {
  14374. if (allocateMemory) {
  14375. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  14376. }
  14377. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14378. } else {
  14379. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14380. }
  14381. } else if (texture.isData3DTexture) {
  14382. if (useTexStorage) {
  14383. if (allocateMemory) {
  14384. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  14385. }
  14386. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14387. } else {
  14388. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14389. }
  14390. } else if (texture.isFramebufferTexture) {
  14391. if (allocateMemory) {
  14392. if (useTexStorage) {
  14393. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14394. } else {
  14395. let width = image.width,
  14396. height = image.height;
  14397. for (let i = 0; i < levels; i++) {
  14398. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14399. width >>= 1;
  14400. height >>= 1;
  14401. }
  14402. }
  14403. }
  14404. } else {
  14405. // regular Texture (image, video, canvas)
  14406. // use manually created mipmaps if available
  14407. // if there are no manual mipmaps
  14408. // set 0 level mipmap and then use GL to generate other mipmap levels
  14409. if (mipmaps.length > 0 && supportsMips) {
  14410. if (useTexStorage && allocateMemory) {
  14411. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14412. }
  14413. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14414. mipmap = mipmaps[i];
  14415. if (useTexStorage) {
  14416. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14417. } else {
  14418. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14419. }
  14420. }
  14421. texture.generateMipmaps = false;
  14422. } else {
  14423. if (useTexStorage) {
  14424. if (allocateMemory) {
  14425. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14426. }
  14427. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14428. } else {
  14429. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14430. }
  14431. }
  14432. }
  14433. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14434. generateMipmap(textureType);
  14435. }
  14436. sourceProperties.__version = source.version;
  14437. if (texture.onUpdate) texture.onUpdate(texture);
  14438. }
  14439. textureProperties.__version = texture.version;
  14440. }
  14441. function uploadCubeTexture(textureProperties, texture, slot) {
  14442. if (texture.image.length !== 6) return;
  14443. const forceUpload = initTexture(textureProperties, texture);
  14444. const source = texture.source;
  14445. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14446. const sourceProperties = properties.get(source);
  14447. if (source.version !== sourceProperties.__version || forceUpload === true) {
  14448. state.activeTexture(_gl.TEXTURE0 + slot);
  14449. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14450. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14451. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14452. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14453. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14454. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14455. const cubeImage = [];
  14456. for (let i = 0; i < 6; i++) {
  14457. if (!isCompressed && !isDataTexture) {
  14458. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14459. } else {
  14460. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14461. }
  14462. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14463. }
  14464. const image = cubeImage[0],
  14465. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14466. glFormat = utils.convert(texture.format, texture.encoding),
  14467. glType = utils.convert(texture.type),
  14468. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14469. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14470. const allocateMemory = sourceProperties.__version === undefined || forceUpload === true;
  14471. let levels = getMipLevels(texture, image, supportsMips);
  14472. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14473. let mipmaps;
  14474. if (isCompressed) {
  14475. if (useTexStorage && allocateMemory) {
  14476. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14477. }
  14478. for (let i = 0; i < 6; i++) {
  14479. mipmaps = cubeImage[i].mipmaps;
  14480. for (let j = 0; j < mipmaps.length; j++) {
  14481. const mipmap = mipmaps[j];
  14482. if (texture.format !== RGBAFormat) {
  14483. if (glFormat !== null) {
  14484. if (useTexStorage) {
  14485. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14486. } else {
  14487. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14488. }
  14489. } else {
  14490. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14491. }
  14492. } else {
  14493. if (useTexStorage) {
  14494. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14495. } else {
  14496. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14497. }
  14498. }
  14499. }
  14500. }
  14501. } else {
  14502. mipmaps = texture.mipmaps;
  14503. if (useTexStorage && allocateMemory) {
  14504. // TODO: Uniformly handle mipmap definitions
  14505. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14506. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14507. if (mipmaps.length > 0) levels++;
  14508. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14509. }
  14510. for (let i = 0; i < 6; i++) {
  14511. if (isDataTexture) {
  14512. if (useTexStorage) {
  14513. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14514. } else {
  14515. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14516. }
  14517. for (let j = 0; j < mipmaps.length; j++) {
  14518. const mipmap = mipmaps[j];
  14519. const mipmapImage = mipmap.image[i].image;
  14520. if (useTexStorage) {
  14521. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14522. } else {
  14523. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14524. }
  14525. }
  14526. } else {
  14527. if (useTexStorage) {
  14528. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14529. } else {
  14530. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14531. }
  14532. for (let j = 0; j < mipmaps.length; j++) {
  14533. const mipmap = mipmaps[j];
  14534. if (useTexStorage) {
  14535. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14536. } else {
  14537. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14538. }
  14539. }
  14540. }
  14541. }
  14542. }
  14543. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14544. // We assume images for cube map have the same size.
  14545. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14546. }
  14547. sourceProperties.__version = source.version;
  14548. if (texture.onUpdate) texture.onUpdate(texture);
  14549. }
  14550. textureProperties.__version = texture.version;
  14551. }
  14552. // Render targets
  14553. // Setup storage for target texture and bind it to correct framebuffer
  14554. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14555. const glFormat = utils.convert(texture.format, texture.encoding);
  14556. const glType = utils.convert(texture.type);
  14557. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14558. const renderTargetProperties = properties.get(renderTarget);
  14559. if (!renderTargetProperties.__hasExternalTextures) {
  14560. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14561. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14562. } else {
  14563. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14564. }
  14565. }
  14566. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14567. if (useMultisampledRTT(renderTarget)) {
  14568. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14569. } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) {
  14570. // see #24753
  14571. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14572. }
  14573. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14574. }
  14575. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14576. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14577. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14578. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14579. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14580. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14581. const depthTexture = renderTarget.depthTexture;
  14582. if (depthTexture && depthTexture.isDepthTexture) {
  14583. if (depthTexture.type === FloatType) {
  14584. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14585. } else if (depthTexture.type === UnsignedIntType) {
  14586. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14587. }
  14588. }
  14589. const samples = getRenderTargetSamples(renderTarget);
  14590. if (useMultisampledRTT(renderTarget)) {
  14591. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14592. } else {
  14593. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14594. }
  14595. } else {
  14596. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14597. }
  14598. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14599. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14600. const samples = getRenderTargetSamples(renderTarget);
  14601. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14602. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14603. } else if (useMultisampledRTT(renderTarget)) {
  14604. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14605. } else {
  14606. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14607. }
  14608. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14609. } else {
  14610. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14611. for (let i = 0; i < textures.length; i++) {
  14612. const texture = textures[i];
  14613. const glFormat = utils.convert(texture.format, texture.encoding);
  14614. const glType = utils.convert(texture.type);
  14615. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14616. const samples = getRenderTargetSamples(renderTarget);
  14617. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14618. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14619. } else if (useMultisampledRTT(renderTarget)) {
  14620. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14621. } else {
  14622. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14623. }
  14624. }
  14625. }
  14626. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14627. }
  14628. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14629. function setupDepthTexture(framebuffer, renderTarget) {
  14630. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14631. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14632. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14633. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14634. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14635. }
  14636. // upload an empty depth texture with framebuffer size
  14637. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14638. renderTarget.depthTexture.image.width = renderTarget.width;
  14639. renderTarget.depthTexture.image.height = renderTarget.height;
  14640. renderTarget.depthTexture.needsUpdate = true;
  14641. }
  14642. setTexture2D(renderTarget.depthTexture, 0);
  14643. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14644. const samples = getRenderTargetSamples(renderTarget);
  14645. if (renderTarget.depthTexture.format === DepthFormat) {
  14646. if (useMultisampledRTT(renderTarget)) {
  14647. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14648. } else {
  14649. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14650. }
  14651. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14652. if (useMultisampledRTT(renderTarget)) {
  14653. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14654. } else {
  14655. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14656. }
  14657. } else {
  14658. throw new Error('Unknown depthTexture format');
  14659. }
  14660. }
  14661. // Setup GL resources for a non-texture depth buffer
  14662. function setupDepthRenderbuffer(renderTarget) {
  14663. const renderTargetProperties = properties.get(renderTarget);
  14664. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14665. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14666. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14667. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14668. } else {
  14669. if (isCube) {
  14670. renderTargetProperties.__webglDepthbuffer = [];
  14671. for (let i = 0; i < 6; i++) {
  14672. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14673. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14674. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14675. }
  14676. } else {
  14677. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14678. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14679. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14680. }
  14681. }
  14682. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14683. }
  14684. // rebind framebuffer with external textures
  14685. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14686. const renderTargetProperties = properties.get(renderTarget);
  14687. if (colorTexture !== undefined) {
  14688. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14689. }
  14690. if (depthTexture !== undefined) {
  14691. setupDepthRenderbuffer(renderTarget);
  14692. }
  14693. }
  14694. // Set up GL resources for the render target
  14695. function setupRenderTarget(renderTarget) {
  14696. const texture = renderTarget.texture;
  14697. const renderTargetProperties = properties.get(renderTarget);
  14698. const textureProperties = properties.get(texture);
  14699. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14700. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14701. if (textureProperties.__webglTexture === undefined) {
  14702. textureProperties.__webglTexture = _gl.createTexture();
  14703. }
  14704. textureProperties.__version = texture.version;
  14705. info.memory.textures++;
  14706. }
  14707. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14708. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14709. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14710. // Setup framebuffer
  14711. if (isCube) {
  14712. renderTargetProperties.__webglFramebuffer = [];
  14713. for (let i = 0; i < 6; i++) {
  14714. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14715. }
  14716. } else {
  14717. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14718. if (isMultipleRenderTargets) {
  14719. if (capabilities.drawBuffers) {
  14720. const textures = renderTarget.texture;
  14721. for (let i = 0, il = textures.length; i < il; i++) {
  14722. const attachmentProperties = properties.get(textures[i]);
  14723. if (attachmentProperties.__webglTexture === undefined) {
  14724. attachmentProperties.__webglTexture = _gl.createTexture();
  14725. info.memory.textures++;
  14726. }
  14727. }
  14728. } else {
  14729. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14730. }
  14731. }
  14732. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14733. const textures = isMultipleRenderTargets ? texture : [texture];
  14734. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14735. renderTargetProperties.__webglColorRenderbuffer = [];
  14736. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14737. for (let i = 0; i < textures.length; i++) {
  14738. const texture = textures[i];
  14739. renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer();
  14740. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14741. const glFormat = utils.convert(texture.format, texture.encoding);
  14742. const glType = utils.convert(texture.type);
  14743. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true);
  14744. const samples = getRenderTargetSamples(renderTarget);
  14745. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14746. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14747. }
  14748. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14749. if (renderTarget.depthBuffer) {
  14750. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14751. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14752. }
  14753. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14754. }
  14755. }
  14756. // Setup color buffer
  14757. if (isCube) {
  14758. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14759. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14760. for (let i = 0; i < 6; i++) {
  14761. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14762. }
  14763. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14764. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14765. }
  14766. state.unbindTexture();
  14767. } else if (isMultipleRenderTargets) {
  14768. const textures = renderTarget.texture;
  14769. for (let i = 0, il = textures.length; i < il; i++) {
  14770. const attachment = textures[i];
  14771. const attachmentProperties = properties.get(attachment);
  14772. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14773. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14774. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14775. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14776. generateMipmap(_gl.TEXTURE_2D);
  14777. }
  14778. }
  14779. state.unbindTexture();
  14780. } else {
  14781. let glTextureType = _gl.TEXTURE_2D;
  14782. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14783. if (isWebGL2) {
  14784. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14785. } else {
  14786. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14787. }
  14788. }
  14789. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14790. setTextureParameters(glTextureType, texture, supportsMips);
  14791. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14792. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14793. generateMipmap(glTextureType);
  14794. }
  14795. state.unbindTexture();
  14796. }
  14797. // Setup depth and stencil buffers
  14798. if (renderTarget.depthBuffer) {
  14799. setupDepthRenderbuffer(renderTarget);
  14800. }
  14801. }
  14802. function updateRenderTargetMipmap(renderTarget) {
  14803. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14804. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14805. for (let i = 0, il = textures.length; i < il; i++) {
  14806. const texture = textures[i];
  14807. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14808. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14809. const webglTexture = properties.get(texture).__webglTexture;
  14810. state.bindTexture(target, webglTexture);
  14811. generateMipmap(target);
  14812. state.unbindTexture();
  14813. }
  14814. }
  14815. }
  14816. function updateMultisampleRenderTarget(renderTarget) {
  14817. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14818. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture];
  14819. const width = renderTarget.width;
  14820. const height = renderTarget.height;
  14821. let mask = _gl.COLOR_BUFFER_BIT;
  14822. const invalidationArray = [];
  14823. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14824. const renderTargetProperties = properties.get(renderTarget);
  14825. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14826. // If MRT we need to remove FBO attachments
  14827. if (isMultipleRenderTargets) {
  14828. for (let i = 0; i < textures.length; i++) {
  14829. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14830. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null);
  14831. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14832. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0);
  14833. }
  14834. }
  14835. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14836. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14837. for (let i = 0; i < textures.length; i++) {
  14838. invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i);
  14839. if (renderTarget.depthBuffer) {
  14840. invalidationArray.push(depthStyle);
  14841. }
  14842. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14843. if (ignoreDepthValues === false) {
  14844. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14845. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14846. }
  14847. if (isMultipleRenderTargets) {
  14848. _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14849. }
  14850. if (ignoreDepthValues === true) {
  14851. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14852. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14853. }
  14854. if (isMultipleRenderTargets) {
  14855. const webglTexture = properties.get(textures[i]).__webglTexture;
  14856. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
  14857. }
  14858. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14859. if (supportsInvalidateFramebuffer) {
  14860. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14861. }
  14862. }
  14863. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14864. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null);
  14865. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14866. if (isMultipleRenderTargets) {
  14867. for (let i = 0; i < textures.length; i++) {
  14868. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14869. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14870. const webglTexture = properties.get(textures[i]).__webglTexture;
  14871. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14872. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0);
  14873. }
  14874. }
  14875. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14876. }
  14877. }
  14878. function getRenderTargetSamples(renderTarget) {
  14879. return Math.min(maxSamples, renderTarget.samples);
  14880. }
  14881. function useMultisampledRTT(renderTarget) {
  14882. const renderTargetProperties = properties.get(renderTarget);
  14883. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14884. }
  14885. function updateVideoTexture(texture) {
  14886. const frame = info.render.frame;
  14887. // Check the last frame we updated the VideoTexture
  14888. if (_videoTextures.get(texture) !== frame) {
  14889. _videoTextures.set(texture, frame);
  14890. texture.update();
  14891. }
  14892. }
  14893. function verifyColorSpace(texture, image) {
  14894. const encoding = texture.encoding;
  14895. const format = texture.format;
  14896. const type = texture.type;
  14897. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14898. if (encoding !== LinearEncoding) {
  14899. // sRGB
  14900. if (encoding === sRGBEncoding) {
  14901. if (isWebGL2 === false) {
  14902. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14903. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14904. texture.format = _SRGBAFormat;
  14905. // it's not possible to generate mips in WebGL 1 with this extension
  14906. texture.minFilter = LinearFilter;
  14907. texture.generateMipmaps = false;
  14908. } else {
  14909. // slow fallback (CPU decode)
  14910. image = ImageUtils.sRGBToLinear(image);
  14911. }
  14912. } else {
  14913. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14914. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14915. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14916. }
  14917. }
  14918. } else {
  14919. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14920. }
  14921. }
  14922. return image;
  14923. }
  14924. //
  14925. this.allocateTextureUnit = allocateTextureUnit;
  14926. this.resetTextureUnits = resetTextureUnits;
  14927. this.setTexture2D = setTexture2D;
  14928. this.setTexture2DArray = setTexture2DArray;
  14929. this.setTexture3D = setTexture3D;
  14930. this.setTextureCube = setTextureCube;
  14931. this.rebindTextures = rebindTextures;
  14932. this.setupRenderTarget = setupRenderTarget;
  14933. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14934. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14935. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14936. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14937. this.useMultisampledRTT = useMultisampledRTT;
  14938. }
  14939. function WebGLUtils(gl, extensions, capabilities) {
  14940. const isWebGL2 = capabilities.isWebGL2;
  14941. function convert(p, encoding = null) {
  14942. let extension;
  14943. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14944. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14945. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14946. if (p === ByteType) return gl.BYTE;
  14947. if (p === ShortType) return gl.SHORT;
  14948. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14949. if (p === IntType) return gl.INT;
  14950. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14951. if (p === FloatType) return gl.FLOAT;
  14952. if (p === HalfFloatType) {
  14953. if (isWebGL2) return gl.HALF_FLOAT;
  14954. extension = extensions.get('OES_texture_half_float');
  14955. if (extension !== null) {
  14956. return extension.HALF_FLOAT_OES;
  14957. } else {
  14958. return null;
  14959. }
  14960. }
  14961. if (p === AlphaFormat) return gl.ALPHA;
  14962. if (p === RGBAFormat) return gl.RGBA;
  14963. if (p === LuminanceFormat) return gl.LUMINANCE;
  14964. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14965. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14966. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14967. // @deprecated since r137
  14968. if (p === RGBFormat) {
  14969. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14970. return gl.RGBA;
  14971. }
  14972. // WebGL 1 sRGB fallback
  14973. if (p === _SRGBAFormat) {
  14974. extension = extensions.get('EXT_sRGB');
  14975. if (extension !== null) {
  14976. return extension.SRGB_ALPHA_EXT;
  14977. } else {
  14978. return null;
  14979. }
  14980. }
  14981. // WebGL2 formats.
  14982. if (p === RedFormat) return gl.RED;
  14983. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14984. if (p === RGFormat) return gl.RG;
  14985. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14986. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  14987. // S3TC
  14988. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14989. if (encoding === sRGBEncoding) {
  14990. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14991. if (extension !== null) {
  14992. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14993. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14994. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14995. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14996. } else {
  14997. return null;
  14998. }
  14999. } else {
  15000. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  15001. if (extension !== null) {
  15002. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15003. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15004. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15005. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15006. } else {
  15007. return null;
  15008. }
  15009. }
  15010. }
  15011. // PVRTC
  15012. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  15013. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  15014. if (extension !== null) {
  15015. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15016. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15017. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15018. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15019. } else {
  15020. return null;
  15021. }
  15022. }
  15023. // ETC1
  15024. if (p === RGB_ETC1_Format) {
  15025. extension = extensions.get('WEBGL_compressed_texture_etc1');
  15026. if (extension !== null) {
  15027. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15028. } else {
  15029. return null;
  15030. }
  15031. }
  15032. // ETC2
  15033. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  15034. extension = extensions.get('WEBGL_compressed_texture_etc');
  15035. if (extension !== null) {
  15036. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15037. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15038. } else {
  15039. return null;
  15040. }
  15041. }
  15042. // ASTC
  15043. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) {
  15044. extension = extensions.get('WEBGL_compressed_texture_astc');
  15045. if (extension !== null) {
  15046. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15047. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15048. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15049. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15050. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15051. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15052. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15053. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15054. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15055. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15056. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15057. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15058. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15059. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15060. } else {
  15061. return null;
  15062. }
  15063. }
  15064. // BPTC
  15065. if (p === RGBA_BPTC_Format) {
  15066. extension = extensions.get('EXT_texture_compression_bptc');
  15067. if (extension !== null) {
  15068. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15069. } else {
  15070. return null;
  15071. }
  15072. }
  15073. //
  15074. if (p === UnsignedInt248Type) {
  15075. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  15076. extension = extensions.get('WEBGL_depth_texture');
  15077. if (extension !== null) {
  15078. return extension.UNSIGNED_INT_24_8_WEBGL;
  15079. } else {
  15080. return null;
  15081. }
  15082. }
  15083. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15084. return gl[p] !== undefined ? gl[p] : null;
  15085. }
  15086. return {
  15087. convert: convert
  15088. };
  15089. }
  15090. class ArrayCamera extends PerspectiveCamera {
  15091. constructor(array = []) {
  15092. super();
  15093. this.isArrayCamera = true;
  15094. this.cameras = array;
  15095. }
  15096. }
  15097. class Group extends Object3D {
  15098. constructor() {
  15099. super();
  15100. this.isGroup = true;
  15101. this.type = 'Group';
  15102. }
  15103. }
  15104. const _moveEvent = {
  15105. type: 'move'
  15106. };
  15107. class WebXRController {
  15108. constructor() {
  15109. this._targetRay = null;
  15110. this._grip = null;
  15111. this._hand = null;
  15112. }
  15113. getHandSpace() {
  15114. if (this._hand === null) {
  15115. this._hand = new Group();
  15116. this._hand.matrixAutoUpdate = false;
  15117. this._hand.visible = false;
  15118. this._hand.joints = {};
  15119. this._hand.inputState = {
  15120. pinching: false
  15121. };
  15122. }
  15123. return this._hand;
  15124. }
  15125. getTargetRaySpace() {
  15126. if (this._targetRay === null) {
  15127. this._targetRay = new Group();
  15128. this._targetRay.matrixAutoUpdate = false;
  15129. this._targetRay.visible = false;
  15130. this._targetRay.hasLinearVelocity = false;
  15131. this._targetRay.linearVelocity = new Vector3();
  15132. this._targetRay.hasAngularVelocity = false;
  15133. this._targetRay.angularVelocity = new Vector3();
  15134. }
  15135. return this._targetRay;
  15136. }
  15137. getGripSpace() {
  15138. if (this._grip === null) {
  15139. this._grip = new Group();
  15140. this._grip.matrixAutoUpdate = false;
  15141. this._grip.visible = false;
  15142. this._grip.hasLinearVelocity = false;
  15143. this._grip.linearVelocity = new Vector3();
  15144. this._grip.hasAngularVelocity = false;
  15145. this._grip.angularVelocity = new Vector3();
  15146. }
  15147. return this._grip;
  15148. }
  15149. dispatchEvent(event) {
  15150. if (this._targetRay !== null) {
  15151. this._targetRay.dispatchEvent(event);
  15152. }
  15153. if (this._grip !== null) {
  15154. this._grip.dispatchEvent(event);
  15155. }
  15156. if (this._hand !== null) {
  15157. this._hand.dispatchEvent(event);
  15158. }
  15159. return this;
  15160. }
  15161. connect(inputSource) {
  15162. if (inputSource && inputSource.hand) {
  15163. const hand = this._hand;
  15164. if (hand) {
  15165. for (const inputjoint of inputSource.hand.values()) {
  15166. // Initialize hand with joints when connected
  15167. this._getHandJoint(hand, inputjoint);
  15168. }
  15169. }
  15170. }
  15171. this.dispatchEvent({
  15172. type: 'connected',
  15173. data: inputSource
  15174. });
  15175. return this;
  15176. }
  15177. disconnect(inputSource) {
  15178. this.dispatchEvent({
  15179. type: 'disconnected',
  15180. data: inputSource
  15181. });
  15182. if (this._targetRay !== null) {
  15183. this._targetRay.visible = false;
  15184. }
  15185. if (this._grip !== null) {
  15186. this._grip.visible = false;
  15187. }
  15188. if (this._hand !== null) {
  15189. this._hand.visible = false;
  15190. }
  15191. return this;
  15192. }
  15193. update(inputSource, frame, referenceSpace) {
  15194. let inputPose = null;
  15195. let gripPose = null;
  15196. let handPose = null;
  15197. const targetRay = this._targetRay;
  15198. const grip = this._grip;
  15199. const hand = this._hand;
  15200. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  15201. if (hand && inputSource.hand) {
  15202. handPose = true;
  15203. for (const inputjoint of inputSource.hand.values()) {
  15204. // Update the joints groups with the XRJoint poses
  15205. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  15206. // The transform of this joint will be updated with the joint pose on each frame
  15207. const joint = this._getHandJoint(hand, inputjoint);
  15208. if (jointPose !== null) {
  15209. joint.matrix.fromArray(jointPose.transform.matrix);
  15210. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  15211. joint.jointRadius = jointPose.radius;
  15212. }
  15213. joint.visible = jointPose !== null;
  15214. }
  15215. // Custom events
  15216. // Check pinchz
  15217. const indexTip = hand.joints['index-finger-tip'];
  15218. const thumbTip = hand.joints['thumb-tip'];
  15219. const distance = indexTip.position.distanceTo(thumbTip.position);
  15220. const distanceToPinch = 0.02;
  15221. const threshold = 0.005;
  15222. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  15223. hand.inputState.pinching = false;
  15224. this.dispatchEvent({
  15225. type: 'pinchend',
  15226. handedness: inputSource.handedness,
  15227. target: this
  15228. });
  15229. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  15230. hand.inputState.pinching = true;
  15231. this.dispatchEvent({
  15232. type: 'pinchstart',
  15233. handedness: inputSource.handedness,
  15234. target: this
  15235. });
  15236. }
  15237. } else {
  15238. if (grip !== null && inputSource.gripSpace) {
  15239. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  15240. if (gripPose !== null) {
  15241. grip.matrix.fromArray(gripPose.transform.matrix);
  15242. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  15243. if (gripPose.linearVelocity) {
  15244. grip.hasLinearVelocity = true;
  15245. grip.linearVelocity.copy(gripPose.linearVelocity);
  15246. } else {
  15247. grip.hasLinearVelocity = false;
  15248. }
  15249. if (gripPose.angularVelocity) {
  15250. grip.hasAngularVelocity = true;
  15251. grip.angularVelocity.copy(gripPose.angularVelocity);
  15252. } else {
  15253. grip.hasAngularVelocity = false;
  15254. }
  15255. }
  15256. }
  15257. }
  15258. if (targetRay !== null) {
  15259. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15260. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15261. if (inputPose === null && gripPose !== null) {
  15262. inputPose = gripPose;
  15263. }
  15264. if (inputPose !== null) {
  15265. targetRay.matrix.fromArray(inputPose.transform.matrix);
  15266. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  15267. if (inputPose.linearVelocity) {
  15268. targetRay.hasLinearVelocity = true;
  15269. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  15270. } else {
  15271. targetRay.hasLinearVelocity = false;
  15272. }
  15273. if (inputPose.angularVelocity) {
  15274. targetRay.hasAngularVelocity = true;
  15275. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  15276. } else {
  15277. targetRay.hasAngularVelocity = false;
  15278. }
  15279. this.dispatchEvent(_moveEvent);
  15280. }
  15281. }
  15282. }
  15283. if (targetRay !== null) {
  15284. targetRay.visible = inputPose !== null;
  15285. }
  15286. if (grip !== null) {
  15287. grip.visible = gripPose !== null;
  15288. }
  15289. if (hand !== null) {
  15290. hand.visible = handPose !== null;
  15291. }
  15292. return this;
  15293. }
  15294. // private method
  15295. _getHandJoint(hand, inputjoint) {
  15296. if (hand.joints[inputjoint.jointName] === undefined) {
  15297. const joint = new Group();
  15298. joint.matrixAutoUpdate = false;
  15299. joint.visible = false;
  15300. hand.joints[inputjoint.jointName] = joint;
  15301. hand.add(joint);
  15302. }
  15303. return hand.joints[inputjoint.jointName];
  15304. }
  15305. }
  15306. class DepthTexture extends Texture {
  15307. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  15308. format = format !== undefined ? format : DepthFormat;
  15309. if (format !== DepthFormat && format !== DepthStencilFormat) {
  15310. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  15311. }
  15312. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  15313. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  15314. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  15315. this.isDepthTexture = true;
  15316. this.image = {
  15317. width: width,
  15318. height: height
  15319. };
  15320. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15321. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15322. this.flipY = false;
  15323. this.generateMipmaps = false;
  15324. }
  15325. }
  15326. class WebXRManager extends EventDispatcher {
  15327. constructor(renderer, gl) {
  15328. super();
  15329. const scope = this;
  15330. let session = null;
  15331. let framebufferScaleFactor = 1.0;
  15332. let referenceSpace = null;
  15333. let referenceSpaceType = 'local-floor';
  15334. let customReferenceSpace = null;
  15335. let pose = null;
  15336. let glBinding = null;
  15337. let glProjLayer = null;
  15338. let glBaseLayer = null;
  15339. let xrFrame = null;
  15340. const attributes = gl.getContextAttributes();
  15341. let initialRenderTarget = null;
  15342. let newRenderTarget = null;
  15343. const controllers = [];
  15344. const controllerInputSources = [];
  15345. const planes = new Set();
  15346. const planesLastChangedTimes = new Map();
  15347. //
  15348. const cameraL = new PerspectiveCamera();
  15349. cameraL.layers.enable(1);
  15350. cameraL.viewport = new Vector4();
  15351. const cameraR = new PerspectiveCamera();
  15352. cameraR.layers.enable(2);
  15353. cameraR.viewport = new Vector4();
  15354. const cameras = [cameraL, cameraR];
  15355. const cameraVR = new ArrayCamera();
  15356. cameraVR.layers.enable(1);
  15357. cameraVR.layers.enable(2);
  15358. let _currentDepthNear = null;
  15359. let _currentDepthFar = null;
  15360. //
  15361. this.cameraAutoUpdate = true;
  15362. this.enabled = false;
  15363. this.isPresenting = false;
  15364. this.getController = function (index) {
  15365. let controller = controllers[index];
  15366. if (controller === undefined) {
  15367. controller = new WebXRController();
  15368. controllers[index] = controller;
  15369. }
  15370. return controller.getTargetRaySpace();
  15371. };
  15372. this.getControllerGrip = function (index) {
  15373. let controller = controllers[index];
  15374. if (controller === undefined) {
  15375. controller = new WebXRController();
  15376. controllers[index] = controller;
  15377. }
  15378. return controller.getGripSpace();
  15379. };
  15380. this.getHand = function (index) {
  15381. let controller = controllers[index];
  15382. if (controller === undefined) {
  15383. controller = new WebXRController();
  15384. controllers[index] = controller;
  15385. }
  15386. return controller.getHandSpace();
  15387. };
  15388. //
  15389. function onSessionEvent(event) {
  15390. const controllerIndex = controllerInputSources.indexOf(event.inputSource);
  15391. if (controllerIndex === -1) {
  15392. return;
  15393. }
  15394. const controller = controllers[controllerIndex];
  15395. if (controller !== undefined) {
  15396. controller.dispatchEvent({
  15397. type: event.type,
  15398. data: event.inputSource
  15399. });
  15400. }
  15401. }
  15402. function onSessionEnd() {
  15403. session.removeEventListener('select', onSessionEvent);
  15404. session.removeEventListener('selectstart', onSessionEvent);
  15405. session.removeEventListener('selectend', onSessionEvent);
  15406. session.removeEventListener('squeeze', onSessionEvent);
  15407. session.removeEventListener('squeezestart', onSessionEvent);
  15408. session.removeEventListener('squeezeend', onSessionEvent);
  15409. session.removeEventListener('end', onSessionEnd);
  15410. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  15411. for (let i = 0; i < controllers.length; i++) {
  15412. const inputSource = controllerInputSources[i];
  15413. if (inputSource === null) continue;
  15414. controllerInputSources[i] = null;
  15415. controllers[i].disconnect(inputSource);
  15416. }
  15417. _currentDepthNear = null;
  15418. _currentDepthFar = null;
  15419. // restore framebuffer/rendering state
  15420. renderer.setRenderTarget(initialRenderTarget);
  15421. glBaseLayer = null;
  15422. glProjLayer = null;
  15423. glBinding = null;
  15424. session = null;
  15425. newRenderTarget = null;
  15426. //
  15427. animation.stop();
  15428. scope.isPresenting = false;
  15429. scope.dispatchEvent({
  15430. type: 'sessionend'
  15431. });
  15432. }
  15433. this.setFramebufferScaleFactor = function (value) {
  15434. framebufferScaleFactor = value;
  15435. if (scope.isPresenting === true) {
  15436. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  15437. }
  15438. };
  15439. this.setReferenceSpaceType = function (value) {
  15440. referenceSpaceType = value;
  15441. if (scope.isPresenting === true) {
  15442. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  15443. }
  15444. };
  15445. this.getReferenceSpace = function () {
  15446. return customReferenceSpace || referenceSpace;
  15447. };
  15448. this.setReferenceSpace = function (space) {
  15449. customReferenceSpace = space;
  15450. };
  15451. this.getBaseLayer = function () {
  15452. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15453. };
  15454. this.getBinding = function () {
  15455. return glBinding;
  15456. };
  15457. this.getFrame = function () {
  15458. return xrFrame;
  15459. };
  15460. this.getSession = function () {
  15461. return session;
  15462. };
  15463. this.setSession = async function (value) {
  15464. session = value;
  15465. if (session !== null) {
  15466. initialRenderTarget = renderer.getRenderTarget();
  15467. session.addEventListener('select', onSessionEvent);
  15468. session.addEventListener('selectstart', onSessionEvent);
  15469. session.addEventListener('selectend', onSessionEvent);
  15470. session.addEventListener('squeeze', onSessionEvent);
  15471. session.addEventListener('squeezestart', onSessionEvent);
  15472. session.addEventListener('squeezeend', onSessionEvent);
  15473. session.addEventListener('end', onSessionEnd);
  15474. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15475. if (attributes.xrCompatible !== true) {
  15476. await gl.makeXRCompatible();
  15477. }
  15478. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15479. const layerInit = {
  15480. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15481. alpha: attributes.alpha,
  15482. depth: attributes.depth,
  15483. stencil: attributes.stencil,
  15484. framebufferScaleFactor: framebufferScaleFactor
  15485. };
  15486. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15487. session.updateRenderState({
  15488. baseLayer: glBaseLayer
  15489. });
  15490. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15491. format: RGBAFormat,
  15492. type: UnsignedByteType,
  15493. encoding: renderer.outputEncoding,
  15494. stencilBuffer: attributes.stencil
  15495. });
  15496. } else {
  15497. let depthFormat = null;
  15498. let depthType = null;
  15499. let glDepthFormat = null;
  15500. if (attributes.depth) {
  15501. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15502. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15503. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15504. }
  15505. const projectionlayerInit = {
  15506. colorFormat: gl.RGBA8,
  15507. depthFormat: glDepthFormat,
  15508. scaleFactor: framebufferScaleFactor
  15509. };
  15510. glBinding = new XRWebGLBinding(session, gl);
  15511. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15512. session.updateRenderState({
  15513. layers: [glProjLayer]
  15514. });
  15515. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15516. format: RGBAFormat,
  15517. type: UnsignedByteType,
  15518. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15519. stencilBuffer: attributes.stencil,
  15520. encoding: renderer.outputEncoding,
  15521. samples: attributes.antialias ? 4 : 0
  15522. });
  15523. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15524. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15525. }
  15526. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15527. // Set foveation to maximum.
  15528. this.setFoveation(1.0);
  15529. customReferenceSpace = null;
  15530. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15531. animation.setContext(session);
  15532. animation.start();
  15533. scope.isPresenting = true;
  15534. scope.dispatchEvent({
  15535. type: 'sessionstart'
  15536. });
  15537. }
  15538. };
  15539. function onInputSourcesChange(event) {
  15540. // Notify disconnected
  15541. for (let i = 0; i < event.removed.length; i++) {
  15542. const inputSource = event.removed[i];
  15543. const index = controllerInputSources.indexOf(inputSource);
  15544. if (index >= 0) {
  15545. controllerInputSources[index] = null;
  15546. controllers[index].disconnect(inputSource);
  15547. }
  15548. }
  15549. // Notify connected
  15550. for (let i = 0; i < event.added.length; i++) {
  15551. const inputSource = event.added[i];
  15552. let controllerIndex = controllerInputSources.indexOf(inputSource);
  15553. if (controllerIndex === -1) {
  15554. // Assign input source a controller that currently has no input source
  15555. for (let i = 0; i < controllers.length; i++) {
  15556. if (i >= controllerInputSources.length) {
  15557. controllerInputSources.push(inputSource);
  15558. controllerIndex = i;
  15559. break;
  15560. } else if (controllerInputSources[i] === null) {
  15561. controllerInputSources[i] = inputSource;
  15562. controllerIndex = i;
  15563. break;
  15564. }
  15565. }
  15566. // If all controllers do currently receive input we ignore new ones
  15567. if (controllerIndex === -1) break;
  15568. }
  15569. const controller = controllers[controllerIndex];
  15570. if (controller) {
  15571. controller.connect(inputSource);
  15572. }
  15573. }
  15574. }
  15575. //
  15576. const cameraLPos = new Vector3();
  15577. const cameraRPos = new Vector3();
  15578. /**
  15579. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15580. * the cameras' projection and world matrices have already been set.
  15581. * And that near and far planes are identical for both cameras.
  15582. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15583. */
  15584. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15585. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15586. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15587. const ipd = cameraLPos.distanceTo(cameraRPos);
  15588. const projL = cameraL.projectionMatrix.elements;
  15589. const projR = cameraR.projectionMatrix.elements;
  15590. // VR systems will have identical far and near planes, and
  15591. // most likely identical top and bottom frustum extents.
  15592. // Use the left camera for these values.
  15593. const near = projL[14] / (projL[10] - 1);
  15594. const far = projL[14] / (projL[10] + 1);
  15595. const topFov = (projL[9] + 1) / projL[5];
  15596. const bottomFov = (projL[9] - 1) / projL[5];
  15597. const leftFov = (projL[8] - 1) / projL[0];
  15598. const rightFov = (projR[8] + 1) / projR[0];
  15599. const left = near * leftFov;
  15600. const right = near * rightFov;
  15601. // Calculate the new camera's position offset from the
  15602. // left camera. xOffset should be roughly half `ipd`.
  15603. const zOffset = ipd / (-leftFov + rightFov);
  15604. const xOffset = zOffset * -leftFov;
  15605. // TODO: Better way to apply this offset?
  15606. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15607. camera.translateX(xOffset);
  15608. camera.translateZ(zOffset);
  15609. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15610. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15611. // Find the union of the frustum values of the cameras and scale
  15612. // the values so that the near plane's position does not change in world space,
  15613. // although must now be relative to the new union camera.
  15614. const near2 = near + zOffset;
  15615. const far2 = far + zOffset;
  15616. const left2 = left - xOffset;
  15617. const right2 = right + (ipd - xOffset);
  15618. const top2 = topFov * far / far2 * near2;
  15619. const bottom2 = bottomFov * far / far2 * near2;
  15620. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15621. }
  15622. function updateCamera(camera, parent) {
  15623. if (parent === null) {
  15624. camera.matrixWorld.copy(camera.matrix);
  15625. } else {
  15626. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15627. }
  15628. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15629. }
  15630. this.updateCamera = function (camera) {
  15631. if (session === null) return;
  15632. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15633. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15634. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15635. // Note that the new renderState won't apply until the next frame. See #18320
  15636. session.updateRenderState({
  15637. depthNear: cameraVR.near,
  15638. depthFar: cameraVR.far
  15639. });
  15640. _currentDepthNear = cameraVR.near;
  15641. _currentDepthFar = cameraVR.far;
  15642. }
  15643. const parent = camera.parent;
  15644. const cameras = cameraVR.cameras;
  15645. updateCamera(cameraVR, parent);
  15646. for (let i = 0; i < cameras.length; i++) {
  15647. updateCamera(cameras[i], parent);
  15648. }
  15649. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale);
  15650. // update user camera and its children
  15651. camera.matrix.copy(cameraVR.matrix);
  15652. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  15653. const children = camera.children;
  15654. for (let i = 0, l = children.length; i < l; i++) {
  15655. children[i].updateMatrixWorld(true);
  15656. }
  15657. // update projection matrix for proper view frustum culling
  15658. if (cameras.length === 2) {
  15659. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15660. } else {
  15661. // assume single camera setup (AR)
  15662. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  15663. }
  15664. };
  15665. this.getCamera = function () {
  15666. return cameraVR;
  15667. };
  15668. this.getFoveation = function () {
  15669. if (glProjLayer !== null) {
  15670. return glProjLayer.fixedFoveation;
  15671. }
  15672. if (glBaseLayer !== null) {
  15673. return glBaseLayer.fixedFoveation;
  15674. }
  15675. return undefined;
  15676. };
  15677. this.setFoveation = function (foveation) {
  15678. // 0 = no foveation = full resolution
  15679. // 1 = maximum foveation = the edges render at lower resolution
  15680. if (glProjLayer !== null) {
  15681. glProjLayer.fixedFoveation = foveation;
  15682. }
  15683. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15684. glBaseLayer.fixedFoveation = foveation;
  15685. }
  15686. };
  15687. this.getPlanes = function () {
  15688. return planes;
  15689. };
  15690. // Animation Loop
  15691. let onAnimationFrameCallback = null;
  15692. function onAnimationFrame(time, frame) {
  15693. pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
  15694. xrFrame = frame;
  15695. if (pose !== null) {
  15696. const views = pose.views;
  15697. if (glBaseLayer !== null) {
  15698. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15699. renderer.setRenderTarget(newRenderTarget);
  15700. }
  15701. let cameraVRNeedsUpdate = false;
  15702. // check if it's necessary to rebuild cameraVR's camera list
  15703. if (views.length !== cameraVR.cameras.length) {
  15704. cameraVR.cameras.length = 0;
  15705. cameraVRNeedsUpdate = true;
  15706. }
  15707. for (let i = 0; i < views.length; i++) {
  15708. const view = views[i];
  15709. let viewport = null;
  15710. if (glBaseLayer !== null) {
  15711. viewport = glBaseLayer.getViewport(view);
  15712. } else {
  15713. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15714. viewport = glSubImage.viewport;
  15715. // For side-by-side projection, we only produce a single texture for both eyes.
  15716. if (i === 0) {
  15717. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15718. renderer.setRenderTarget(newRenderTarget);
  15719. }
  15720. }
  15721. let camera = cameras[i];
  15722. if (camera === undefined) {
  15723. camera = new PerspectiveCamera();
  15724. camera.layers.enable(i);
  15725. camera.viewport = new Vector4();
  15726. cameras[i] = camera;
  15727. }
  15728. camera.matrix.fromArray(view.transform.matrix);
  15729. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15730. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15731. if (i === 0) {
  15732. cameraVR.matrix.copy(camera.matrix);
  15733. }
  15734. if (cameraVRNeedsUpdate === true) {
  15735. cameraVR.cameras.push(camera);
  15736. }
  15737. }
  15738. }
  15739. //
  15740. for (let i = 0; i < controllers.length; i++) {
  15741. const inputSource = controllerInputSources[i];
  15742. const controller = controllers[i];
  15743. if (inputSource !== null && controller !== undefined) {
  15744. controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
  15745. }
  15746. }
  15747. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15748. if (frame.detectedPlanes) {
  15749. scope.dispatchEvent({
  15750. type: 'planesdetected',
  15751. data: frame.detectedPlanes
  15752. });
  15753. let planesToRemove = null;
  15754. for (const plane of planes) {
  15755. if (!frame.detectedPlanes.has(plane)) {
  15756. if (planesToRemove === null) {
  15757. planesToRemove = [];
  15758. }
  15759. planesToRemove.push(plane);
  15760. }
  15761. }
  15762. if (planesToRemove !== null) {
  15763. for (const plane of planesToRemove) {
  15764. planes.delete(plane);
  15765. planesLastChangedTimes.delete(plane);
  15766. scope.dispatchEvent({
  15767. type: 'planeremoved',
  15768. data: plane
  15769. });
  15770. }
  15771. }
  15772. for (const plane of frame.detectedPlanes) {
  15773. if (!planes.has(plane)) {
  15774. planes.add(plane);
  15775. planesLastChangedTimes.set(plane, frame.lastChangedTime);
  15776. scope.dispatchEvent({
  15777. type: 'planeadded',
  15778. data: plane
  15779. });
  15780. } else {
  15781. const lastKnownTime = planesLastChangedTimes.get(plane);
  15782. if (plane.lastChangedTime > lastKnownTime) {
  15783. planesLastChangedTimes.set(plane, plane.lastChangedTime);
  15784. scope.dispatchEvent({
  15785. type: 'planechanged',
  15786. data: plane
  15787. });
  15788. }
  15789. }
  15790. }
  15791. }
  15792. xrFrame = null;
  15793. }
  15794. const animation = new WebGLAnimation();
  15795. animation.setAnimationLoop(onAnimationFrame);
  15796. this.setAnimationLoop = function (callback) {
  15797. onAnimationFrameCallback = callback;
  15798. };
  15799. this.dispose = function () {};
  15800. }
  15801. }
  15802. function WebGLMaterials(renderer, properties) {
  15803. function refreshFogUniforms(uniforms, fog) {
  15804. fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer));
  15805. if (fog.isFog) {
  15806. uniforms.fogNear.value = fog.near;
  15807. uniforms.fogFar.value = fog.far;
  15808. } else if (fog.isFogExp2) {
  15809. uniforms.fogDensity.value = fog.density;
  15810. }
  15811. }
  15812. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15813. if (material.isMeshBasicMaterial) {
  15814. refreshUniformsCommon(uniforms, material);
  15815. } else if (material.isMeshLambertMaterial) {
  15816. refreshUniformsCommon(uniforms, material);
  15817. } else if (material.isMeshToonMaterial) {
  15818. refreshUniformsCommon(uniforms, material);
  15819. refreshUniformsToon(uniforms, material);
  15820. } else if (material.isMeshPhongMaterial) {
  15821. refreshUniformsCommon(uniforms, material);
  15822. refreshUniformsPhong(uniforms, material);
  15823. } else if (material.isMeshStandardMaterial) {
  15824. refreshUniformsCommon(uniforms, material);
  15825. refreshUniformsStandard(uniforms, material);
  15826. if (material.isMeshPhysicalMaterial) {
  15827. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15828. }
  15829. } else if (material.isMeshMatcapMaterial) {
  15830. refreshUniformsCommon(uniforms, material);
  15831. refreshUniformsMatcap(uniforms, material);
  15832. } else if (material.isMeshDepthMaterial) {
  15833. refreshUniformsCommon(uniforms, material);
  15834. } else if (material.isMeshDistanceMaterial) {
  15835. refreshUniformsCommon(uniforms, material);
  15836. refreshUniformsDistance(uniforms, material);
  15837. } else if (material.isMeshNormalMaterial) {
  15838. refreshUniformsCommon(uniforms, material);
  15839. } else if (material.isLineBasicMaterial) {
  15840. refreshUniformsLine(uniforms, material);
  15841. if (material.isLineDashedMaterial) {
  15842. refreshUniformsDash(uniforms, material);
  15843. }
  15844. } else if (material.isPointsMaterial) {
  15845. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15846. } else if (material.isSpriteMaterial) {
  15847. refreshUniformsSprites(uniforms, material);
  15848. } else if (material.isShadowMaterial) {
  15849. uniforms.color.value.copy(material.color);
  15850. uniforms.opacity.value = material.opacity;
  15851. } else if (material.isShaderMaterial) {
  15852. material.uniformsNeedUpdate = false; // #15581
  15853. }
  15854. }
  15855. function refreshUniformsCommon(uniforms, material) {
  15856. uniforms.opacity.value = material.opacity;
  15857. if (material.color) {
  15858. uniforms.diffuse.value.copy(material.color);
  15859. }
  15860. if (material.emissive) {
  15861. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15862. }
  15863. if (material.map) {
  15864. uniforms.map.value = material.map;
  15865. }
  15866. if (material.alphaMap) {
  15867. uniforms.alphaMap.value = material.alphaMap;
  15868. }
  15869. if (material.bumpMap) {
  15870. uniforms.bumpMap.value = material.bumpMap;
  15871. uniforms.bumpScale.value = material.bumpScale;
  15872. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15873. }
  15874. if (material.displacementMap) {
  15875. uniforms.displacementMap.value = material.displacementMap;
  15876. uniforms.displacementScale.value = material.displacementScale;
  15877. uniforms.displacementBias.value = material.displacementBias;
  15878. }
  15879. if (material.emissiveMap) {
  15880. uniforms.emissiveMap.value = material.emissiveMap;
  15881. }
  15882. if (material.normalMap) {
  15883. uniforms.normalMap.value = material.normalMap;
  15884. uniforms.normalScale.value.copy(material.normalScale);
  15885. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15886. }
  15887. if (material.specularMap) {
  15888. uniforms.specularMap.value = material.specularMap;
  15889. }
  15890. if (material.alphaTest > 0) {
  15891. uniforms.alphaTest.value = material.alphaTest;
  15892. }
  15893. const envMap = properties.get(material).envMap;
  15894. if (envMap) {
  15895. uniforms.envMap.value = envMap;
  15896. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15897. uniforms.reflectivity.value = material.reflectivity;
  15898. uniforms.ior.value = material.ior;
  15899. uniforms.refractionRatio.value = material.refractionRatio;
  15900. }
  15901. if (material.lightMap) {
  15902. uniforms.lightMap.value = material.lightMap;
  15903. // artist-friendly light intensity scaling factor
  15904. const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1;
  15905. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15906. }
  15907. if (material.aoMap) {
  15908. uniforms.aoMap.value = material.aoMap;
  15909. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15910. }
  15911. // uv repeat and offset setting priorities
  15912. // 1. color map
  15913. // 2. specular map
  15914. // 3. displacementMap map
  15915. // 4. normal map
  15916. // 5. bump map
  15917. // 6. roughnessMap map
  15918. // 7. metalnessMap map
  15919. // 8. alphaMap map
  15920. // 9. emissiveMap map
  15921. // 10. clearcoat map
  15922. // 11. clearcoat normal map
  15923. // 12. clearcoat roughnessMap map
  15924. // 13. iridescence map
  15925. // 14. iridescence thickness map
  15926. // 15. specular intensity map
  15927. // 16. specular tint map
  15928. // 17. transmission map
  15929. // 18. thickness map
  15930. let uvScaleMap;
  15931. if (material.map) {
  15932. uvScaleMap = material.map;
  15933. } else if (material.specularMap) {
  15934. uvScaleMap = material.specularMap;
  15935. } else if (material.displacementMap) {
  15936. uvScaleMap = material.displacementMap;
  15937. } else if (material.normalMap) {
  15938. uvScaleMap = material.normalMap;
  15939. } else if (material.bumpMap) {
  15940. uvScaleMap = material.bumpMap;
  15941. } else if (material.roughnessMap) {
  15942. uvScaleMap = material.roughnessMap;
  15943. } else if (material.metalnessMap) {
  15944. uvScaleMap = material.metalnessMap;
  15945. } else if (material.alphaMap) {
  15946. uvScaleMap = material.alphaMap;
  15947. } else if (material.emissiveMap) {
  15948. uvScaleMap = material.emissiveMap;
  15949. } else if (material.clearcoatMap) {
  15950. uvScaleMap = material.clearcoatMap;
  15951. } else if (material.clearcoatNormalMap) {
  15952. uvScaleMap = material.clearcoatNormalMap;
  15953. } else if (material.clearcoatRoughnessMap) {
  15954. uvScaleMap = material.clearcoatRoughnessMap;
  15955. } else if (material.iridescenceMap) {
  15956. uvScaleMap = material.iridescenceMap;
  15957. } else if (material.iridescenceThicknessMap) {
  15958. uvScaleMap = material.iridescenceThicknessMap;
  15959. } else if (material.specularIntensityMap) {
  15960. uvScaleMap = material.specularIntensityMap;
  15961. } else if (material.specularColorMap) {
  15962. uvScaleMap = material.specularColorMap;
  15963. } else if (material.transmissionMap) {
  15964. uvScaleMap = material.transmissionMap;
  15965. } else if (material.thicknessMap) {
  15966. uvScaleMap = material.thicknessMap;
  15967. } else if (material.sheenColorMap) {
  15968. uvScaleMap = material.sheenColorMap;
  15969. } else if (material.sheenRoughnessMap) {
  15970. uvScaleMap = material.sheenRoughnessMap;
  15971. }
  15972. if (uvScaleMap !== undefined) {
  15973. // backwards compatibility
  15974. if (uvScaleMap.isWebGLRenderTarget) {
  15975. uvScaleMap = uvScaleMap.texture;
  15976. }
  15977. if (uvScaleMap.matrixAutoUpdate === true) {
  15978. uvScaleMap.updateMatrix();
  15979. }
  15980. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15981. }
  15982. // uv repeat and offset setting priorities for uv2
  15983. // 1. ao map
  15984. // 2. light map
  15985. let uv2ScaleMap;
  15986. if (material.aoMap) {
  15987. uv2ScaleMap = material.aoMap;
  15988. } else if (material.lightMap) {
  15989. uv2ScaleMap = material.lightMap;
  15990. }
  15991. if (uv2ScaleMap !== undefined) {
  15992. // backwards compatibility
  15993. if (uv2ScaleMap.isWebGLRenderTarget) {
  15994. uv2ScaleMap = uv2ScaleMap.texture;
  15995. }
  15996. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15997. uv2ScaleMap.updateMatrix();
  15998. }
  15999. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  16000. }
  16001. }
  16002. function refreshUniformsLine(uniforms, material) {
  16003. uniforms.diffuse.value.copy(material.color);
  16004. uniforms.opacity.value = material.opacity;
  16005. }
  16006. function refreshUniformsDash(uniforms, material) {
  16007. uniforms.dashSize.value = material.dashSize;
  16008. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16009. uniforms.scale.value = material.scale;
  16010. }
  16011. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  16012. uniforms.diffuse.value.copy(material.color);
  16013. uniforms.opacity.value = material.opacity;
  16014. uniforms.size.value = material.size * pixelRatio;
  16015. uniforms.scale.value = height * 0.5;
  16016. if (material.map) {
  16017. uniforms.map.value = material.map;
  16018. }
  16019. if (material.alphaMap) {
  16020. uniforms.alphaMap.value = material.alphaMap;
  16021. }
  16022. if (material.alphaTest > 0) {
  16023. uniforms.alphaTest.value = material.alphaTest;
  16024. }
  16025. // uv repeat and offset setting priorities
  16026. // 1. color map
  16027. // 2. alpha map
  16028. let uvScaleMap;
  16029. if (material.map) {
  16030. uvScaleMap = material.map;
  16031. } else if (material.alphaMap) {
  16032. uvScaleMap = material.alphaMap;
  16033. }
  16034. if (uvScaleMap !== undefined) {
  16035. if (uvScaleMap.matrixAutoUpdate === true) {
  16036. uvScaleMap.updateMatrix();
  16037. }
  16038. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16039. }
  16040. }
  16041. function refreshUniformsSprites(uniforms, material) {
  16042. uniforms.diffuse.value.copy(material.color);
  16043. uniforms.opacity.value = material.opacity;
  16044. uniforms.rotation.value = material.rotation;
  16045. if (material.map) {
  16046. uniforms.map.value = material.map;
  16047. }
  16048. if (material.alphaMap) {
  16049. uniforms.alphaMap.value = material.alphaMap;
  16050. }
  16051. if (material.alphaTest > 0) {
  16052. uniforms.alphaTest.value = material.alphaTest;
  16053. }
  16054. // uv repeat and offset setting priorities
  16055. // 1. color map
  16056. // 2. alpha map
  16057. let uvScaleMap;
  16058. if (material.map) {
  16059. uvScaleMap = material.map;
  16060. } else if (material.alphaMap) {
  16061. uvScaleMap = material.alphaMap;
  16062. }
  16063. if (uvScaleMap !== undefined) {
  16064. if (uvScaleMap.matrixAutoUpdate === true) {
  16065. uvScaleMap.updateMatrix();
  16066. }
  16067. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16068. }
  16069. }
  16070. function refreshUniformsPhong(uniforms, material) {
  16071. uniforms.specular.value.copy(material.specular);
  16072. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16073. }
  16074. function refreshUniformsToon(uniforms, material) {
  16075. if (material.gradientMap) {
  16076. uniforms.gradientMap.value = material.gradientMap;
  16077. }
  16078. }
  16079. function refreshUniformsStandard(uniforms, material) {
  16080. uniforms.roughness.value = material.roughness;
  16081. uniforms.metalness.value = material.metalness;
  16082. if (material.roughnessMap) {
  16083. uniforms.roughnessMap.value = material.roughnessMap;
  16084. }
  16085. if (material.metalnessMap) {
  16086. uniforms.metalnessMap.value = material.metalnessMap;
  16087. }
  16088. const envMap = properties.get(material).envMap;
  16089. if (envMap) {
  16090. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16091. uniforms.envMapIntensity.value = material.envMapIntensity;
  16092. }
  16093. }
  16094. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  16095. uniforms.ior.value = material.ior; // also part of uniforms common
  16096. if (material.sheen > 0) {
  16097. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  16098. uniforms.sheenRoughness.value = material.sheenRoughness;
  16099. if (material.sheenColorMap) {
  16100. uniforms.sheenColorMap.value = material.sheenColorMap;
  16101. }
  16102. if (material.sheenRoughnessMap) {
  16103. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16104. }
  16105. }
  16106. if (material.clearcoat > 0) {
  16107. uniforms.clearcoat.value = material.clearcoat;
  16108. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16109. if (material.clearcoatMap) {
  16110. uniforms.clearcoatMap.value = material.clearcoatMap;
  16111. }
  16112. if (material.clearcoatRoughnessMap) {
  16113. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16114. }
  16115. if (material.clearcoatNormalMap) {
  16116. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16117. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16118. if (material.side === BackSide) {
  16119. uniforms.clearcoatNormalScale.value.negate();
  16120. }
  16121. }
  16122. }
  16123. if (material.iridescence > 0) {
  16124. uniforms.iridescence.value = material.iridescence;
  16125. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16126. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0];
  16127. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1];
  16128. if (material.iridescenceMap) {
  16129. uniforms.iridescenceMap.value = material.iridescenceMap;
  16130. }
  16131. if (material.iridescenceThicknessMap) {
  16132. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16133. }
  16134. }
  16135. if (material.transmission > 0) {
  16136. uniforms.transmission.value = material.transmission;
  16137. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16138. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  16139. if (material.transmissionMap) {
  16140. uniforms.transmissionMap.value = material.transmissionMap;
  16141. }
  16142. uniforms.thickness.value = material.thickness;
  16143. if (material.thicknessMap) {
  16144. uniforms.thicknessMap.value = material.thicknessMap;
  16145. }
  16146. uniforms.attenuationDistance.value = material.attenuationDistance;
  16147. uniforms.attenuationColor.value.copy(material.attenuationColor);
  16148. }
  16149. uniforms.specularIntensity.value = material.specularIntensity;
  16150. uniforms.specularColor.value.copy(material.specularColor);
  16151. if (material.specularIntensityMap) {
  16152. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16153. }
  16154. if (material.specularColorMap) {
  16155. uniforms.specularColorMap.value = material.specularColorMap;
  16156. }
  16157. }
  16158. function refreshUniformsMatcap(uniforms, material) {
  16159. if (material.matcap) {
  16160. uniforms.matcap.value = material.matcap;
  16161. }
  16162. }
  16163. function refreshUniformsDistance(uniforms, material) {
  16164. uniforms.referencePosition.value.copy(material.referencePosition);
  16165. uniforms.nearDistance.value = material.nearDistance;
  16166. uniforms.farDistance.value = material.farDistance;
  16167. }
  16168. return {
  16169. refreshFogUniforms: refreshFogUniforms,
  16170. refreshMaterialUniforms: refreshMaterialUniforms
  16171. };
  16172. }
  16173. function WebGLUniformsGroups(gl, info, capabilities, state) {
  16174. let buffers = {};
  16175. let updateList = {};
  16176. let allocatedBindingPoints = [];
  16177. const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; // binding points are global whereas block indices are per shader program
  16178. function bind(uniformsGroup, program) {
  16179. const webglProgram = program.program;
  16180. state.uniformBlockBinding(uniformsGroup, webglProgram);
  16181. }
  16182. function update(uniformsGroup, program) {
  16183. let buffer = buffers[uniformsGroup.id];
  16184. if (buffer === undefined) {
  16185. prepareUniformsGroup(uniformsGroup);
  16186. buffer = createBuffer(uniformsGroup);
  16187. buffers[uniformsGroup.id] = buffer;
  16188. uniformsGroup.addEventListener('dispose', onUniformsGroupsDispose);
  16189. }
  16190. // ensure to update the binding points/block indices mapping for this program
  16191. const webglProgram = program.program;
  16192. state.updateUBOMapping(uniformsGroup, webglProgram);
  16193. // update UBO once per frame
  16194. const frame = info.render.frame;
  16195. if (updateList[uniformsGroup.id] !== frame) {
  16196. updateBufferData(uniformsGroup);
  16197. updateList[uniformsGroup.id] = frame;
  16198. }
  16199. }
  16200. function createBuffer(uniformsGroup) {
  16201. // the setup of an UBO is independent of a particular shader program but global
  16202. const bindingPointIndex = allocateBindingPointIndex();
  16203. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16204. const buffer = gl.createBuffer();
  16205. const size = uniformsGroup.__size;
  16206. const usage = uniformsGroup.usage;
  16207. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  16208. gl.bufferData(gl.UNIFORM_BUFFER, size, usage);
  16209. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  16210. gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer);
  16211. return buffer;
  16212. }
  16213. function allocateBindingPointIndex() {
  16214. for (let i = 0; i < maxBindingPoints; i++) {
  16215. if (allocatedBindingPoints.indexOf(i) === -1) {
  16216. allocatedBindingPoints.push(i);
  16217. return i;
  16218. }
  16219. }
  16220. console.error('THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.');
  16221. return 0;
  16222. }
  16223. function updateBufferData(uniformsGroup) {
  16224. const buffer = buffers[uniformsGroup.id];
  16225. const uniforms = uniformsGroup.uniforms;
  16226. const cache = uniformsGroup.__cache;
  16227. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  16228. for (let i = 0, il = uniforms.length; i < il; i++) {
  16229. const uniform = uniforms[i];
  16230. // partly update the buffer if necessary
  16231. if (hasUniformChanged(uniform, i, cache) === true) {
  16232. const value = uniform.value;
  16233. const offset = uniform.__offset;
  16234. if (typeof value === 'number') {
  16235. uniform.__data[0] = value;
  16236. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  16237. } else {
  16238. if (uniform.value.isMatrix3) {
  16239. // manually converting 3x3 to 3x4
  16240. uniform.__data[0] = uniform.value.elements[0];
  16241. uniform.__data[1] = uniform.value.elements[1];
  16242. uniform.__data[2] = uniform.value.elements[2];
  16243. uniform.__data[3] = uniform.value.elements[0];
  16244. uniform.__data[4] = uniform.value.elements[3];
  16245. uniform.__data[5] = uniform.value.elements[4];
  16246. uniform.__data[6] = uniform.value.elements[5];
  16247. uniform.__data[7] = uniform.value.elements[0];
  16248. uniform.__data[8] = uniform.value.elements[6];
  16249. uniform.__data[9] = uniform.value.elements[7];
  16250. uniform.__data[10] = uniform.value.elements[8];
  16251. uniform.__data[11] = uniform.value.elements[0];
  16252. } else {
  16253. value.toArray(uniform.__data);
  16254. }
  16255. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  16256. }
  16257. }
  16258. }
  16259. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  16260. }
  16261. function hasUniformChanged(uniform, index, cache) {
  16262. const value = uniform.value;
  16263. if (cache[index] === undefined) {
  16264. // cache entry does not exist so far
  16265. if (typeof value === 'number') {
  16266. cache[index] = value;
  16267. } else {
  16268. cache[index] = value.clone();
  16269. }
  16270. return true;
  16271. } else {
  16272. // compare current value with cached entry
  16273. if (typeof value === 'number') {
  16274. if (cache[index] !== value) {
  16275. cache[index] = value;
  16276. return true;
  16277. }
  16278. } else {
  16279. const cachedObject = cache[index];
  16280. if (cachedObject.equals(value) === false) {
  16281. cachedObject.copy(value);
  16282. return true;
  16283. }
  16284. }
  16285. }
  16286. return false;
  16287. }
  16288. function prepareUniformsGroup(uniformsGroup) {
  16289. // determine total buffer size according to the STD140 layout
  16290. // Hint: STD140 is the only supported layout in WebGL 2
  16291. const uniforms = uniformsGroup.uniforms;
  16292. let offset = 0; // global buffer offset in bytes
  16293. const chunkSize = 16; // size of a chunk in bytes
  16294. let chunkOffset = 0; // offset within a single chunk in bytes
  16295. for (let i = 0, l = uniforms.length; i < l; i++) {
  16296. const uniform = uniforms[i];
  16297. const info = getUniformSize(uniform);
  16298. // the following two properties will be used for partial buffer updates
  16299. uniform.__data = new Float32Array(info.storage / Float32Array.BYTES_PER_ELEMENT);
  16300. uniform.__offset = offset;
  16301. //
  16302. if (i > 0) {
  16303. chunkOffset = offset % chunkSize;
  16304. const remainingSizeInChunk = chunkSize - chunkOffset;
  16305. // check for chunk overflow
  16306. if (chunkOffset !== 0 && remainingSizeInChunk - info.boundary < 0) {
  16307. // add padding and adjust offset
  16308. offset += chunkSize - chunkOffset;
  16309. uniform.__offset = offset;
  16310. }
  16311. }
  16312. offset += info.storage;
  16313. }
  16314. // ensure correct final padding
  16315. chunkOffset = offset % chunkSize;
  16316. if (chunkOffset > 0) offset += chunkSize - chunkOffset;
  16317. //
  16318. uniformsGroup.__size = offset;
  16319. uniformsGroup.__cache = {};
  16320. return this;
  16321. }
  16322. function getUniformSize(uniform) {
  16323. const value = uniform.value;
  16324. const info = {
  16325. boundary: 0,
  16326. // bytes
  16327. storage: 0 // bytes
  16328. };
  16329. // determine sizes according to STD140
  16330. if (typeof value === 'number') {
  16331. // float/int
  16332. info.boundary = 4;
  16333. info.storage = 4;
  16334. } else if (value.isVector2) {
  16335. // vec2
  16336. info.boundary = 8;
  16337. info.storage = 8;
  16338. } else if (value.isVector3 || value.isColor) {
  16339. // vec3
  16340. info.boundary = 16;
  16341. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16342. } else if (value.isVector4) {
  16343. // vec4
  16344. info.boundary = 16;
  16345. info.storage = 16;
  16346. } else if (value.isMatrix3) {
  16347. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16348. info.boundary = 48;
  16349. info.storage = 48;
  16350. } else if (value.isMatrix4) {
  16351. // mat4
  16352. info.boundary = 64;
  16353. info.storage = 64;
  16354. } else if (value.isTexture) {
  16355. console.warn('THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.');
  16356. } else {
  16357. console.warn('THREE.WebGLRenderer: Unsupported uniform value type.', value);
  16358. }
  16359. return info;
  16360. }
  16361. function onUniformsGroupsDispose(event) {
  16362. const uniformsGroup = event.target;
  16363. uniformsGroup.removeEventListener('dispose', onUniformsGroupsDispose);
  16364. const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);
  16365. allocatedBindingPoints.splice(index, 1);
  16366. gl.deleteBuffer(buffers[uniformsGroup.id]);
  16367. delete buffers[uniformsGroup.id];
  16368. delete updateList[uniformsGroup.id];
  16369. }
  16370. function dispose() {
  16371. for (const id in buffers) {
  16372. gl.deleteBuffer(buffers[id]);
  16373. }
  16374. allocatedBindingPoints = [];
  16375. buffers = {};
  16376. updateList = {};
  16377. }
  16378. return {
  16379. bind: bind,
  16380. update: update,
  16381. dispose: dispose
  16382. };
  16383. }
  16384. function createCanvasElement() {
  16385. const canvas = createElementNS('canvas');
  16386. canvas.style.display = 'block';
  16387. return canvas;
  16388. }
  16389. function WebGLRenderer(parameters = {}) {
  16390. this.isWebGLRenderer = true;
  16391. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16392. _context = parameters.context !== undefined ? parameters.context : null,
  16393. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16394. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16395. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16396. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16397. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16398. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16399. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16400. let _alpha;
  16401. if (_context !== null) {
  16402. _alpha = _context.getContextAttributes().alpha;
  16403. } else {
  16404. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16405. }
  16406. let currentRenderList = null;
  16407. let currentRenderState = null;
  16408. // render() can be called from within a callback triggered by another render.
  16409. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16410. const renderListStack = [];
  16411. const renderStateStack = [];
  16412. // public properties
  16413. this.domElement = _canvas;
  16414. // Debug configuration container
  16415. this.debug = {
  16416. /**
  16417. * Enables error checking and reporting when shader programs are being compiled
  16418. * @type {boolean}
  16419. */
  16420. checkShaderErrors: true
  16421. };
  16422. // clearing
  16423. this.autoClear = true;
  16424. this.autoClearColor = true;
  16425. this.autoClearDepth = true;
  16426. this.autoClearStencil = true;
  16427. // scene graph
  16428. this.sortObjects = true;
  16429. // user-defined clipping
  16430. this.clippingPlanes = [];
  16431. this.localClippingEnabled = false;
  16432. // physically based shading
  16433. this.outputEncoding = LinearEncoding;
  16434. // physical lights
  16435. this.physicallyCorrectLights = false;
  16436. // tone mapping
  16437. this.toneMapping = NoToneMapping;
  16438. this.toneMappingExposure = 1.0;
  16439. // internal properties
  16440. const _this = this;
  16441. let _isContextLost = false;
  16442. // internal state cache
  16443. let _currentActiveCubeFace = 0;
  16444. let _currentActiveMipmapLevel = 0;
  16445. let _currentRenderTarget = null;
  16446. let _currentMaterialId = -1;
  16447. let _currentCamera = null;
  16448. const _currentViewport = new Vector4();
  16449. const _currentScissor = new Vector4();
  16450. let _currentScissorTest = null;
  16451. //
  16452. let _width = _canvas.width;
  16453. let _height = _canvas.height;
  16454. let _pixelRatio = 1;
  16455. let _opaqueSort = null;
  16456. let _transparentSort = null;
  16457. const _viewport = new Vector4(0, 0, _width, _height);
  16458. const _scissor = new Vector4(0, 0, _width, _height);
  16459. let _scissorTest = false;
  16460. // frustum
  16461. const _frustum = new Frustum();
  16462. // clipping
  16463. let _clippingEnabled = false;
  16464. let _localClippingEnabled = false;
  16465. // transmission
  16466. let _transmissionRenderTarget = null;
  16467. // camera matrices cache
  16468. const _projScreenMatrix = new Matrix4();
  16469. const _vector2 = new Vector2();
  16470. const _vector3 = new Vector3();
  16471. const _emptyScene = {
  16472. background: null,
  16473. fog: null,
  16474. environment: null,
  16475. overrideMaterial: null,
  16476. isScene: true
  16477. };
  16478. function getTargetPixelRatio() {
  16479. return _currentRenderTarget === null ? _pixelRatio : 1;
  16480. }
  16481. // initialize
  16482. let _gl = _context;
  16483. function getContext(contextNames, contextAttributes) {
  16484. for (let i = 0; i < contextNames.length; i++) {
  16485. const contextName = contextNames[i];
  16486. const context = _canvas.getContext(contextName, contextAttributes);
  16487. if (context !== null) return context;
  16488. }
  16489. return null;
  16490. }
  16491. try {
  16492. const contextAttributes = {
  16493. alpha: true,
  16494. depth: _depth,
  16495. stencil: _stencil,
  16496. antialias: _antialias,
  16497. premultipliedAlpha: _premultipliedAlpha,
  16498. preserveDrawingBuffer: _preserveDrawingBuffer,
  16499. powerPreference: _powerPreference,
  16500. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16501. };
  16502. // OffscreenCanvas does not have setAttribute, see #22811
  16503. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`);
  16504. // event listeners must be registered before WebGL context is created, see #12753
  16505. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  16506. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  16507. _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  16508. if (_gl === null) {
  16509. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  16510. if (_this.isWebGL1Renderer === true) {
  16511. contextNames.shift();
  16512. }
  16513. _gl = getContext(contextNames, contextAttributes);
  16514. if (_gl === null) {
  16515. if (getContext(contextNames)) {
  16516. throw new Error('Error creating WebGL context with your selected attributes.');
  16517. } else {
  16518. throw new Error('Error creating WebGL context.');
  16519. }
  16520. }
  16521. }
  16522. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16523. if (_gl.getShaderPrecisionFormat === undefined) {
  16524. _gl.getShaderPrecisionFormat = function () {
  16525. return {
  16526. 'rangeMin': 1,
  16527. 'rangeMax': 1,
  16528. 'precision': 1
  16529. };
  16530. };
  16531. }
  16532. } catch (error) {
  16533. console.error('THREE.WebGLRenderer: ' + error.message);
  16534. throw error;
  16535. }
  16536. let extensions, capabilities, state, info;
  16537. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16538. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16539. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16540. let utils, bindingStates, uniformsGroups;
  16541. function initGLContext() {
  16542. extensions = new WebGLExtensions(_gl);
  16543. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  16544. extensions.init(capabilities);
  16545. utils = new WebGLUtils(_gl, extensions, capabilities);
  16546. state = new WebGLState(_gl, extensions, capabilities);
  16547. info = new WebGLInfo(_gl);
  16548. properties = new WebGLProperties();
  16549. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  16550. cubemaps = new WebGLCubeMaps(_this);
  16551. cubeuvmaps = new WebGLCubeUVMaps(_this);
  16552. attributes = new WebGLAttributes(_gl, capabilities);
  16553. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  16554. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  16555. objects = new WebGLObjects(_gl, geometries, attributes, info);
  16556. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  16557. clipping = new WebGLClipping(properties);
  16558. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  16559. materials = new WebGLMaterials(_this, properties);
  16560. renderLists = new WebGLRenderLists();
  16561. renderStates = new WebGLRenderStates(extensions, capabilities);
  16562. background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha);
  16563. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  16564. uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state);
  16565. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  16566. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  16567. info.programs = programCache.programs;
  16568. _this.capabilities = capabilities;
  16569. _this.extensions = extensions;
  16570. _this.properties = properties;
  16571. _this.renderLists = renderLists;
  16572. _this.shadowMap = shadowMap;
  16573. _this.state = state;
  16574. _this.info = info;
  16575. }
  16576. initGLContext();
  16577. // xr
  16578. const xr = new WebXRManager(_this, _gl);
  16579. this.xr = xr;
  16580. // API
  16581. this.getContext = function () {
  16582. return _gl;
  16583. };
  16584. this.getContextAttributes = function () {
  16585. return _gl.getContextAttributes();
  16586. };
  16587. this.forceContextLoss = function () {
  16588. const extension = extensions.get('WEBGL_lose_context');
  16589. if (extension) extension.loseContext();
  16590. };
  16591. this.forceContextRestore = function () {
  16592. const extension = extensions.get('WEBGL_lose_context');
  16593. if (extension) extension.restoreContext();
  16594. };
  16595. this.getPixelRatio = function () {
  16596. return _pixelRatio;
  16597. };
  16598. this.setPixelRatio = function (value) {
  16599. if (value === undefined) return;
  16600. _pixelRatio = value;
  16601. this.setSize(_width, _height, false);
  16602. };
  16603. this.getSize = function (target) {
  16604. return target.set(_width, _height);
  16605. };
  16606. this.setSize = function (width, height, updateStyle) {
  16607. if (xr.isPresenting) {
  16608. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  16609. return;
  16610. }
  16611. _width = width;
  16612. _height = height;
  16613. _canvas.width = Math.floor(width * _pixelRatio);
  16614. _canvas.height = Math.floor(height * _pixelRatio);
  16615. if (updateStyle !== false) {
  16616. _canvas.style.width = width + 'px';
  16617. _canvas.style.height = height + 'px';
  16618. }
  16619. this.setViewport(0, 0, width, height);
  16620. };
  16621. this.getDrawingBufferSize = function (target) {
  16622. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  16623. };
  16624. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  16625. _width = width;
  16626. _height = height;
  16627. _pixelRatio = pixelRatio;
  16628. _canvas.width = Math.floor(width * pixelRatio);
  16629. _canvas.height = Math.floor(height * pixelRatio);
  16630. this.setViewport(0, 0, width, height);
  16631. };
  16632. this.getCurrentViewport = function (target) {
  16633. return target.copy(_currentViewport);
  16634. };
  16635. this.getViewport = function (target) {
  16636. return target.copy(_viewport);
  16637. };
  16638. this.setViewport = function (x, y, width, height) {
  16639. if (x.isVector4) {
  16640. _viewport.set(x.x, x.y, x.z, x.w);
  16641. } else {
  16642. _viewport.set(x, y, width, height);
  16643. }
  16644. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  16645. };
  16646. this.getScissor = function (target) {
  16647. return target.copy(_scissor);
  16648. };
  16649. this.setScissor = function (x, y, width, height) {
  16650. if (x.isVector4) {
  16651. _scissor.set(x.x, x.y, x.z, x.w);
  16652. } else {
  16653. _scissor.set(x, y, width, height);
  16654. }
  16655. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  16656. };
  16657. this.getScissorTest = function () {
  16658. return _scissorTest;
  16659. };
  16660. this.setScissorTest = function (boolean) {
  16661. state.setScissorTest(_scissorTest = boolean);
  16662. };
  16663. this.setOpaqueSort = function (method) {
  16664. _opaqueSort = method;
  16665. };
  16666. this.setTransparentSort = function (method) {
  16667. _transparentSort = method;
  16668. };
  16669. // Clearing
  16670. this.getClearColor = function (target) {
  16671. return target.copy(background.getClearColor());
  16672. };
  16673. this.setClearColor = function () {
  16674. background.setClearColor.apply(background, arguments);
  16675. };
  16676. this.getClearAlpha = function () {
  16677. return background.getClearAlpha();
  16678. };
  16679. this.setClearAlpha = function () {
  16680. background.setClearAlpha.apply(background, arguments);
  16681. };
  16682. this.clear = function (color = true, depth = true, stencil = true) {
  16683. let bits = 0;
  16684. if (color) bits |= _gl.COLOR_BUFFER_BIT;
  16685. if (depth) bits |= _gl.DEPTH_BUFFER_BIT;
  16686. if (stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  16687. _gl.clear(bits);
  16688. };
  16689. this.clearColor = function () {
  16690. this.clear(true, false, false);
  16691. };
  16692. this.clearDepth = function () {
  16693. this.clear(false, true, false);
  16694. };
  16695. this.clearStencil = function () {
  16696. this.clear(false, false, true);
  16697. };
  16698. //
  16699. this.dispose = function () {
  16700. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  16701. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  16702. _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  16703. renderLists.dispose();
  16704. renderStates.dispose();
  16705. properties.dispose();
  16706. cubemaps.dispose();
  16707. cubeuvmaps.dispose();
  16708. objects.dispose();
  16709. bindingStates.dispose();
  16710. uniformsGroups.dispose();
  16711. programCache.dispose();
  16712. xr.dispose();
  16713. xr.removeEventListener('sessionstart', onXRSessionStart);
  16714. xr.removeEventListener('sessionend', onXRSessionEnd);
  16715. if (_transmissionRenderTarget) {
  16716. _transmissionRenderTarget.dispose();
  16717. _transmissionRenderTarget = null;
  16718. }
  16719. animation.stop();
  16720. };
  16721. // Events
  16722. function onContextLost(event) {
  16723. event.preventDefault();
  16724. console.log('THREE.WebGLRenderer: Context Lost.');
  16725. _isContextLost = true;
  16726. }
  16727. function /* event */
  16728. onContextRestore() {
  16729. console.log('THREE.WebGLRenderer: Context Restored.');
  16730. _isContextLost = false;
  16731. const infoAutoReset = info.autoReset;
  16732. const shadowMapEnabled = shadowMap.enabled;
  16733. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16734. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16735. const shadowMapType = shadowMap.type;
  16736. initGLContext();
  16737. info.autoReset = infoAutoReset;
  16738. shadowMap.enabled = shadowMapEnabled;
  16739. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16740. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16741. shadowMap.type = shadowMapType;
  16742. }
  16743. function onContextCreationError(event) {
  16744. console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage);
  16745. }
  16746. function onMaterialDispose(event) {
  16747. const material = event.target;
  16748. material.removeEventListener('dispose', onMaterialDispose);
  16749. deallocateMaterial(material);
  16750. }
  16751. // Buffer deallocation
  16752. function deallocateMaterial(material) {
  16753. releaseMaterialProgramReferences(material);
  16754. properties.remove(material);
  16755. }
  16756. function releaseMaterialProgramReferences(material) {
  16757. const programs = properties.get(material).programs;
  16758. if (programs !== undefined) {
  16759. programs.forEach(function (program) {
  16760. programCache.releaseProgram(program);
  16761. });
  16762. if (material.isShaderMaterial) {
  16763. programCache.releaseShaderCache(material);
  16764. }
  16765. }
  16766. }
  16767. // Buffer rendering
  16768. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  16769. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16770. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  16771. const program = setProgram(camera, scene, geometry, material, object);
  16772. state.setMaterial(material, frontFaceCW);
  16773. //
  16774. let index = geometry.index;
  16775. let rangeFactor = 1;
  16776. if (material.wireframe === true) {
  16777. index = geometries.getWireframeAttribute(geometry);
  16778. rangeFactor = 2;
  16779. }
  16780. //
  16781. const drawRange = geometry.drawRange;
  16782. const position = geometry.attributes.position;
  16783. let drawStart = drawRange.start * rangeFactor;
  16784. let drawEnd = (drawRange.start + drawRange.count) * rangeFactor;
  16785. if (group !== null) {
  16786. drawStart = Math.max(drawStart, group.start * rangeFactor);
  16787. drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor);
  16788. }
  16789. if (index !== null) {
  16790. drawStart = Math.max(drawStart, 0);
  16791. drawEnd = Math.min(drawEnd, index.count);
  16792. } else if (position !== undefined && position !== null) {
  16793. drawStart = Math.max(drawStart, 0);
  16794. drawEnd = Math.min(drawEnd, position.count);
  16795. }
  16796. const drawCount = drawEnd - drawStart;
  16797. if (drawCount < 0 || drawCount === Infinity) return;
  16798. //
  16799. bindingStates.setup(object, material, program, geometry, index);
  16800. let attribute;
  16801. let renderer = bufferRenderer;
  16802. if (index !== null) {
  16803. attribute = attributes.get(index);
  16804. renderer = indexedBufferRenderer;
  16805. renderer.setIndex(attribute);
  16806. }
  16807. //
  16808. if (object.isMesh) {
  16809. if (material.wireframe === true) {
  16810. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16811. renderer.setMode(_gl.LINES);
  16812. } else {
  16813. renderer.setMode(_gl.TRIANGLES);
  16814. }
  16815. } else if (object.isLine) {
  16816. let lineWidth = material.linewidth;
  16817. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16818. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16819. if (object.isLineSegments) {
  16820. renderer.setMode(_gl.LINES);
  16821. } else if (object.isLineLoop) {
  16822. renderer.setMode(_gl.LINE_LOOP);
  16823. } else {
  16824. renderer.setMode(_gl.LINE_STRIP);
  16825. }
  16826. } else if (object.isPoints) {
  16827. renderer.setMode(_gl.POINTS);
  16828. } else if (object.isSprite) {
  16829. renderer.setMode(_gl.TRIANGLES);
  16830. }
  16831. if (object.isInstancedMesh) {
  16832. renderer.renderInstances(drawStart, drawCount, object.count);
  16833. } else if (geometry.isInstancedBufferGeometry) {
  16834. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16835. const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount);
  16836. renderer.renderInstances(drawStart, drawCount, instanceCount);
  16837. } else {
  16838. renderer.render(drawStart, drawCount);
  16839. }
  16840. };
  16841. // Compile
  16842. this.compile = function (scene, camera) {
  16843. function prepare(material, scene, object) {
  16844. if (material.transparent === true && material.side === DoubleSide) {
  16845. material.side = BackSide;
  16846. material.needsUpdate = true;
  16847. getProgram(material, scene, object);
  16848. material.side = FrontSide;
  16849. material.needsUpdate = true;
  16850. getProgram(material, scene, object);
  16851. material.side = DoubleSide;
  16852. } else {
  16853. getProgram(material, scene, object);
  16854. }
  16855. }
  16856. currentRenderState = renderStates.get(scene);
  16857. currentRenderState.init();
  16858. renderStateStack.push(currentRenderState);
  16859. scene.traverseVisible(function (object) {
  16860. if (object.isLight && object.layers.test(camera.layers)) {
  16861. currentRenderState.pushLight(object);
  16862. if (object.castShadow) {
  16863. currentRenderState.pushShadow(object);
  16864. }
  16865. }
  16866. });
  16867. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16868. scene.traverse(function (object) {
  16869. const material = object.material;
  16870. if (material) {
  16871. if (Array.isArray(material)) {
  16872. for (let i = 0; i < material.length; i++) {
  16873. const material2 = material[i];
  16874. prepare(material2, scene, object);
  16875. }
  16876. } else {
  16877. prepare(material, scene, object);
  16878. }
  16879. }
  16880. });
  16881. renderStateStack.pop();
  16882. currentRenderState = null;
  16883. };
  16884. // Animation Loop
  16885. let onAnimationFrameCallback = null;
  16886. function onAnimationFrame(time) {
  16887. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16888. }
  16889. function onXRSessionStart() {
  16890. animation.stop();
  16891. }
  16892. function onXRSessionEnd() {
  16893. animation.start();
  16894. }
  16895. const animation = new WebGLAnimation();
  16896. animation.setAnimationLoop(onAnimationFrame);
  16897. if (typeof self !== 'undefined') animation.setContext(self);
  16898. this.setAnimationLoop = function (callback) {
  16899. onAnimationFrameCallback = callback;
  16900. xr.setAnimationLoop(callback);
  16901. callback === null ? animation.stop() : animation.start();
  16902. };
  16903. xr.addEventListener('sessionstart', onXRSessionStart);
  16904. xr.addEventListener('sessionend', onXRSessionEnd);
  16905. // Rendering
  16906. this.render = function (scene, camera) {
  16907. if (camera !== undefined && camera.isCamera !== true) {
  16908. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16909. return;
  16910. }
  16911. if (_isContextLost === true) return;
  16912. // update scene graph
  16913. if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
  16914. // update camera matrices and frustum
  16915. if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
  16916. if (xr.enabled === true && xr.isPresenting === true) {
  16917. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  16918. camera = xr.getCamera(); // use XR camera for rendering
  16919. }
  16920. //
  16921. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  16922. currentRenderState = renderStates.get(scene, renderStateStack.length);
  16923. currentRenderState.init();
  16924. renderStateStack.push(currentRenderState);
  16925. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16926. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  16927. _localClippingEnabled = this.localClippingEnabled;
  16928. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16929. currentRenderList = renderLists.get(scene, renderListStack.length);
  16930. currentRenderList.init();
  16931. renderListStack.push(currentRenderList);
  16932. projectObject(scene, camera, 0, _this.sortObjects);
  16933. currentRenderList.finish();
  16934. if (_this.sortObjects === true) {
  16935. currentRenderList.sort(_opaqueSort, _transparentSort);
  16936. }
  16937. //
  16938. if (_clippingEnabled === true) clipping.beginShadows();
  16939. const shadowsArray = currentRenderState.state.shadowsArray;
  16940. shadowMap.render(shadowsArray, scene, camera);
  16941. if (_clippingEnabled === true) clipping.endShadows();
  16942. //
  16943. if (this.info.autoReset === true) this.info.reset();
  16944. //
  16945. background.render(currentRenderList, scene);
  16946. // render scene
  16947. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16948. if (camera.isArrayCamera) {
  16949. const cameras = camera.cameras;
  16950. for (let i = 0, l = cameras.length; i < l; i++) {
  16951. const camera2 = cameras[i];
  16952. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16953. }
  16954. } else {
  16955. renderScene(currentRenderList, scene, camera);
  16956. }
  16957. //
  16958. if (_currentRenderTarget !== null) {
  16959. // resolve multisample renderbuffers to a single-sample texture if necessary
  16960. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16961. // Generate mipmap if we're using any kind of mipmap filtering
  16962. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16963. }
  16964. //
  16965. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera);
  16966. // _gl.finish();
  16967. bindingStates.resetDefaultState();
  16968. _currentMaterialId = -1;
  16969. _currentCamera = null;
  16970. renderStateStack.pop();
  16971. if (renderStateStack.length > 0) {
  16972. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16973. } else {
  16974. currentRenderState = null;
  16975. }
  16976. renderListStack.pop();
  16977. if (renderListStack.length > 0) {
  16978. currentRenderList = renderListStack[renderListStack.length - 1];
  16979. } else {
  16980. currentRenderList = null;
  16981. }
  16982. };
  16983. function projectObject(object, camera, groupOrder, sortObjects) {
  16984. if (object.visible === false) return;
  16985. const visible = object.layers.test(camera.layers);
  16986. if (visible) {
  16987. if (object.isGroup) {
  16988. groupOrder = object.renderOrder;
  16989. } else if (object.isLOD) {
  16990. if (object.autoUpdate === true) object.update(camera);
  16991. } else if (object.isLight) {
  16992. currentRenderState.pushLight(object);
  16993. if (object.castShadow) {
  16994. currentRenderState.pushShadow(object);
  16995. }
  16996. } else if (object.isSprite) {
  16997. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16998. if (sortObjects) {
  16999. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  17000. }
  17001. const geometry = objects.update(object);
  17002. const material = object.material;
  17003. if (material.visible) {
  17004. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  17005. }
  17006. }
  17007. } else if (object.isMesh || object.isLine || object.isPoints) {
  17008. if (object.isSkinnedMesh) {
  17009. // update skeleton only once in a frame
  17010. if (object.skeleton.frame !== info.render.frame) {
  17011. object.skeleton.update();
  17012. object.skeleton.frame = info.render.frame;
  17013. }
  17014. }
  17015. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  17016. if (sortObjects) {
  17017. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  17018. }
  17019. const geometry = objects.update(object);
  17020. const material = object.material;
  17021. if (Array.isArray(material)) {
  17022. const groups = geometry.groups;
  17023. for (let i = 0, l = groups.length; i < l; i++) {
  17024. const group = groups[i];
  17025. const groupMaterial = material[group.materialIndex];
  17026. if (groupMaterial && groupMaterial.visible) {
  17027. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  17028. }
  17029. }
  17030. } else if (material.visible) {
  17031. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  17032. }
  17033. }
  17034. }
  17035. }
  17036. const children = object.children;
  17037. for (let i = 0, l = children.length; i < l; i++) {
  17038. projectObject(children[i], camera, groupOrder, sortObjects);
  17039. }
  17040. }
  17041. function renderScene(currentRenderList, scene, camera, viewport) {
  17042. const opaqueObjects = currentRenderList.opaque;
  17043. const transmissiveObjects = currentRenderList.transmissive;
  17044. const transparentObjects = currentRenderList.transparent;
  17045. currentRenderState.setupLightsView(camera);
  17046. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  17047. if (viewport) state.viewport(_currentViewport.copy(viewport));
  17048. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  17049. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  17050. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  17051. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17052. state.buffers.depth.setTest(true);
  17053. state.buffers.depth.setMask(true);
  17054. state.buffers.color.setMask(true);
  17055. state.setPolygonOffset(false);
  17056. }
  17057. function renderTransmissionPass(opaqueObjects, scene, camera) {
  17058. const isWebGL2 = capabilities.isWebGL2;
  17059. if (_transmissionRenderTarget === null) {
  17060. _transmissionRenderTarget = new WebGLRenderTarget(1, 1, {
  17061. generateMipmaps: true,
  17062. type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType,
  17063. minFilter: LinearMipmapLinearFilter,
  17064. samples: isWebGL2 && _antialias === true ? 4 : 0
  17065. });
  17066. }
  17067. _this.getDrawingBufferSize(_vector2);
  17068. if (isWebGL2) {
  17069. _transmissionRenderTarget.setSize(_vector2.x, _vector2.y);
  17070. } else {
  17071. _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y));
  17072. }
  17073. //
  17074. const currentRenderTarget = _this.getRenderTarget();
  17075. _this.setRenderTarget(_transmissionRenderTarget);
  17076. _this.clear();
  17077. // Turn off the features which can affect the frag color for opaque objects pass.
  17078. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17079. const currentToneMapping = _this.toneMapping;
  17080. _this.toneMapping = NoToneMapping;
  17081. renderObjects(opaqueObjects, scene, camera);
  17082. _this.toneMapping = currentToneMapping;
  17083. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  17084. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  17085. _this.setRenderTarget(currentRenderTarget);
  17086. }
  17087. function renderObjects(renderList, scene, camera) {
  17088. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17089. for (let i = 0, l = renderList.length; i < l; i++) {
  17090. const renderItem = renderList[i];
  17091. const object = renderItem.object;
  17092. const geometry = renderItem.geometry;
  17093. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17094. const group = renderItem.group;
  17095. if (object.layers.test(camera.layers)) {
  17096. renderObject(object, scene, camera, geometry, material, group);
  17097. }
  17098. }
  17099. }
  17100. function renderObject(object, scene, camera, geometry, material, group) {
  17101. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  17102. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  17103. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  17104. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  17105. if (material.transparent === true && material.side === DoubleSide) {
  17106. material.side = BackSide;
  17107. material.needsUpdate = true;
  17108. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  17109. material.side = FrontSide;
  17110. material.needsUpdate = true;
  17111. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  17112. material.side = DoubleSide;
  17113. } else {
  17114. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  17115. }
  17116. object.onAfterRender(_this, scene, camera, geometry, material, group);
  17117. }
  17118. function getProgram(material, scene, object) {
  17119. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17120. const materialProperties = properties.get(material);
  17121. const lights = currentRenderState.state.lights;
  17122. const shadowsArray = currentRenderState.state.shadowsArray;
  17123. const lightsStateVersion = lights.state.version;
  17124. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  17125. const programCacheKey = programCache.getProgramCacheKey(parameters);
  17126. let programs = materialProperties.programs;
  17127. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17128. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17129. materialProperties.fog = scene.fog;
  17130. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  17131. if (programs === undefined) {
  17132. // new material
  17133. material.addEventListener('dispose', onMaterialDispose);
  17134. programs = new Map();
  17135. materialProperties.programs = programs;
  17136. }
  17137. let program = programs.get(programCacheKey);
  17138. if (program !== undefined) {
  17139. // early out if program and light state is identical
  17140. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  17141. updateCommonMaterialProperties(material, parameters);
  17142. return program;
  17143. }
  17144. } else {
  17145. parameters.uniforms = programCache.getUniforms(material);
  17146. material.onBuild(object, parameters, _this);
  17147. material.onBeforeCompile(parameters, _this);
  17148. program = programCache.acquireProgram(parameters, programCacheKey);
  17149. programs.set(programCacheKey, program);
  17150. materialProperties.uniforms = parameters.uniforms;
  17151. }
  17152. const uniforms = materialProperties.uniforms;
  17153. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  17154. uniforms.clippingPlanes = clipping.uniform;
  17155. }
  17156. updateCommonMaterialProperties(material, parameters);
  17157. // store the light setup it was created for
  17158. materialProperties.needsLights = materialNeedsLights(material);
  17159. materialProperties.lightsStateVersion = lightsStateVersion;
  17160. if (materialProperties.needsLights) {
  17161. // wire up the material to this renderer's lighting state
  17162. uniforms.ambientLightColor.value = lights.state.ambient;
  17163. uniforms.lightProbe.value = lights.state.probe;
  17164. uniforms.directionalLights.value = lights.state.directional;
  17165. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17166. uniforms.spotLights.value = lights.state.spot;
  17167. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17168. uniforms.rectAreaLights.value = lights.state.rectArea;
  17169. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17170. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17171. uniforms.pointLights.value = lights.state.point;
  17172. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17173. uniforms.hemisphereLights.value = lights.state.hemi;
  17174. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17175. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17176. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17177. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17178. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17179. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17180. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17181. // TODO (abelnation): add area lights shadow info to uniforms
  17182. }
  17183. const progUniforms = program.getUniforms();
  17184. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  17185. materialProperties.currentProgram = program;
  17186. materialProperties.uniformsList = uniformsList;
  17187. return program;
  17188. }
  17189. function updateCommonMaterialProperties(material, parameters) {
  17190. const materialProperties = properties.get(material);
  17191. materialProperties.outputEncoding = parameters.outputEncoding;
  17192. materialProperties.instancing = parameters.instancing;
  17193. materialProperties.skinning = parameters.skinning;
  17194. materialProperties.morphTargets = parameters.morphTargets;
  17195. materialProperties.morphNormals = parameters.morphNormals;
  17196. materialProperties.morphColors = parameters.morphColors;
  17197. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17198. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17199. materialProperties.numIntersection = parameters.numClipIntersection;
  17200. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17201. materialProperties.vertexTangents = parameters.vertexTangents;
  17202. materialProperties.toneMapping = parameters.toneMapping;
  17203. }
  17204. function setProgram(camera, scene, geometry, material, object) {
  17205. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17206. textures.resetTextureUnits();
  17207. const fog = scene.fog;
  17208. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17209. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
  17210. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  17211. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17212. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  17213. const morphTargets = !!geometry.morphAttributes.position;
  17214. const morphNormals = !!geometry.morphAttributes.normal;
  17215. const morphColors = !!geometry.morphAttributes.color;
  17216. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17217. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17218. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  17219. const materialProperties = properties.get(material);
  17220. const lights = currentRenderState.state.lights;
  17221. if (_clippingEnabled === true) {
  17222. if (_localClippingEnabled === true || camera !== _currentCamera) {
  17223. const useCache = camera === _currentCamera && material.id === _currentMaterialId;
  17224. // we might want to call this function with some ClippingGroup
  17225. // object instead of the material, once it becomes feasible
  17226. // (#8465, #8379)
  17227. clipping.setState(material, camera, useCache);
  17228. }
  17229. }
  17230. //
  17231. let needsProgramChange = false;
  17232. if (material.version === materialProperties.__version) {
  17233. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  17234. needsProgramChange = true;
  17235. } else if (materialProperties.outputEncoding !== encoding) {
  17236. needsProgramChange = true;
  17237. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  17238. needsProgramChange = true;
  17239. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  17240. needsProgramChange = true;
  17241. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  17242. needsProgramChange = true;
  17243. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  17244. needsProgramChange = true;
  17245. } else if (materialProperties.envMap !== envMap) {
  17246. needsProgramChange = true;
  17247. } else if (material.fog === true && materialProperties.fog !== fog) {
  17248. needsProgramChange = true;
  17249. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  17250. needsProgramChange = true;
  17251. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  17252. needsProgramChange = true;
  17253. } else if (materialProperties.vertexTangents !== vertexTangents) {
  17254. needsProgramChange = true;
  17255. } else if (materialProperties.morphTargets !== morphTargets) {
  17256. needsProgramChange = true;
  17257. } else if (materialProperties.morphNormals !== morphNormals) {
  17258. needsProgramChange = true;
  17259. } else if (materialProperties.morphColors !== morphColors) {
  17260. needsProgramChange = true;
  17261. } else if (materialProperties.toneMapping !== toneMapping) {
  17262. needsProgramChange = true;
  17263. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  17264. needsProgramChange = true;
  17265. }
  17266. } else {
  17267. needsProgramChange = true;
  17268. materialProperties.__version = material.version;
  17269. }
  17270. //
  17271. let program = materialProperties.currentProgram;
  17272. if (needsProgramChange === true) {
  17273. program = getProgram(material, scene, object);
  17274. }
  17275. let refreshProgram = false;
  17276. let refreshMaterial = false;
  17277. let refreshLights = false;
  17278. const p_uniforms = program.getUniforms(),
  17279. m_uniforms = materialProperties.uniforms;
  17280. if (state.useProgram(program.program)) {
  17281. refreshProgram = true;
  17282. refreshMaterial = true;
  17283. refreshLights = true;
  17284. }
  17285. if (material.id !== _currentMaterialId) {
  17286. _currentMaterialId = material.id;
  17287. refreshMaterial = true;
  17288. }
  17289. if (refreshProgram || _currentCamera !== camera) {
  17290. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  17291. if (capabilities.logarithmicDepthBuffer) {
  17292. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  17293. }
  17294. if (_currentCamera !== camera) {
  17295. _currentCamera = camera;
  17296. // lighting uniforms depend on the camera so enforce an update
  17297. // now, in case this material supports lights - or later, when
  17298. // the next material that does gets activated:
  17299. refreshMaterial = true; // set to true on material change
  17300. refreshLights = true; // remains set until update done
  17301. }
  17302. // load material specific uniforms
  17303. // (shader material also gets them for the sake of genericity)
  17304. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  17305. const uCamPos = p_uniforms.map.cameraPosition;
  17306. if (uCamPos !== undefined) {
  17307. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  17308. }
  17309. }
  17310. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  17311. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  17312. }
  17313. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  17314. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  17315. }
  17316. }
  17317. // skinning and morph target uniforms must be set even if material didn't change
  17318. // auto-setting of texture unit for bone and morph texture must go before other textures
  17319. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17320. if (object.isSkinnedMesh) {
  17321. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  17322. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  17323. const skeleton = object.skeleton;
  17324. if (skeleton) {
  17325. if (capabilities.floatVertexTextures) {
  17326. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  17327. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  17328. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  17329. } else {
  17330. console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.');
  17331. }
  17332. }
  17333. }
  17334. const morphAttributes = geometry.morphAttributes;
  17335. if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) {
  17336. morphtargets.update(object, geometry, material, program);
  17337. }
  17338. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  17339. materialProperties.receiveShadow = object.receiveShadow;
  17340. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  17341. }
  17342. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17343. if (material.isMeshGouraudMaterial && material.envMap !== null) {
  17344. m_uniforms.envMap.value = envMap;
  17345. m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  17346. }
  17347. if (refreshMaterial) {
  17348. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  17349. if (materialProperties.needsLights) {
  17350. // the current material requires lighting info
  17351. // note: all lighting uniforms are always set correctly
  17352. // they simply reference the renderer's state for their
  17353. // values
  17354. //
  17355. // use the current material's .needsUpdate flags to set
  17356. // the GL state when required
  17357. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  17358. }
  17359. // refresh uniforms common to several materials
  17360. if (fog && material.fog === true) {
  17361. materials.refreshFogUniforms(m_uniforms, fog);
  17362. }
  17363. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  17364. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  17365. }
  17366. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  17367. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  17368. material.uniformsNeedUpdate = false;
  17369. }
  17370. if (material.isSpriteMaterial) {
  17371. p_uniforms.setValue(_gl, 'center', object.center);
  17372. }
  17373. // common matrices
  17374. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  17375. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  17376. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  17377. // UBOs
  17378. if (material.isShaderMaterial || material.isRawShaderMaterial) {
  17379. const groups = material.uniformsGroups;
  17380. for (let i = 0, l = groups.length; i < l; i++) {
  17381. if (capabilities.isWebGL2) {
  17382. const group = groups[i];
  17383. uniformsGroups.update(group, program);
  17384. uniformsGroups.bind(group, program);
  17385. } else {
  17386. console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.');
  17387. }
  17388. }
  17389. }
  17390. return program;
  17391. }
  17392. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17393. function markUniformsLightsNeedsUpdate(uniforms, value) {
  17394. uniforms.ambientLightColor.needsUpdate = value;
  17395. uniforms.lightProbe.needsUpdate = value;
  17396. uniforms.directionalLights.needsUpdate = value;
  17397. uniforms.directionalLightShadows.needsUpdate = value;
  17398. uniforms.pointLights.needsUpdate = value;
  17399. uniforms.pointLightShadows.needsUpdate = value;
  17400. uniforms.spotLights.needsUpdate = value;
  17401. uniforms.spotLightShadows.needsUpdate = value;
  17402. uniforms.rectAreaLights.needsUpdate = value;
  17403. uniforms.hemisphereLights.needsUpdate = value;
  17404. }
  17405. function materialNeedsLights(material) {
  17406. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  17407. }
  17408. this.getActiveCubeFace = function () {
  17409. return _currentActiveCubeFace;
  17410. };
  17411. this.getActiveMipmapLevel = function () {
  17412. return _currentActiveMipmapLevel;
  17413. };
  17414. this.getRenderTarget = function () {
  17415. return _currentRenderTarget;
  17416. };
  17417. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  17418. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  17419. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  17420. const renderTargetProperties = properties.get(renderTarget);
  17421. renderTargetProperties.__hasExternalTextures = true;
  17422. if (renderTargetProperties.__hasExternalTextures) {
  17423. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17424. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  17425. // The multisample_render_to_texture extension doesn't work properly if there
  17426. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17427. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  17428. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  17429. renderTargetProperties.__useRenderToTexture = false;
  17430. }
  17431. }
  17432. }
  17433. };
  17434. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  17435. const renderTargetProperties = properties.get(renderTarget);
  17436. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17437. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17438. };
  17439. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  17440. _currentRenderTarget = renderTarget;
  17441. _currentActiveCubeFace = activeCubeFace;
  17442. _currentActiveMipmapLevel = activeMipmapLevel;
  17443. let useDefaultFramebuffer = true;
  17444. let framebuffer = null;
  17445. let isCube = false;
  17446. let isRenderTarget3D = false;
  17447. if (renderTarget) {
  17448. const renderTargetProperties = properties.get(renderTarget);
  17449. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  17450. // We need to make sure to rebind the framebuffer.
  17451. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  17452. useDefaultFramebuffer = false;
  17453. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  17454. textures.setupRenderTarget(renderTarget);
  17455. } else if (renderTargetProperties.__hasExternalTextures) {
  17456. // Color and depth texture must be rebound in order for the swapchain to update.
  17457. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  17458. }
  17459. const texture = renderTarget.texture;
  17460. if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
  17461. isRenderTarget3D = true;
  17462. }
  17463. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  17464. if (renderTarget.isWebGLCubeRenderTarget) {
  17465. framebuffer = __webglFramebuffer[activeCubeFace];
  17466. isCube = true;
  17467. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  17468. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  17469. } else {
  17470. framebuffer = __webglFramebuffer;
  17471. }
  17472. _currentViewport.copy(renderTarget.viewport);
  17473. _currentScissor.copy(renderTarget.scissor);
  17474. _currentScissorTest = renderTarget.scissorTest;
  17475. } else {
  17476. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  17477. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  17478. _currentScissorTest = _scissorTest;
  17479. }
  17480. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17481. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  17482. state.drawBuffers(renderTarget, framebuffer);
  17483. }
  17484. state.viewport(_currentViewport);
  17485. state.scissor(_currentScissor);
  17486. state.setScissorTest(_currentScissorTest);
  17487. if (isCube) {
  17488. const textureProperties = properties.get(renderTarget.texture);
  17489. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  17490. } else if (isRenderTarget3D) {
  17491. const textureProperties = properties.get(renderTarget.texture);
  17492. const layer = activeCubeFace || 0;
  17493. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  17494. }
  17495. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  17496. };
  17497. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  17498. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  17499. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  17500. return;
  17501. }
  17502. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  17503. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  17504. framebuffer = framebuffer[activeCubeFaceIndex];
  17505. }
  17506. if (framebuffer) {
  17507. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17508. try {
  17509. const texture = renderTarget.texture;
  17510. const textureFormat = texture.format;
  17511. const textureType = texture.type;
  17512. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  17513. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  17514. return;
  17515. }
  17516. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  17517. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) &&
  17518. // Edge and Chrome Mac < 52 (#9513)
  17519. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) &&
  17520. // Chrome Mac >= 52 and Firefox
  17521. !halfFloatSupportedByExt) {
  17522. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  17523. return;
  17524. }
  17525. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17526. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  17527. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  17528. }
  17529. } finally {
  17530. // restore framebuffer of current render target if necessary
  17531. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  17532. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17533. }
  17534. }
  17535. };
  17536. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  17537. const levelScale = Math.pow(2, -level);
  17538. const width = Math.floor(texture.image.width * levelScale);
  17539. const height = Math.floor(texture.image.height * levelScale);
  17540. textures.setTexture2D(texture, 0);
  17541. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  17542. state.unbindTexture();
  17543. };
  17544. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  17545. const width = srcTexture.image.width;
  17546. const height = srcTexture.image.height;
  17547. const glFormat = utils.convert(dstTexture.format);
  17548. const glType = utils.convert(dstTexture.type);
  17549. textures.setTexture2D(dstTexture, 0);
  17550. // As another texture upload may have changed pixelStorei
  17551. // parameters, make sure they are correct for the dstTexture
  17552. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17553. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17554. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17555. if (srcTexture.isDataTexture) {
  17556. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  17557. } else {
  17558. if (srcTexture.isCompressedTexture) {
  17559. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  17560. } else {
  17561. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  17562. }
  17563. }
  17564. // Generate mipmaps only when copying level 0
  17565. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  17566. state.unbindTexture();
  17567. };
  17568. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  17569. if (_this.isWebGL1Renderer) {
  17570. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  17571. return;
  17572. }
  17573. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17574. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17575. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17576. const glFormat = utils.convert(dstTexture.format);
  17577. const glType = utils.convert(dstTexture.type);
  17578. let glTarget;
  17579. if (dstTexture.isData3DTexture) {
  17580. textures.setTexture3D(dstTexture, 0);
  17581. glTarget = _gl.TEXTURE_3D;
  17582. } else if (dstTexture.isDataArrayTexture) {
  17583. textures.setTexture2DArray(dstTexture, 0);
  17584. glTarget = _gl.TEXTURE_2D_ARRAY;
  17585. } else {
  17586. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  17587. return;
  17588. }
  17589. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17590. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17591. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17592. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  17593. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  17594. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  17595. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  17596. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  17597. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  17598. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  17599. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  17600. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  17601. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  17602. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  17603. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  17604. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  17605. } else {
  17606. if (srcTexture.isCompressedArrayTexture) {
  17607. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  17608. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  17609. } else {
  17610. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  17611. }
  17612. }
  17613. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  17614. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  17615. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  17616. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  17617. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages);
  17618. // Generate mipmaps only when copying level 0
  17619. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  17620. state.unbindTexture();
  17621. };
  17622. this.initTexture = function (texture) {
  17623. if (texture.isCubeTexture) {
  17624. textures.setTextureCube(texture, 0);
  17625. } else if (texture.isData3DTexture) {
  17626. textures.setTexture3D(texture, 0);
  17627. } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
  17628. textures.setTexture2DArray(texture, 0);
  17629. } else {
  17630. textures.setTexture2D(texture, 0);
  17631. }
  17632. state.unbindTexture();
  17633. };
  17634. this.resetState = function () {
  17635. _currentActiveCubeFace = 0;
  17636. _currentActiveMipmapLevel = 0;
  17637. _currentRenderTarget = null;
  17638. state.reset();
  17639. bindingStates.reset();
  17640. };
  17641. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17642. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17643. detail: this
  17644. }));
  17645. }
  17646. }
  17647. class WebGL1Renderer extends WebGLRenderer {}
  17648. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17649. class FogExp2 {
  17650. constructor(color, density = 0.00025) {
  17651. this.isFogExp2 = true;
  17652. this.name = '';
  17653. this.color = new Color(color);
  17654. this.density = density;
  17655. }
  17656. clone() {
  17657. return new FogExp2(this.color, this.density);
  17658. }
  17659. toJSON() {
  17660. return {
  17661. type: 'FogExp2',
  17662. color: this.color.getHex(),
  17663. density: this.density
  17664. };
  17665. }
  17666. }
  17667. class Fog {
  17668. constructor(color, near = 1, far = 1000) {
  17669. this.isFog = true;
  17670. this.name = '';
  17671. this.color = new Color(color);
  17672. this.near = near;
  17673. this.far = far;
  17674. }
  17675. clone() {
  17676. return new Fog(this.color, this.near, this.far);
  17677. }
  17678. toJSON() {
  17679. return {
  17680. type: 'Fog',
  17681. color: this.color.getHex(),
  17682. near: this.near,
  17683. far: this.far
  17684. };
  17685. }
  17686. }
  17687. class Scene extends Object3D {
  17688. constructor() {
  17689. super();
  17690. this.isScene = true;
  17691. this.type = 'Scene';
  17692. this.background = null;
  17693. this.environment = null;
  17694. this.fog = null;
  17695. this.backgroundBlurriness = 0;
  17696. this.backgroundIntensity = 1;
  17697. this.overrideMaterial = null;
  17698. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17699. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17700. detail: this
  17701. }));
  17702. }
  17703. }
  17704. copy(source, recursive) {
  17705. super.copy(source, recursive);
  17706. if (source.background !== null) this.background = source.background.clone();
  17707. if (source.environment !== null) this.environment = source.environment.clone();
  17708. if (source.fog !== null) this.fog = source.fog.clone();
  17709. this.backgroundBlurriness = source.backgroundBlurriness;
  17710. this.backgroundIntensity = source.backgroundIntensity;
  17711. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  17712. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17713. return this;
  17714. }
  17715. toJSON(meta) {
  17716. const data = super.toJSON(meta);
  17717. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  17718. if (this.backgroundBlurriness > 0) data.backgroundBlurriness = this.backgroundBlurriness;
  17719. if (this.backgroundIntensity !== 1) data.backgroundIntensity = this.backgroundIntensity;
  17720. return data;
  17721. }
  17722. // @deprecated
  17723. get autoUpdate() {
  17724. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17725. return this.matrixWorldAutoUpdate;
  17726. }
  17727. set autoUpdate(value) {
  17728. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17729. this.matrixWorldAutoUpdate = value;
  17730. }
  17731. }
  17732. class InterleavedBuffer {
  17733. constructor(array, stride) {
  17734. this.isInterleavedBuffer = true;
  17735. this.array = array;
  17736. this.stride = stride;
  17737. this.count = array !== undefined ? array.length / stride : 0;
  17738. this.usage = StaticDrawUsage;
  17739. this.updateRange = {
  17740. offset: 0,
  17741. count: -1
  17742. };
  17743. this.version = 0;
  17744. this.uuid = generateUUID();
  17745. }
  17746. onUploadCallback() {}
  17747. set needsUpdate(value) {
  17748. if (value === true) this.version++;
  17749. }
  17750. setUsage(value) {
  17751. this.usage = value;
  17752. return this;
  17753. }
  17754. copy(source) {
  17755. this.array = new source.array.constructor(source.array);
  17756. this.count = source.count;
  17757. this.stride = source.stride;
  17758. this.usage = source.usage;
  17759. return this;
  17760. }
  17761. copyAt(index1, attribute, index2) {
  17762. index1 *= this.stride;
  17763. index2 *= attribute.stride;
  17764. for (let i = 0, l = this.stride; i < l; i++) {
  17765. this.array[index1 + i] = attribute.array[index2 + i];
  17766. }
  17767. return this;
  17768. }
  17769. set(value, offset = 0) {
  17770. this.array.set(value, offset);
  17771. return this;
  17772. }
  17773. clone(data) {
  17774. if (data.arrayBuffers === undefined) {
  17775. data.arrayBuffers = {};
  17776. }
  17777. if (this.array.buffer._uuid === undefined) {
  17778. this.array.buffer._uuid = generateUUID();
  17779. }
  17780. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17781. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  17782. }
  17783. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  17784. const ib = new this.constructor(array, this.stride);
  17785. ib.setUsage(this.usage);
  17786. return ib;
  17787. }
  17788. onUpload(callback) {
  17789. this.onUploadCallback = callback;
  17790. return this;
  17791. }
  17792. toJSON(data) {
  17793. if (data.arrayBuffers === undefined) {
  17794. data.arrayBuffers = {};
  17795. }
  17796. // generate UUID for array buffer if necessary
  17797. if (this.array.buffer._uuid === undefined) {
  17798. this.array.buffer._uuid = generateUUID();
  17799. }
  17800. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17801. data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
  17802. }
  17803. //
  17804. return {
  17805. uuid: this.uuid,
  17806. buffer: this.array.buffer._uuid,
  17807. type: this.array.constructor.name,
  17808. stride: this.stride
  17809. };
  17810. }
  17811. }
  17812. const _vector$6 = /*@__PURE__*/new Vector3();
  17813. class InterleavedBufferAttribute {
  17814. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  17815. this.isInterleavedBufferAttribute = true;
  17816. this.name = '';
  17817. this.data = interleavedBuffer;
  17818. this.itemSize = itemSize;
  17819. this.offset = offset;
  17820. this.normalized = normalized === true;
  17821. }
  17822. get count() {
  17823. return this.data.count;
  17824. }
  17825. get array() {
  17826. return this.data.array;
  17827. }
  17828. set needsUpdate(value) {
  17829. this.data.needsUpdate = value;
  17830. }
  17831. applyMatrix4(m) {
  17832. for (let i = 0, l = this.data.count; i < l; i++) {
  17833. _vector$6.fromBufferAttribute(this, i);
  17834. _vector$6.applyMatrix4(m);
  17835. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17836. }
  17837. return this;
  17838. }
  17839. applyNormalMatrix(m) {
  17840. for (let i = 0, l = this.count; i < l; i++) {
  17841. _vector$6.fromBufferAttribute(this, i);
  17842. _vector$6.applyNormalMatrix(m);
  17843. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17844. }
  17845. return this;
  17846. }
  17847. transformDirection(m) {
  17848. for (let i = 0, l = this.count; i < l; i++) {
  17849. _vector$6.fromBufferAttribute(this, i);
  17850. _vector$6.transformDirection(m);
  17851. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17852. }
  17853. return this;
  17854. }
  17855. setX(index, x) {
  17856. if (this.normalized) x = normalize(x, this.array);
  17857. this.data.array[index * this.data.stride + this.offset] = x;
  17858. return this;
  17859. }
  17860. setY(index, y) {
  17861. if (this.normalized) y = normalize(y, this.array);
  17862. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17863. return this;
  17864. }
  17865. setZ(index, z) {
  17866. if (this.normalized) z = normalize(z, this.array);
  17867. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17868. return this;
  17869. }
  17870. setW(index, w) {
  17871. if (this.normalized) w = normalize(w, this.array);
  17872. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17873. return this;
  17874. }
  17875. getX(index) {
  17876. let x = this.data.array[index * this.data.stride + this.offset];
  17877. if (this.normalized) x = denormalize(x, this.array);
  17878. return x;
  17879. }
  17880. getY(index) {
  17881. let y = this.data.array[index * this.data.stride + this.offset + 1];
  17882. if (this.normalized) y = denormalize(y, this.array);
  17883. return y;
  17884. }
  17885. getZ(index) {
  17886. let z = this.data.array[index * this.data.stride + this.offset + 2];
  17887. if (this.normalized) z = denormalize(z, this.array);
  17888. return z;
  17889. }
  17890. getW(index) {
  17891. let w = this.data.array[index * this.data.stride + this.offset + 3];
  17892. if (this.normalized) w = denormalize(w, this.array);
  17893. return w;
  17894. }
  17895. setXY(index, x, y) {
  17896. index = index * this.data.stride + this.offset;
  17897. if (this.normalized) {
  17898. x = normalize(x, this.array);
  17899. y = normalize(y, this.array);
  17900. }
  17901. this.data.array[index + 0] = x;
  17902. this.data.array[index + 1] = y;
  17903. return this;
  17904. }
  17905. setXYZ(index, x, y, z) {
  17906. index = index * this.data.stride + this.offset;
  17907. if (this.normalized) {
  17908. x = normalize(x, this.array);
  17909. y = normalize(y, this.array);
  17910. z = normalize(z, this.array);
  17911. }
  17912. this.data.array[index + 0] = x;
  17913. this.data.array[index + 1] = y;
  17914. this.data.array[index + 2] = z;
  17915. return this;
  17916. }
  17917. setXYZW(index, x, y, z, w) {
  17918. index = index * this.data.stride + this.offset;
  17919. if (this.normalized) {
  17920. x = normalize(x, this.array);
  17921. y = normalize(y, this.array);
  17922. z = normalize(z, this.array);
  17923. w = normalize(w, this.array);
  17924. }
  17925. this.data.array[index + 0] = x;
  17926. this.data.array[index + 1] = y;
  17927. this.data.array[index + 2] = z;
  17928. this.data.array[index + 3] = w;
  17929. return this;
  17930. }
  17931. clone(data) {
  17932. if (data === undefined) {
  17933. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.');
  17934. const array = [];
  17935. for (let i = 0; i < this.count; i++) {
  17936. const index = i * this.data.stride + this.offset;
  17937. for (let j = 0; j < this.itemSize; j++) {
  17938. array.push(this.data.array[index + j]);
  17939. }
  17940. }
  17941. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17942. } else {
  17943. if (data.interleavedBuffers === undefined) {
  17944. data.interleavedBuffers = {};
  17945. }
  17946. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17947. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17948. }
  17949. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17950. }
  17951. }
  17952. toJSON(data) {
  17953. if (data === undefined) {
  17954. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.');
  17955. const array = [];
  17956. for (let i = 0; i < this.count; i++) {
  17957. const index = i * this.data.stride + this.offset;
  17958. for (let j = 0; j < this.itemSize; j++) {
  17959. array.push(this.data.array[index + j]);
  17960. }
  17961. }
  17962. // de-interleave data and save it as an ordinary buffer attribute for now
  17963. return {
  17964. itemSize: this.itemSize,
  17965. type: this.array.constructor.name,
  17966. array: array,
  17967. normalized: this.normalized
  17968. };
  17969. } else {
  17970. // save as true interleaved attribute
  17971. if (data.interleavedBuffers === undefined) {
  17972. data.interleavedBuffers = {};
  17973. }
  17974. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17975. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  17976. }
  17977. return {
  17978. isInterleavedBufferAttribute: true,
  17979. itemSize: this.itemSize,
  17980. data: this.data.uuid,
  17981. offset: this.offset,
  17982. normalized: this.normalized
  17983. };
  17984. }
  17985. }
  17986. }
  17987. class SpriteMaterial extends Material {
  17988. constructor(parameters) {
  17989. super();
  17990. this.isSpriteMaterial = true;
  17991. this.type = 'SpriteMaterial';
  17992. this.color = new Color(0xffffff);
  17993. this.map = null;
  17994. this.alphaMap = null;
  17995. this.rotation = 0;
  17996. this.sizeAttenuation = true;
  17997. this.transparent = true;
  17998. this.fog = true;
  17999. this.setValues(parameters);
  18000. }
  18001. copy(source) {
  18002. super.copy(source);
  18003. this.color.copy(source.color);
  18004. this.map = source.map;
  18005. this.alphaMap = source.alphaMap;
  18006. this.rotation = source.rotation;
  18007. this.sizeAttenuation = source.sizeAttenuation;
  18008. this.fog = source.fog;
  18009. return this;
  18010. }
  18011. }
  18012. let _geometry;
  18013. const _intersectPoint = /*@__PURE__*/new Vector3();
  18014. const _worldScale = /*@__PURE__*/new Vector3();
  18015. const _mvPosition = /*@__PURE__*/new Vector3();
  18016. const _alignedPosition = /*@__PURE__*/new Vector2();
  18017. const _rotatedPosition = /*@__PURE__*/new Vector2();
  18018. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  18019. const _vA = /*@__PURE__*/new Vector3();
  18020. const _vB = /*@__PURE__*/new Vector3();
  18021. const _vC = /*@__PURE__*/new Vector3();
  18022. const _uvA = /*@__PURE__*/new Vector2();
  18023. const _uvB = /*@__PURE__*/new Vector2();
  18024. const _uvC = /*@__PURE__*/new Vector2();
  18025. class Sprite extends Object3D {
  18026. constructor(material) {
  18027. super();
  18028. this.isSprite = true;
  18029. this.type = 'Sprite';
  18030. if (_geometry === undefined) {
  18031. _geometry = new BufferGeometry();
  18032. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  18033. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  18034. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  18035. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  18036. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  18037. }
  18038. this.geometry = _geometry;
  18039. this.material = material !== undefined ? material : new SpriteMaterial();
  18040. this.center = new Vector2(0.5, 0.5);
  18041. }
  18042. raycast(raycaster, intersects) {
  18043. if (raycaster.camera === null) {
  18044. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  18045. }
  18046. _worldScale.setFromMatrixScale(this.matrixWorld);
  18047. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  18048. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  18049. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  18050. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  18051. _worldScale.multiplyScalar(-_mvPosition.z);
  18052. }
  18053. const rotation = this.material.rotation;
  18054. let sin, cos;
  18055. if (rotation !== 0) {
  18056. cos = Math.cos(rotation);
  18057. sin = Math.sin(rotation);
  18058. }
  18059. const center = this.center;
  18060. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18061. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18062. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18063. _uvA.set(0, 0);
  18064. _uvB.set(1, 0);
  18065. _uvC.set(1, 1);
  18066. // check first triangle
  18067. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  18068. if (intersect === null) {
  18069. // check second triangle
  18070. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18071. _uvB.set(0, 1);
  18072. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  18073. if (intersect === null) {
  18074. return;
  18075. }
  18076. }
  18077. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  18078. if (distance < raycaster.near || distance > raycaster.far) return;
  18079. intersects.push({
  18080. distance: distance,
  18081. point: _intersectPoint.clone(),
  18082. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  18083. face: null,
  18084. object: this
  18085. });
  18086. }
  18087. copy(source, recursive) {
  18088. super.copy(source, recursive);
  18089. if (source.center !== undefined) this.center.copy(source.center);
  18090. this.material = source.material;
  18091. return this;
  18092. }
  18093. }
  18094. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  18095. // compute position in camera space
  18096. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale);
  18097. // to check if rotation is not zero
  18098. if (sin !== undefined) {
  18099. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  18100. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  18101. } else {
  18102. _rotatedPosition.copy(_alignedPosition);
  18103. }
  18104. vertexPosition.copy(mvPosition);
  18105. vertexPosition.x += _rotatedPosition.x;
  18106. vertexPosition.y += _rotatedPosition.y;
  18107. // transform to world space
  18108. vertexPosition.applyMatrix4(_viewWorldMatrix);
  18109. }
  18110. const _v1$2 = /*@__PURE__*/new Vector3();
  18111. const _v2$1 = /*@__PURE__*/new Vector3();
  18112. class LOD extends Object3D {
  18113. constructor() {
  18114. super();
  18115. this._currentLevel = 0;
  18116. this.type = 'LOD';
  18117. Object.defineProperties(this, {
  18118. levels: {
  18119. enumerable: true,
  18120. value: []
  18121. },
  18122. isLOD: {
  18123. value: true
  18124. }
  18125. });
  18126. this.autoUpdate = true;
  18127. }
  18128. copy(source) {
  18129. super.copy(source, false);
  18130. const levels = source.levels;
  18131. for (let i = 0, l = levels.length; i < l; i++) {
  18132. const level = levels[i];
  18133. this.addLevel(level.object.clone(), level.distance, level.hysteresis);
  18134. }
  18135. this.autoUpdate = source.autoUpdate;
  18136. return this;
  18137. }
  18138. addLevel(object, distance = 0, hysteresis = 0) {
  18139. distance = Math.abs(distance);
  18140. const levels = this.levels;
  18141. let l;
  18142. for (l = 0; l < levels.length; l++) {
  18143. if (distance < levels[l].distance) {
  18144. break;
  18145. }
  18146. }
  18147. levels.splice(l, 0, {
  18148. distance: distance,
  18149. hysteresis: hysteresis,
  18150. object: object
  18151. });
  18152. this.add(object);
  18153. return this;
  18154. }
  18155. getCurrentLevel() {
  18156. return this._currentLevel;
  18157. }
  18158. getObjectForDistance(distance) {
  18159. const levels = this.levels;
  18160. if (levels.length > 0) {
  18161. let i, l;
  18162. for (i = 1, l = levels.length; i < l; i++) {
  18163. let levelDistance = levels[i].distance;
  18164. if (levels[i].object.visible) {
  18165. levelDistance -= levelDistance * levels[i].hysteresis;
  18166. }
  18167. if (distance < levelDistance) {
  18168. break;
  18169. }
  18170. }
  18171. return levels[i - 1].object;
  18172. }
  18173. return null;
  18174. }
  18175. raycast(raycaster, intersects) {
  18176. const levels = this.levels;
  18177. if (levels.length > 0) {
  18178. _v1$2.setFromMatrixPosition(this.matrixWorld);
  18179. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  18180. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  18181. }
  18182. }
  18183. update(camera) {
  18184. const levels = this.levels;
  18185. if (levels.length > 1) {
  18186. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  18187. _v2$1.setFromMatrixPosition(this.matrixWorld);
  18188. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  18189. levels[0].object.visible = true;
  18190. let i, l;
  18191. for (i = 1, l = levels.length; i < l; i++) {
  18192. let levelDistance = levels[i].distance;
  18193. if (levels[i].object.visible) {
  18194. levelDistance -= levelDistance * levels[i].hysteresis;
  18195. }
  18196. if (distance >= levelDistance) {
  18197. levels[i - 1].object.visible = false;
  18198. levels[i].object.visible = true;
  18199. } else {
  18200. break;
  18201. }
  18202. }
  18203. this._currentLevel = i - 1;
  18204. for (; i < l; i++) {
  18205. levels[i].object.visible = false;
  18206. }
  18207. }
  18208. }
  18209. toJSON(meta) {
  18210. const data = super.toJSON(meta);
  18211. if (this.autoUpdate === false) data.object.autoUpdate = false;
  18212. data.object.levels = [];
  18213. const levels = this.levels;
  18214. for (let i = 0, l = levels.length; i < l; i++) {
  18215. const level = levels[i];
  18216. data.object.levels.push({
  18217. object: level.object.uuid,
  18218. distance: level.distance,
  18219. hysteresis: level.hysteresis
  18220. });
  18221. }
  18222. return data;
  18223. }
  18224. }
  18225. const _basePosition = /*@__PURE__*/new Vector3();
  18226. const _skinIndex = /*@__PURE__*/new Vector4();
  18227. const _skinWeight = /*@__PURE__*/new Vector4();
  18228. const _vector$5 = /*@__PURE__*/new Vector3();
  18229. const _matrix = /*@__PURE__*/new Matrix4();
  18230. class SkinnedMesh extends Mesh {
  18231. constructor(geometry, material) {
  18232. super(geometry, material);
  18233. this.isSkinnedMesh = true;
  18234. this.type = 'SkinnedMesh';
  18235. this.bindMode = 'attached';
  18236. this.bindMatrix = new Matrix4();
  18237. this.bindMatrixInverse = new Matrix4();
  18238. }
  18239. copy(source, recursive) {
  18240. super.copy(source, recursive);
  18241. this.bindMode = source.bindMode;
  18242. this.bindMatrix.copy(source.bindMatrix);
  18243. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  18244. this.skeleton = source.skeleton;
  18245. return this;
  18246. }
  18247. bind(skeleton, bindMatrix) {
  18248. this.skeleton = skeleton;
  18249. if (bindMatrix === undefined) {
  18250. this.updateMatrixWorld(true);
  18251. this.skeleton.calculateInverses();
  18252. bindMatrix = this.matrixWorld;
  18253. }
  18254. this.bindMatrix.copy(bindMatrix);
  18255. this.bindMatrixInverse.copy(bindMatrix).invert();
  18256. }
  18257. pose() {
  18258. this.skeleton.pose();
  18259. }
  18260. normalizeSkinWeights() {
  18261. const vector = new Vector4();
  18262. const skinWeight = this.geometry.attributes.skinWeight;
  18263. for (let i = 0, l = skinWeight.count; i < l; i++) {
  18264. vector.fromBufferAttribute(skinWeight, i);
  18265. const scale = 1.0 / vector.manhattanLength();
  18266. if (scale !== Infinity) {
  18267. vector.multiplyScalar(scale);
  18268. } else {
  18269. vector.set(1, 0, 0, 0); // do something reasonable
  18270. }
  18271. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  18272. }
  18273. }
  18274. updateMatrixWorld(force) {
  18275. super.updateMatrixWorld(force);
  18276. if (this.bindMode === 'attached') {
  18277. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  18278. } else if (this.bindMode === 'detached') {
  18279. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  18280. } else {
  18281. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  18282. }
  18283. }
  18284. boneTransform(index, target) {
  18285. const skeleton = this.skeleton;
  18286. const geometry = this.geometry;
  18287. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  18288. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  18289. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  18290. target.set(0, 0, 0);
  18291. for (let i = 0; i < 4; i++) {
  18292. const weight = _skinWeight.getComponent(i);
  18293. if (weight !== 0) {
  18294. const boneIndex = _skinIndex.getComponent(i);
  18295. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  18296. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  18297. }
  18298. }
  18299. return target.applyMatrix4(this.bindMatrixInverse);
  18300. }
  18301. }
  18302. class Bone extends Object3D {
  18303. constructor() {
  18304. super();
  18305. this.isBone = true;
  18306. this.type = 'Bone';
  18307. }
  18308. }
  18309. class DataTexture extends Texture {
  18310. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  18311. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18312. this.isDataTexture = true;
  18313. this.image = {
  18314. data: data,
  18315. width: width,
  18316. height: height
  18317. };
  18318. this.generateMipmaps = false;
  18319. this.flipY = false;
  18320. this.unpackAlignment = 1;
  18321. }
  18322. }
  18323. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  18324. const _identityMatrix = /*@__PURE__*/new Matrix4();
  18325. class Skeleton {
  18326. constructor(bones = [], boneInverses = []) {
  18327. this.uuid = generateUUID();
  18328. this.bones = bones.slice(0);
  18329. this.boneInverses = boneInverses;
  18330. this.boneMatrices = null;
  18331. this.boneTexture = null;
  18332. this.boneTextureSize = 0;
  18333. this.frame = -1;
  18334. this.init();
  18335. }
  18336. init() {
  18337. const bones = this.bones;
  18338. const boneInverses = this.boneInverses;
  18339. this.boneMatrices = new Float32Array(bones.length * 16);
  18340. // calculate inverse bone matrices if necessary
  18341. if (boneInverses.length === 0) {
  18342. this.calculateInverses();
  18343. } else {
  18344. // handle special case
  18345. if (bones.length !== boneInverses.length) {
  18346. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  18347. this.boneInverses = [];
  18348. for (let i = 0, il = this.bones.length; i < il; i++) {
  18349. this.boneInverses.push(new Matrix4());
  18350. }
  18351. }
  18352. }
  18353. }
  18354. calculateInverses() {
  18355. this.boneInverses.length = 0;
  18356. for (let i = 0, il = this.bones.length; i < il; i++) {
  18357. const inverse = new Matrix4();
  18358. if (this.bones[i]) {
  18359. inverse.copy(this.bones[i].matrixWorld).invert();
  18360. }
  18361. this.boneInverses.push(inverse);
  18362. }
  18363. }
  18364. pose() {
  18365. // recover the bind-time world matrices
  18366. for (let i = 0, il = this.bones.length; i < il; i++) {
  18367. const bone = this.bones[i];
  18368. if (bone) {
  18369. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  18370. }
  18371. }
  18372. // compute the local matrices, positions, rotations and scales
  18373. for (let i = 0, il = this.bones.length; i < il; i++) {
  18374. const bone = this.bones[i];
  18375. if (bone) {
  18376. if (bone.parent && bone.parent.isBone) {
  18377. bone.matrix.copy(bone.parent.matrixWorld).invert();
  18378. bone.matrix.multiply(bone.matrixWorld);
  18379. } else {
  18380. bone.matrix.copy(bone.matrixWorld);
  18381. }
  18382. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  18383. }
  18384. }
  18385. }
  18386. update() {
  18387. const bones = this.bones;
  18388. const boneInverses = this.boneInverses;
  18389. const boneMatrices = this.boneMatrices;
  18390. const boneTexture = this.boneTexture;
  18391. // flatten bone matrices to array
  18392. for (let i = 0, il = bones.length; i < il; i++) {
  18393. // compute the offset between the current and the original transform
  18394. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  18395. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  18396. _offsetMatrix.toArray(boneMatrices, i * 16);
  18397. }
  18398. if (boneTexture !== null) {
  18399. boneTexture.needsUpdate = true;
  18400. }
  18401. }
  18402. clone() {
  18403. return new Skeleton(this.bones, this.boneInverses);
  18404. }
  18405. computeBoneTexture() {
  18406. // layout (1 matrix = 4 pixels)
  18407. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18408. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18409. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18410. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18411. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18412. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  18413. size = ceilPowerOfTwo(size);
  18414. size = Math.max(size, 4);
  18415. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  18416. boneMatrices.set(this.boneMatrices); // copy current values
  18417. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  18418. boneTexture.needsUpdate = true;
  18419. this.boneMatrices = boneMatrices;
  18420. this.boneTexture = boneTexture;
  18421. this.boneTextureSize = size;
  18422. return this;
  18423. }
  18424. getBoneByName(name) {
  18425. for (let i = 0, il = this.bones.length; i < il; i++) {
  18426. const bone = this.bones[i];
  18427. if (bone.name === name) {
  18428. return bone;
  18429. }
  18430. }
  18431. return undefined;
  18432. }
  18433. dispose() {
  18434. if (this.boneTexture !== null) {
  18435. this.boneTexture.dispose();
  18436. this.boneTexture = null;
  18437. }
  18438. }
  18439. fromJSON(json, bones) {
  18440. this.uuid = json.uuid;
  18441. for (let i = 0, l = json.bones.length; i < l; i++) {
  18442. const uuid = json.bones[i];
  18443. let bone = bones[uuid];
  18444. if (bone === undefined) {
  18445. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  18446. bone = new Bone();
  18447. }
  18448. this.bones.push(bone);
  18449. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  18450. }
  18451. this.init();
  18452. return this;
  18453. }
  18454. toJSON() {
  18455. const data = {
  18456. metadata: {
  18457. version: 4.5,
  18458. type: 'Skeleton',
  18459. generator: 'Skeleton.toJSON'
  18460. },
  18461. bones: [],
  18462. boneInverses: []
  18463. };
  18464. data.uuid = this.uuid;
  18465. const bones = this.bones;
  18466. const boneInverses = this.boneInverses;
  18467. for (let i = 0, l = bones.length; i < l; i++) {
  18468. const bone = bones[i];
  18469. data.bones.push(bone.uuid);
  18470. const boneInverse = boneInverses[i];
  18471. data.boneInverses.push(boneInverse.toArray());
  18472. }
  18473. return data;
  18474. }
  18475. }
  18476. class InstancedBufferAttribute extends BufferAttribute {
  18477. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  18478. super(array, itemSize, normalized);
  18479. this.isInstancedBufferAttribute = true;
  18480. this.meshPerAttribute = meshPerAttribute;
  18481. }
  18482. copy(source) {
  18483. super.copy(source);
  18484. this.meshPerAttribute = source.meshPerAttribute;
  18485. return this;
  18486. }
  18487. toJSON() {
  18488. const data = super.toJSON();
  18489. data.meshPerAttribute = this.meshPerAttribute;
  18490. data.isInstancedBufferAttribute = true;
  18491. return data;
  18492. }
  18493. }
  18494. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  18495. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  18496. const _instanceIntersects = [];
  18497. const _identity = /*@__PURE__*/new Matrix4();
  18498. const _mesh = /*@__PURE__*/new Mesh();
  18499. class InstancedMesh extends Mesh {
  18500. constructor(geometry, material, count) {
  18501. super(geometry, material);
  18502. this.isInstancedMesh = true;
  18503. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  18504. this.instanceColor = null;
  18505. this.count = count;
  18506. this.frustumCulled = false;
  18507. for (let i = 0; i < count; i++) {
  18508. this.setMatrixAt(i, _identity);
  18509. }
  18510. }
  18511. copy(source, recursive) {
  18512. super.copy(source, recursive);
  18513. this.instanceMatrix.copy(source.instanceMatrix);
  18514. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  18515. this.count = source.count;
  18516. return this;
  18517. }
  18518. getColorAt(index, color) {
  18519. color.fromArray(this.instanceColor.array, index * 3);
  18520. }
  18521. getMatrixAt(index, matrix) {
  18522. matrix.fromArray(this.instanceMatrix.array, index * 16);
  18523. }
  18524. raycast(raycaster, intersects) {
  18525. const matrixWorld = this.matrixWorld;
  18526. const raycastTimes = this.count;
  18527. _mesh.geometry = this.geometry;
  18528. _mesh.material = this.material;
  18529. if (_mesh.material === undefined) return;
  18530. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  18531. // calculate the world matrix for each instance
  18532. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  18533. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix);
  18534. // the mesh represents this single instance
  18535. _mesh.matrixWorld = _instanceWorldMatrix;
  18536. _mesh.raycast(raycaster, _instanceIntersects);
  18537. // process the result of raycast
  18538. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  18539. const intersect = _instanceIntersects[i];
  18540. intersect.instanceId = instanceId;
  18541. intersect.object = this;
  18542. intersects.push(intersect);
  18543. }
  18544. _instanceIntersects.length = 0;
  18545. }
  18546. }
  18547. setColorAt(index, color) {
  18548. if (this.instanceColor === null) {
  18549. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  18550. }
  18551. color.toArray(this.instanceColor.array, index * 3);
  18552. }
  18553. setMatrixAt(index, matrix) {
  18554. matrix.toArray(this.instanceMatrix.array, index * 16);
  18555. }
  18556. updateMorphTargets() {}
  18557. dispose() {
  18558. this.dispatchEvent({
  18559. type: 'dispose'
  18560. });
  18561. }
  18562. }
  18563. class LineBasicMaterial extends Material {
  18564. constructor(parameters) {
  18565. super();
  18566. this.isLineBasicMaterial = true;
  18567. this.type = 'LineBasicMaterial';
  18568. this.color = new Color(0xffffff);
  18569. this.linewidth = 1;
  18570. this.linecap = 'round';
  18571. this.linejoin = 'round';
  18572. this.fog = true;
  18573. this.setValues(parameters);
  18574. }
  18575. copy(source) {
  18576. super.copy(source);
  18577. this.color.copy(source.color);
  18578. this.linewidth = source.linewidth;
  18579. this.linecap = source.linecap;
  18580. this.linejoin = source.linejoin;
  18581. this.fog = source.fog;
  18582. return this;
  18583. }
  18584. }
  18585. const _start$1 = /*@__PURE__*/new Vector3();
  18586. const _end$1 = /*@__PURE__*/new Vector3();
  18587. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  18588. const _ray$1 = /*@__PURE__*/new Ray();
  18589. const _sphere$1 = /*@__PURE__*/new Sphere();
  18590. class Line extends Object3D {
  18591. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  18592. super();
  18593. this.isLine = true;
  18594. this.type = 'Line';
  18595. this.geometry = geometry;
  18596. this.material = material;
  18597. this.updateMorphTargets();
  18598. }
  18599. copy(source, recursive) {
  18600. super.copy(source, recursive);
  18601. this.material = source.material;
  18602. this.geometry = source.geometry;
  18603. return this;
  18604. }
  18605. computeLineDistances() {
  18606. const geometry = this.geometry;
  18607. // we assume non-indexed geometry
  18608. if (geometry.index === null) {
  18609. const positionAttribute = geometry.attributes.position;
  18610. const lineDistances = [0];
  18611. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  18612. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  18613. _end$1.fromBufferAttribute(positionAttribute, i);
  18614. lineDistances[i] = lineDistances[i - 1];
  18615. lineDistances[i] += _start$1.distanceTo(_end$1);
  18616. }
  18617. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18618. } else {
  18619. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18620. }
  18621. return this;
  18622. }
  18623. raycast(raycaster, intersects) {
  18624. const geometry = this.geometry;
  18625. const matrixWorld = this.matrixWorld;
  18626. const threshold = raycaster.params.Line.threshold;
  18627. const drawRange = geometry.drawRange;
  18628. // Checking boundingSphere distance to ray
  18629. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18630. _sphere$1.copy(geometry.boundingSphere);
  18631. _sphere$1.applyMatrix4(matrixWorld);
  18632. _sphere$1.radius += threshold;
  18633. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return;
  18634. //
  18635. _inverseMatrix$1.copy(matrixWorld).invert();
  18636. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  18637. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18638. const localThresholdSq = localThreshold * localThreshold;
  18639. const vStart = new Vector3();
  18640. const vEnd = new Vector3();
  18641. const interSegment = new Vector3();
  18642. const interRay = new Vector3();
  18643. const step = this.isLineSegments ? 2 : 1;
  18644. const index = geometry.index;
  18645. const attributes = geometry.attributes;
  18646. const positionAttribute = attributes.position;
  18647. if (index !== null) {
  18648. const start = Math.max(0, drawRange.start);
  18649. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18650. for (let i = start, l = end - 1; i < l; i += step) {
  18651. const a = index.getX(i);
  18652. const b = index.getX(i + 1);
  18653. vStart.fromBufferAttribute(positionAttribute, a);
  18654. vEnd.fromBufferAttribute(positionAttribute, b);
  18655. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18656. if (distSq > localThresholdSq) continue;
  18657. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18658. const distance = raycaster.ray.origin.distanceTo(interRay);
  18659. if (distance < raycaster.near || distance > raycaster.far) continue;
  18660. intersects.push({
  18661. distance: distance,
  18662. // What do we want? intersection point on the ray or on the segment??
  18663. // point: raycaster.ray.at( distance ),
  18664. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18665. index: i,
  18666. face: null,
  18667. faceIndex: null,
  18668. object: this
  18669. });
  18670. }
  18671. } else {
  18672. const start = Math.max(0, drawRange.start);
  18673. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18674. for (let i = start, l = end - 1; i < l; i += step) {
  18675. vStart.fromBufferAttribute(positionAttribute, i);
  18676. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  18677. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18678. if (distSq > localThresholdSq) continue;
  18679. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18680. const distance = raycaster.ray.origin.distanceTo(interRay);
  18681. if (distance < raycaster.near || distance > raycaster.far) continue;
  18682. intersects.push({
  18683. distance: distance,
  18684. // What do we want? intersection point on the ray or on the segment??
  18685. // point: raycaster.ray.at( distance ),
  18686. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18687. index: i,
  18688. face: null,
  18689. faceIndex: null,
  18690. object: this
  18691. });
  18692. }
  18693. }
  18694. }
  18695. updateMorphTargets() {
  18696. const geometry = this.geometry;
  18697. const morphAttributes = geometry.morphAttributes;
  18698. const keys = Object.keys(morphAttributes);
  18699. if (keys.length > 0) {
  18700. const morphAttribute = morphAttributes[keys[0]];
  18701. if (morphAttribute !== undefined) {
  18702. this.morphTargetInfluences = [];
  18703. this.morphTargetDictionary = {};
  18704. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18705. const name = morphAttribute[m].name || String(m);
  18706. this.morphTargetInfluences.push(0);
  18707. this.morphTargetDictionary[name] = m;
  18708. }
  18709. }
  18710. }
  18711. }
  18712. }
  18713. const _start = /*@__PURE__*/new Vector3();
  18714. const _end = /*@__PURE__*/new Vector3();
  18715. class LineSegments extends Line {
  18716. constructor(geometry, material) {
  18717. super(geometry, material);
  18718. this.isLineSegments = true;
  18719. this.type = 'LineSegments';
  18720. }
  18721. computeLineDistances() {
  18722. const geometry = this.geometry;
  18723. // we assume non-indexed geometry
  18724. if (geometry.index === null) {
  18725. const positionAttribute = geometry.attributes.position;
  18726. const lineDistances = [];
  18727. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  18728. _start.fromBufferAttribute(positionAttribute, i);
  18729. _end.fromBufferAttribute(positionAttribute, i + 1);
  18730. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  18731. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  18732. }
  18733. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18734. } else {
  18735. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18736. }
  18737. return this;
  18738. }
  18739. }
  18740. class LineLoop extends Line {
  18741. constructor(geometry, material) {
  18742. super(geometry, material);
  18743. this.isLineLoop = true;
  18744. this.type = 'LineLoop';
  18745. }
  18746. }
  18747. class PointsMaterial extends Material {
  18748. constructor(parameters) {
  18749. super();
  18750. this.isPointsMaterial = true;
  18751. this.type = 'PointsMaterial';
  18752. this.color = new Color(0xffffff);
  18753. this.map = null;
  18754. this.alphaMap = null;
  18755. this.size = 1;
  18756. this.sizeAttenuation = true;
  18757. this.fog = true;
  18758. this.setValues(parameters);
  18759. }
  18760. copy(source) {
  18761. super.copy(source);
  18762. this.color.copy(source.color);
  18763. this.map = source.map;
  18764. this.alphaMap = source.alphaMap;
  18765. this.size = source.size;
  18766. this.sizeAttenuation = source.sizeAttenuation;
  18767. this.fog = source.fog;
  18768. return this;
  18769. }
  18770. }
  18771. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  18772. const _ray = /*@__PURE__*/new Ray();
  18773. const _sphere = /*@__PURE__*/new Sphere();
  18774. const _position$2 = /*@__PURE__*/new Vector3();
  18775. class Points extends Object3D {
  18776. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  18777. super();
  18778. this.isPoints = true;
  18779. this.type = 'Points';
  18780. this.geometry = geometry;
  18781. this.material = material;
  18782. this.updateMorphTargets();
  18783. }
  18784. copy(source, recursive) {
  18785. super.copy(source, recursive);
  18786. this.material = source.material;
  18787. this.geometry = source.geometry;
  18788. return this;
  18789. }
  18790. raycast(raycaster, intersects) {
  18791. const geometry = this.geometry;
  18792. const matrixWorld = this.matrixWorld;
  18793. const threshold = raycaster.params.Points.threshold;
  18794. const drawRange = geometry.drawRange;
  18795. // Checking boundingSphere distance to ray
  18796. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18797. _sphere.copy(geometry.boundingSphere);
  18798. _sphere.applyMatrix4(matrixWorld);
  18799. _sphere.radius += threshold;
  18800. if (raycaster.ray.intersectsSphere(_sphere) === false) return;
  18801. //
  18802. _inverseMatrix.copy(matrixWorld).invert();
  18803. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  18804. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18805. const localThresholdSq = localThreshold * localThreshold;
  18806. const index = geometry.index;
  18807. const attributes = geometry.attributes;
  18808. const positionAttribute = attributes.position;
  18809. if (index !== null) {
  18810. const start = Math.max(0, drawRange.start);
  18811. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18812. for (let i = start, il = end; i < il; i++) {
  18813. const a = index.getX(i);
  18814. _position$2.fromBufferAttribute(positionAttribute, a);
  18815. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18816. }
  18817. } else {
  18818. const start = Math.max(0, drawRange.start);
  18819. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18820. for (let i = start, l = end; i < l; i++) {
  18821. _position$2.fromBufferAttribute(positionAttribute, i);
  18822. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18823. }
  18824. }
  18825. }
  18826. updateMorphTargets() {
  18827. const geometry = this.geometry;
  18828. const morphAttributes = geometry.morphAttributes;
  18829. const keys = Object.keys(morphAttributes);
  18830. if (keys.length > 0) {
  18831. const morphAttribute = morphAttributes[keys[0]];
  18832. if (morphAttribute !== undefined) {
  18833. this.morphTargetInfluences = [];
  18834. this.morphTargetDictionary = {};
  18835. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18836. const name = morphAttribute[m].name || String(m);
  18837. this.morphTargetInfluences.push(0);
  18838. this.morphTargetDictionary[name] = m;
  18839. }
  18840. }
  18841. }
  18842. }
  18843. }
  18844. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  18845. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  18846. if (rayPointDistanceSq < localThresholdSq) {
  18847. const intersectPoint = new Vector3();
  18848. _ray.closestPointToPoint(point, intersectPoint);
  18849. intersectPoint.applyMatrix4(matrixWorld);
  18850. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  18851. if (distance < raycaster.near || distance > raycaster.far) return;
  18852. intersects.push({
  18853. distance: distance,
  18854. distanceToRay: Math.sqrt(rayPointDistanceSq),
  18855. point: intersectPoint,
  18856. index: index,
  18857. face: null,
  18858. object: object
  18859. });
  18860. }
  18861. }
  18862. class VideoTexture extends Texture {
  18863. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18864. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18865. this.isVideoTexture = true;
  18866. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18867. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18868. this.generateMipmaps = false;
  18869. const scope = this;
  18870. function updateVideo() {
  18871. scope.needsUpdate = true;
  18872. video.requestVideoFrameCallback(updateVideo);
  18873. }
  18874. if ('requestVideoFrameCallback' in video) {
  18875. video.requestVideoFrameCallback(updateVideo);
  18876. }
  18877. }
  18878. clone() {
  18879. return new this.constructor(this.image).copy(this);
  18880. }
  18881. update() {
  18882. const video = this.image;
  18883. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18884. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18885. this.needsUpdate = true;
  18886. }
  18887. }
  18888. }
  18889. class FramebufferTexture extends Texture {
  18890. constructor(width, height, format) {
  18891. super({
  18892. width,
  18893. height
  18894. });
  18895. this.isFramebufferTexture = true;
  18896. this.format = format;
  18897. this.magFilter = NearestFilter;
  18898. this.minFilter = NearestFilter;
  18899. this.generateMipmaps = false;
  18900. this.needsUpdate = true;
  18901. }
  18902. }
  18903. class CompressedTexture extends Texture {
  18904. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18905. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18906. this.isCompressedTexture = true;
  18907. this.image = {
  18908. width: width,
  18909. height: height
  18910. };
  18911. this.mipmaps = mipmaps;
  18912. // no flipping for cube textures
  18913. // (also flipping doesn't work for compressed textures )
  18914. this.flipY = false;
  18915. // can't generate mipmaps for compressed textures
  18916. // mips must be embedded in DDS files
  18917. this.generateMipmaps = false;
  18918. }
  18919. }
  18920. class CompressedArrayTexture extends CompressedTexture {
  18921. constructor(mipmaps, width, height, depth, format, type) {
  18922. super(mipmaps, width, height, format, type);
  18923. this.isCompressedArrayTexture = true;
  18924. this.image.depth = depth;
  18925. this.wrapR = ClampToEdgeWrapping;
  18926. }
  18927. }
  18928. class CanvasTexture extends Texture {
  18929. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18930. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18931. this.isCanvasTexture = true;
  18932. this.needsUpdate = true;
  18933. }
  18934. }
  18935. /**
  18936. * Extensible curve object.
  18937. *
  18938. * Some common of curve methods:
  18939. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18940. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18941. * .getPoints(), .getSpacedPoints()
  18942. * .getLength()
  18943. * .updateArcLengths()
  18944. *
  18945. * This following curves inherit from THREE.Curve:
  18946. *
  18947. * -- 2D curves --
  18948. * THREE.ArcCurve
  18949. * THREE.CubicBezierCurve
  18950. * THREE.EllipseCurve
  18951. * THREE.LineCurve
  18952. * THREE.QuadraticBezierCurve
  18953. * THREE.SplineCurve
  18954. *
  18955. * -- 3D curves --
  18956. * THREE.CatmullRomCurve3
  18957. * THREE.CubicBezierCurve3
  18958. * THREE.LineCurve3
  18959. * THREE.QuadraticBezierCurve3
  18960. *
  18961. * A series of curves can be represented as a THREE.CurvePath.
  18962. *
  18963. **/
  18964. class Curve {
  18965. constructor() {
  18966. this.type = 'Curve';
  18967. this.arcLengthDivisions = 200;
  18968. }
  18969. // Virtual base class method to overwrite and implement in subclasses
  18970. // - t [0 .. 1]
  18971. getPoint() {
  18972. console.warn('THREE.Curve: .getPoint() not implemented.');
  18973. return null;
  18974. }
  18975. // Get point at relative position in curve according to arc length
  18976. // - u [0 .. 1]
  18977. getPointAt(u, optionalTarget) {
  18978. const t = this.getUtoTmapping(u);
  18979. return this.getPoint(t, optionalTarget);
  18980. }
  18981. // Get sequence of points using getPoint( t )
  18982. getPoints(divisions = 5) {
  18983. const points = [];
  18984. for (let d = 0; d <= divisions; d++) {
  18985. points.push(this.getPoint(d / divisions));
  18986. }
  18987. return points;
  18988. }
  18989. // Get sequence of points using getPointAt( u )
  18990. getSpacedPoints(divisions = 5) {
  18991. const points = [];
  18992. for (let d = 0; d <= divisions; d++) {
  18993. points.push(this.getPointAt(d / divisions));
  18994. }
  18995. return points;
  18996. }
  18997. // Get total curve arc length
  18998. getLength() {
  18999. const lengths = this.getLengths();
  19000. return lengths[lengths.length - 1];
  19001. }
  19002. // Get list of cumulative segment lengths
  19003. getLengths(divisions = this.arcLengthDivisions) {
  19004. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  19005. return this.cacheArcLengths;
  19006. }
  19007. this.needsUpdate = false;
  19008. const cache = [];
  19009. let current,
  19010. last = this.getPoint(0);
  19011. let sum = 0;
  19012. cache.push(0);
  19013. for (let p = 1; p <= divisions; p++) {
  19014. current = this.getPoint(p / divisions);
  19015. sum += current.distanceTo(last);
  19016. cache.push(sum);
  19017. last = current;
  19018. }
  19019. this.cacheArcLengths = cache;
  19020. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19021. }
  19022. updateArcLengths() {
  19023. this.needsUpdate = true;
  19024. this.getLengths();
  19025. }
  19026. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19027. getUtoTmapping(u, distance) {
  19028. const arcLengths = this.getLengths();
  19029. let i = 0;
  19030. const il = arcLengths.length;
  19031. let targetArcLength; // The targeted u distance value to get
  19032. if (distance) {
  19033. targetArcLength = distance;
  19034. } else {
  19035. targetArcLength = u * arcLengths[il - 1];
  19036. }
  19037. // binary search for the index with largest value smaller than target u distance
  19038. let low = 0,
  19039. high = il - 1,
  19040. comparison;
  19041. while (low <= high) {
  19042. 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
  19043. comparison = arcLengths[i] - targetArcLength;
  19044. if (comparison < 0) {
  19045. low = i + 1;
  19046. } else if (comparison > 0) {
  19047. high = i - 1;
  19048. } else {
  19049. high = i;
  19050. break;
  19051. // DONE
  19052. }
  19053. }
  19054. i = high;
  19055. if (arcLengths[i] === targetArcLength) {
  19056. return i / (il - 1);
  19057. }
  19058. // we could get finer grain at lengths, or use simple interpolation between two points
  19059. const lengthBefore = arcLengths[i];
  19060. const lengthAfter = arcLengths[i + 1];
  19061. const segmentLength = lengthAfter - lengthBefore;
  19062. // determine where we are between the 'before' and 'after' points
  19063. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength;
  19064. // add that fractional amount to t
  19065. const t = (i + segmentFraction) / (il - 1);
  19066. return t;
  19067. }
  19068. // Returns a unit vector tangent at t
  19069. // In case any sub curve does not implement its tangent derivation,
  19070. // 2 points a small delta apart will be used to find its gradient
  19071. // which seems to give a reasonable approximation
  19072. getTangent(t, optionalTarget) {
  19073. const delta = 0.0001;
  19074. let t1 = t - delta;
  19075. let t2 = t + delta;
  19076. // Capping in case of danger
  19077. if (t1 < 0) t1 = 0;
  19078. if (t2 > 1) t2 = 1;
  19079. const pt1 = this.getPoint(t1);
  19080. const pt2 = this.getPoint(t2);
  19081. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  19082. tangent.copy(pt2).sub(pt1).normalize();
  19083. return tangent;
  19084. }
  19085. getTangentAt(u, optionalTarget) {
  19086. const t = this.getUtoTmapping(u);
  19087. return this.getTangent(t, optionalTarget);
  19088. }
  19089. computeFrenetFrames(segments, closed) {
  19090. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19091. const normal = new Vector3();
  19092. const tangents = [];
  19093. const normals = [];
  19094. const binormals = [];
  19095. const vec = new Vector3();
  19096. const mat = new Matrix4();
  19097. // compute the tangent vectors for each segment on the curve
  19098. for (let i = 0; i <= segments; i++) {
  19099. const u = i / segments;
  19100. tangents[i] = this.getTangentAt(u, new Vector3());
  19101. }
  19102. // select an initial normal vector perpendicular to the first tangent vector,
  19103. // and in the direction of the minimum tangent xyz component
  19104. normals[0] = new Vector3();
  19105. binormals[0] = new Vector3();
  19106. let min = Number.MAX_VALUE;
  19107. const tx = Math.abs(tangents[0].x);
  19108. const ty = Math.abs(tangents[0].y);
  19109. const tz = Math.abs(tangents[0].z);
  19110. if (tx <= min) {
  19111. min = tx;
  19112. normal.set(1, 0, 0);
  19113. }
  19114. if (ty <= min) {
  19115. min = ty;
  19116. normal.set(0, 1, 0);
  19117. }
  19118. if (tz <= min) {
  19119. normal.set(0, 0, 1);
  19120. }
  19121. vec.crossVectors(tangents[0], normal).normalize();
  19122. normals[0].crossVectors(tangents[0], vec);
  19123. binormals[0].crossVectors(tangents[0], normals[0]);
  19124. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19125. for (let i = 1; i <= segments; i++) {
  19126. normals[i] = normals[i - 1].clone();
  19127. binormals[i] = binormals[i - 1].clone();
  19128. vec.crossVectors(tangents[i - 1], tangents[i]);
  19129. if (vec.length() > Number.EPSILON) {
  19130. vec.normalize();
  19131. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  19132. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  19133. }
  19134. binormals[i].crossVectors(tangents[i], normals[i]);
  19135. }
  19136. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19137. if (closed === true) {
  19138. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  19139. theta /= segments;
  19140. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  19141. theta = -theta;
  19142. }
  19143. for (let i = 1; i <= segments; i++) {
  19144. // twist a little...
  19145. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  19146. binormals[i].crossVectors(tangents[i], normals[i]);
  19147. }
  19148. }
  19149. return {
  19150. tangents: tangents,
  19151. normals: normals,
  19152. binormals: binormals
  19153. };
  19154. }
  19155. clone() {
  19156. return new this.constructor().copy(this);
  19157. }
  19158. copy(source) {
  19159. this.arcLengthDivisions = source.arcLengthDivisions;
  19160. return this;
  19161. }
  19162. toJSON() {
  19163. const data = {
  19164. metadata: {
  19165. version: 4.5,
  19166. type: 'Curve',
  19167. generator: 'Curve.toJSON'
  19168. }
  19169. };
  19170. data.arcLengthDivisions = this.arcLengthDivisions;
  19171. data.type = this.type;
  19172. return data;
  19173. }
  19174. fromJSON(json) {
  19175. this.arcLengthDivisions = json.arcLengthDivisions;
  19176. return this;
  19177. }
  19178. }
  19179. class EllipseCurve extends Curve {
  19180. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  19181. super();
  19182. this.isEllipseCurve = true;
  19183. this.type = 'EllipseCurve';
  19184. this.aX = aX;
  19185. this.aY = aY;
  19186. this.xRadius = xRadius;
  19187. this.yRadius = yRadius;
  19188. this.aStartAngle = aStartAngle;
  19189. this.aEndAngle = aEndAngle;
  19190. this.aClockwise = aClockwise;
  19191. this.aRotation = aRotation;
  19192. }
  19193. getPoint(t, optionalTarget) {
  19194. const point = optionalTarget || new Vector2();
  19195. const twoPi = Math.PI * 2;
  19196. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19197. const samePoints = Math.abs(deltaAngle) < Number.EPSILON;
  19198. // ensures that deltaAngle is 0 .. 2 PI
  19199. while (deltaAngle < 0) deltaAngle += twoPi;
  19200. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  19201. if (deltaAngle < Number.EPSILON) {
  19202. if (samePoints) {
  19203. deltaAngle = 0;
  19204. } else {
  19205. deltaAngle = twoPi;
  19206. }
  19207. }
  19208. if (this.aClockwise === true && !samePoints) {
  19209. if (deltaAngle === twoPi) {
  19210. deltaAngle = -twoPi;
  19211. } else {
  19212. deltaAngle = deltaAngle - twoPi;
  19213. }
  19214. }
  19215. const angle = this.aStartAngle + t * deltaAngle;
  19216. let x = this.aX + this.xRadius * Math.cos(angle);
  19217. let y = this.aY + this.yRadius * Math.sin(angle);
  19218. if (this.aRotation !== 0) {
  19219. const cos = Math.cos(this.aRotation);
  19220. const sin = Math.sin(this.aRotation);
  19221. const tx = x - this.aX;
  19222. const ty = y - this.aY;
  19223. // Rotate the point about the center of the ellipse.
  19224. x = tx * cos - ty * sin + this.aX;
  19225. y = tx * sin + ty * cos + this.aY;
  19226. }
  19227. return point.set(x, y);
  19228. }
  19229. copy(source) {
  19230. super.copy(source);
  19231. this.aX = source.aX;
  19232. this.aY = source.aY;
  19233. this.xRadius = source.xRadius;
  19234. this.yRadius = source.yRadius;
  19235. this.aStartAngle = source.aStartAngle;
  19236. this.aEndAngle = source.aEndAngle;
  19237. this.aClockwise = source.aClockwise;
  19238. this.aRotation = source.aRotation;
  19239. return this;
  19240. }
  19241. toJSON() {
  19242. const data = super.toJSON();
  19243. data.aX = this.aX;
  19244. data.aY = this.aY;
  19245. data.xRadius = this.xRadius;
  19246. data.yRadius = this.yRadius;
  19247. data.aStartAngle = this.aStartAngle;
  19248. data.aEndAngle = this.aEndAngle;
  19249. data.aClockwise = this.aClockwise;
  19250. data.aRotation = this.aRotation;
  19251. return data;
  19252. }
  19253. fromJSON(json) {
  19254. super.fromJSON(json);
  19255. this.aX = json.aX;
  19256. this.aY = json.aY;
  19257. this.xRadius = json.xRadius;
  19258. this.yRadius = json.yRadius;
  19259. this.aStartAngle = json.aStartAngle;
  19260. this.aEndAngle = json.aEndAngle;
  19261. this.aClockwise = json.aClockwise;
  19262. this.aRotation = json.aRotation;
  19263. return this;
  19264. }
  19265. }
  19266. class ArcCurve extends EllipseCurve {
  19267. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19268. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19269. this.isArcCurve = true;
  19270. this.type = 'ArcCurve';
  19271. }
  19272. }
  19273. /**
  19274. * Centripetal CatmullRom Curve - which is useful for avoiding
  19275. * cusps and self-intersections in non-uniform catmull rom curves.
  19276. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19277. *
  19278. * curve.type accepts centripetal(default), chordal and catmullrom
  19279. * curve.tension is used for catmullrom which defaults to 0.5
  19280. */
  19281. /*
  19282. Based on an optimized c++ solution in
  19283. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19284. - http://ideone.com/NoEbVM
  19285. This CubicPoly class could be used for reusing some variables and calculations,
  19286. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19287. which can be placed in CurveUtils.
  19288. */
  19289. function CubicPoly() {
  19290. let c0 = 0,
  19291. c1 = 0,
  19292. c2 = 0,
  19293. c3 = 0;
  19294. /*
  19295. * Compute coefficients for a cubic polynomial
  19296. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19297. * such that
  19298. * p(0) = x0, p(1) = x1
  19299. * and
  19300. * p'(0) = t0, p'(1) = t1.
  19301. */
  19302. function init(x0, x1, t0, t1) {
  19303. c0 = x0;
  19304. c1 = t0;
  19305. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  19306. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19307. }
  19308. return {
  19309. initCatmullRom: function (x0, x1, x2, x3, tension) {
  19310. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  19311. },
  19312. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  19313. // compute tangents when parameterized in [t1,t2]
  19314. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  19315. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2;
  19316. // rescale tangents for parametrization in [0,1]
  19317. t1 *= dt1;
  19318. t2 *= dt1;
  19319. init(x1, x2, t1, t2);
  19320. },
  19321. calc: function (t) {
  19322. const t2 = t * t;
  19323. const t3 = t2 * t;
  19324. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19325. }
  19326. };
  19327. }
  19328. //
  19329. const tmp = /*@__PURE__*/new Vector3();
  19330. const px = /*@__PURE__*/new CubicPoly();
  19331. const py = /*@__PURE__*/new CubicPoly();
  19332. const pz = /*@__PURE__*/new CubicPoly();
  19333. class CatmullRomCurve3 extends Curve {
  19334. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  19335. super();
  19336. this.isCatmullRomCurve3 = true;
  19337. this.type = 'CatmullRomCurve3';
  19338. this.points = points;
  19339. this.closed = closed;
  19340. this.curveType = curveType;
  19341. this.tension = tension;
  19342. }
  19343. getPoint(t, optionalTarget = new Vector3()) {
  19344. const point = optionalTarget;
  19345. const points = this.points;
  19346. const l = points.length;
  19347. const p = (l - (this.closed ? 0 : 1)) * t;
  19348. let intPoint = Math.floor(p);
  19349. let weight = p - intPoint;
  19350. if (this.closed) {
  19351. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  19352. } else if (weight === 0 && intPoint === l - 1) {
  19353. intPoint = l - 2;
  19354. weight = 1;
  19355. }
  19356. let p0, p3; // 4 points (p1 & p2 defined below)
  19357. if (this.closed || intPoint > 0) {
  19358. p0 = points[(intPoint - 1) % l];
  19359. } else {
  19360. // extrapolate first point
  19361. tmp.subVectors(points[0], points[1]).add(points[0]);
  19362. p0 = tmp;
  19363. }
  19364. const p1 = points[intPoint % l];
  19365. const p2 = points[(intPoint + 1) % l];
  19366. if (this.closed || intPoint + 2 < l) {
  19367. p3 = points[(intPoint + 2) % l];
  19368. } else {
  19369. // extrapolate last point
  19370. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  19371. p3 = tmp;
  19372. }
  19373. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  19374. // init Centripetal / Chordal Catmull-Rom
  19375. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19376. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  19377. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  19378. let dt2 = Math.pow(p2.distanceToSquared(p3), pow);
  19379. // safety check for repeated points
  19380. if (dt1 < 1e-4) dt1 = 1.0;
  19381. if (dt0 < 1e-4) dt0 = dt1;
  19382. if (dt2 < 1e-4) dt2 = dt1;
  19383. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  19384. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  19385. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  19386. } else if (this.curveType === 'catmullrom') {
  19387. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  19388. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  19389. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  19390. }
  19391. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  19392. return point;
  19393. }
  19394. copy(source) {
  19395. super.copy(source);
  19396. this.points = [];
  19397. for (let i = 0, l = source.points.length; i < l; i++) {
  19398. const point = source.points[i];
  19399. this.points.push(point.clone());
  19400. }
  19401. this.closed = source.closed;
  19402. this.curveType = source.curveType;
  19403. this.tension = source.tension;
  19404. return this;
  19405. }
  19406. toJSON() {
  19407. const data = super.toJSON();
  19408. data.points = [];
  19409. for (let i = 0, l = this.points.length; i < l; i++) {
  19410. const point = this.points[i];
  19411. data.points.push(point.toArray());
  19412. }
  19413. data.closed = this.closed;
  19414. data.curveType = this.curveType;
  19415. data.tension = this.tension;
  19416. return data;
  19417. }
  19418. fromJSON(json) {
  19419. super.fromJSON(json);
  19420. this.points = [];
  19421. for (let i = 0, l = json.points.length; i < l; i++) {
  19422. const point = json.points[i];
  19423. this.points.push(new Vector3().fromArray(point));
  19424. }
  19425. this.closed = json.closed;
  19426. this.curveType = json.curveType;
  19427. this.tension = json.tension;
  19428. return this;
  19429. }
  19430. }
  19431. /**
  19432. * Bezier Curves formulas obtained from
  19433. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19434. */
  19435. function CatmullRom(t, p0, p1, p2, p3) {
  19436. const v0 = (p2 - p0) * 0.5;
  19437. const v1 = (p3 - p1) * 0.5;
  19438. const t2 = t * t;
  19439. const t3 = t * t2;
  19440. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  19441. }
  19442. //
  19443. function QuadraticBezierP0(t, p) {
  19444. const k = 1 - t;
  19445. return k * k * p;
  19446. }
  19447. function QuadraticBezierP1(t, p) {
  19448. return 2 * (1 - t) * t * p;
  19449. }
  19450. function QuadraticBezierP2(t, p) {
  19451. return t * t * p;
  19452. }
  19453. function QuadraticBezier(t, p0, p1, p2) {
  19454. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  19455. }
  19456. //
  19457. function CubicBezierP0(t, p) {
  19458. const k = 1 - t;
  19459. return k * k * k * p;
  19460. }
  19461. function CubicBezierP1(t, p) {
  19462. const k = 1 - t;
  19463. return 3 * k * k * t * p;
  19464. }
  19465. function CubicBezierP2(t, p) {
  19466. return 3 * (1 - t) * t * t * p;
  19467. }
  19468. function CubicBezierP3(t, p) {
  19469. return t * t * t * p;
  19470. }
  19471. function CubicBezier(t, p0, p1, p2, p3) {
  19472. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  19473. }
  19474. class CubicBezierCurve extends Curve {
  19475. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  19476. super();
  19477. this.isCubicBezierCurve = true;
  19478. this.type = 'CubicBezierCurve';
  19479. this.v0 = v0;
  19480. this.v1 = v1;
  19481. this.v2 = v2;
  19482. this.v3 = v3;
  19483. }
  19484. getPoint(t, optionalTarget = new Vector2()) {
  19485. const point = optionalTarget;
  19486. const v0 = this.v0,
  19487. v1 = this.v1,
  19488. v2 = this.v2,
  19489. v3 = this.v3;
  19490. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  19491. return point;
  19492. }
  19493. copy(source) {
  19494. super.copy(source);
  19495. this.v0.copy(source.v0);
  19496. this.v1.copy(source.v1);
  19497. this.v2.copy(source.v2);
  19498. this.v3.copy(source.v3);
  19499. return this;
  19500. }
  19501. toJSON() {
  19502. const data = super.toJSON();
  19503. data.v0 = this.v0.toArray();
  19504. data.v1 = this.v1.toArray();
  19505. data.v2 = this.v2.toArray();
  19506. data.v3 = this.v3.toArray();
  19507. return data;
  19508. }
  19509. fromJSON(json) {
  19510. super.fromJSON(json);
  19511. this.v0.fromArray(json.v0);
  19512. this.v1.fromArray(json.v1);
  19513. this.v2.fromArray(json.v2);
  19514. this.v3.fromArray(json.v3);
  19515. return this;
  19516. }
  19517. }
  19518. class CubicBezierCurve3 extends Curve {
  19519. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  19520. super();
  19521. this.isCubicBezierCurve3 = true;
  19522. this.type = 'CubicBezierCurve3';
  19523. this.v0 = v0;
  19524. this.v1 = v1;
  19525. this.v2 = v2;
  19526. this.v3 = v3;
  19527. }
  19528. getPoint(t, optionalTarget = new Vector3()) {
  19529. const point = optionalTarget;
  19530. const v0 = this.v0,
  19531. v1 = this.v1,
  19532. v2 = this.v2,
  19533. v3 = this.v3;
  19534. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  19535. return point;
  19536. }
  19537. copy(source) {
  19538. super.copy(source);
  19539. this.v0.copy(source.v0);
  19540. this.v1.copy(source.v1);
  19541. this.v2.copy(source.v2);
  19542. this.v3.copy(source.v3);
  19543. return this;
  19544. }
  19545. toJSON() {
  19546. const data = super.toJSON();
  19547. data.v0 = this.v0.toArray();
  19548. data.v1 = this.v1.toArray();
  19549. data.v2 = this.v2.toArray();
  19550. data.v3 = this.v3.toArray();
  19551. return data;
  19552. }
  19553. fromJSON(json) {
  19554. super.fromJSON(json);
  19555. this.v0.fromArray(json.v0);
  19556. this.v1.fromArray(json.v1);
  19557. this.v2.fromArray(json.v2);
  19558. this.v3.fromArray(json.v3);
  19559. return this;
  19560. }
  19561. }
  19562. class LineCurve extends Curve {
  19563. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  19564. super();
  19565. this.isLineCurve = true;
  19566. this.type = 'LineCurve';
  19567. this.v1 = v1;
  19568. this.v2 = v2;
  19569. }
  19570. getPoint(t, optionalTarget = new Vector2()) {
  19571. const point = optionalTarget;
  19572. if (t === 1) {
  19573. point.copy(this.v2);
  19574. } else {
  19575. point.copy(this.v2).sub(this.v1);
  19576. point.multiplyScalar(t).add(this.v1);
  19577. }
  19578. return point;
  19579. }
  19580. // Line curve is linear, so we can overwrite default getPointAt
  19581. getPointAt(u, optionalTarget) {
  19582. return this.getPoint(u, optionalTarget);
  19583. }
  19584. getTangent(t, optionalTarget) {
  19585. const tangent = optionalTarget || new Vector2();
  19586. tangent.copy(this.v2).sub(this.v1).normalize();
  19587. return tangent;
  19588. }
  19589. copy(source) {
  19590. super.copy(source);
  19591. this.v1.copy(source.v1);
  19592. this.v2.copy(source.v2);
  19593. return this;
  19594. }
  19595. toJSON() {
  19596. const data = super.toJSON();
  19597. data.v1 = this.v1.toArray();
  19598. data.v2 = this.v2.toArray();
  19599. return data;
  19600. }
  19601. fromJSON(json) {
  19602. super.fromJSON(json);
  19603. this.v1.fromArray(json.v1);
  19604. this.v2.fromArray(json.v2);
  19605. return this;
  19606. }
  19607. }
  19608. class LineCurve3 extends Curve {
  19609. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  19610. super();
  19611. this.isLineCurve3 = true;
  19612. this.type = 'LineCurve3';
  19613. this.v1 = v1;
  19614. this.v2 = v2;
  19615. }
  19616. getPoint(t, optionalTarget = new Vector3()) {
  19617. const point = optionalTarget;
  19618. if (t === 1) {
  19619. point.copy(this.v2);
  19620. } else {
  19621. point.copy(this.v2).sub(this.v1);
  19622. point.multiplyScalar(t).add(this.v1);
  19623. }
  19624. return point;
  19625. }
  19626. // Line curve is linear, so we can overwrite default getPointAt
  19627. getPointAt(u, optionalTarget) {
  19628. return this.getPoint(u, optionalTarget);
  19629. }
  19630. copy(source) {
  19631. super.copy(source);
  19632. this.v1.copy(source.v1);
  19633. this.v2.copy(source.v2);
  19634. return this;
  19635. }
  19636. toJSON() {
  19637. const data = super.toJSON();
  19638. data.v1 = this.v1.toArray();
  19639. data.v2 = this.v2.toArray();
  19640. return data;
  19641. }
  19642. fromJSON(json) {
  19643. super.fromJSON(json);
  19644. this.v1.fromArray(json.v1);
  19645. this.v2.fromArray(json.v2);
  19646. return this;
  19647. }
  19648. }
  19649. class QuadraticBezierCurve extends Curve {
  19650. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19651. super();
  19652. this.isQuadraticBezierCurve = true;
  19653. this.type = 'QuadraticBezierCurve';
  19654. this.v0 = v0;
  19655. this.v1 = v1;
  19656. this.v2 = v2;
  19657. }
  19658. getPoint(t, optionalTarget = new Vector2()) {
  19659. const point = optionalTarget;
  19660. const v0 = this.v0,
  19661. v1 = this.v1,
  19662. v2 = this.v2;
  19663. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19664. return point;
  19665. }
  19666. copy(source) {
  19667. super.copy(source);
  19668. this.v0.copy(source.v0);
  19669. this.v1.copy(source.v1);
  19670. this.v2.copy(source.v2);
  19671. return this;
  19672. }
  19673. toJSON() {
  19674. const data = super.toJSON();
  19675. data.v0 = this.v0.toArray();
  19676. data.v1 = this.v1.toArray();
  19677. data.v2 = this.v2.toArray();
  19678. return data;
  19679. }
  19680. fromJSON(json) {
  19681. super.fromJSON(json);
  19682. this.v0.fromArray(json.v0);
  19683. this.v1.fromArray(json.v1);
  19684. this.v2.fromArray(json.v2);
  19685. return this;
  19686. }
  19687. }
  19688. class QuadraticBezierCurve3 extends Curve {
  19689. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19690. super();
  19691. this.isQuadraticBezierCurve3 = true;
  19692. this.type = 'QuadraticBezierCurve3';
  19693. this.v0 = v0;
  19694. this.v1 = v1;
  19695. this.v2 = v2;
  19696. }
  19697. getPoint(t, optionalTarget = new Vector3()) {
  19698. const point = optionalTarget;
  19699. const v0 = this.v0,
  19700. v1 = this.v1,
  19701. v2 = this.v2;
  19702. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  19703. return point;
  19704. }
  19705. copy(source) {
  19706. super.copy(source);
  19707. this.v0.copy(source.v0);
  19708. this.v1.copy(source.v1);
  19709. this.v2.copy(source.v2);
  19710. return this;
  19711. }
  19712. toJSON() {
  19713. const data = super.toJSON();
  19714. data.v0 = this.v0.toArray();
  19715. data.v1 = this.v1.toArray();
  19716. data.v2 = this.v2.toArray();
  19717. return data;
  19718. }
  19719. fromJSON(json) {
  19720. super.fromJSON(json);
  19721. this.v0.fromArray(json.v0);
  19722. this.v1.fromArray(json.v1);
  19723. this.v2.fromArray(json.v2);
  19724. return this;
  19725. }
  19726. }
  19727. class SplineCurve extends Curve {
  19728. constructor(points = []) {
  19729. super();
  19730. this.isSplineCurve = true;
  19731. this.type = 'SplineCurve';
  19732. this.points = points;
  19733. }
  19734. getPoint(t, optionalTarget = new Vector2()) {
  19735. const point = optionalTarget;
  19736. const points = this.points;
  19737. const p = (points.length - 1) * t;
  19738. const intPoint = Math.floor(p);
  19739. const weight = p - intPoint;
  19740. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19741. const p1 = points[intPoint];
  19742. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19743. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19744. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19745. return point;
  19746. }
  19747. copy(source) {
  19748. super.copy(source);
  19749. this.points = [];
  19750. for (let i = 0, l = source.points.length; i < l; i++) {
  19751. const point = source.points[i];
  19752. this.points.push(point.clone());
  19753. }
  19754. return this;
  19755. }
  19756. toJSON() {
  19757. const data = super.toJSON();
  19758. data.points = [];
  19759. for (let i = 0, l = this.points.length; i < l; i++) {
  19760. const point = this.points[i];
  19761. data.points.push(point.toArray());
  19762. }
  19763. return data;
  19764. }
  19765. fromJSON(json) {
  19766. super.fromJSON(json);
  19767. this.points = [];
  19768. for (let i = 0, l = json.points.length; i < l; i++) {
  19769. const point = json.points[i];
  19770. this.points.push(new Vector2().fromArray(point));
  19771. }
  19772. return this;
  19773. }
  19774. }
  19775. var Curves = /*#__PURE__*/Object.freeze({
  19776. __proto__: null,
  19777. ArcCurve: ArcCurve,
  19778. CatmullRomCurve3: CatmullRomCurve3,
  19779. CubicBezierCurve: CubicBezierCurve,
  19780. CubicBezierCurve3: CubicBezierCurve3,
  19781. EllipseCurve: EllipseCurve,
  19782. LineCurve: LineCurve,
  19783. LineCurve3: LineCurve3,
  19784. QuadraticBezierCurve: QuadraticBezierCurve,
  19785. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19786. SplineCurve: SplineCurve
  19787. });
  19788. /**************************************************************
  19789. * Curved Path - a curve path is simply a array of connected
  19790. * curves, but retains the api of a curve
  19791. **************************************************************/
  19792. class CurvePath extends Curve {
  19793. constructor() {
  19794. super();
  19795. this.type = 'CurvePath';
  19796. this.curves = [];
  19797. this.autoClose = false; // Automatically closes the path
  19798. }
  19799. add(curve) {
  19800. this.curves.push(curve);
  19801. }
  19802. closePath() {
  19803. // Add a line curve if start and end of lines are not connected
  19804. const startPoint = this.curves[0].getPoint(0);
  19805. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19806. if (!startPoint.equals(endPoint)) {
  19807. this.curves.push(new LineCurve(endPoint, startPoint));
  19808. }
  19809. }
  19810. // To get accurate point with reference to
  19811. // entire path distance at time t,
  19812. // following has to be done:
  19813. // 1. Length of each sub path have to be known
  19814. // 2. Locate and identify type of curve
  19815. // 3. Get t for the curve
  19816. // 4. Return curve.getPointAt(t')
  19817. getPoint(t, optionalTarget) {
  19818. const d = t * this.getLength();
  19819. const curveLengths = this.getCurveLengths();
  19820. let i = 0;
  19821. // To think about boundaries points.
  19822. while (i < curveLengths.length) {
  19823. if (curveLengths[i] >= d) {
  19824. const diff = curveLengths[i] - d;
  19825. const curve = this.curves[i];
  19826. const segmentLength = curve.getLength();
  19827. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19828. return curve.getPointAt(u, optionalTarget);
  19829. }
  19830. i++;
  19831. }
  19832. return null;
  19833. // loop where sum != 0, sum > d , sum+1 <d
  19834. }
  19835. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19836. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19837. // getPoint() depends on getLength
  19838. getLength() {
  19839. const lens = this.getCurveLengths();
  19840. return lens[lens.length - 1];
  19841. }
  19842. // cacheLengths must be recalculated.
  19843. updateArcLengths() {
  19844. this.needsUpdate = true;
  19845. this.cacheLengths = null;
  19846. this.getCurveLengths();
  19847. }
  19848. // Compute lengths and cache them
  19849. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19850. getCurveLengths() {
  19851. // We use cache values if curves and cache array are same length
  19852. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19853. return this.cacheLengths;
  19854. }
  19855. // Get length of sub-curve
  19856. // Push sums into cached array
  19857. const lengths = [];
  19858. let sums = 0;
  19859. for (let i = 0, l = this.curves.length; i < l; i++) {
  19860. sums += this.curves[i].getLength();
  19861. lengths.push(sums);
  19862. }
  19863. this.cacheLengths = lengths;
  19864. return lengths;
  19865. }
  19866. getSpacedPoints(divisions = 40) {
  19867. const points = [];
  19868. for (let i = 0; i <= divisions; i++) {
  19869. points.push(this.getPoint(i / divisions));
  19870. }
  19871. if (this.autoClose) {
  19872. points.push(points[0]);
  19873. }
  19874. return points;
  19875. }
  19876. getPoints(divisions = 12) {
  19877. const points = [];
  19878. let last;
  19879. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19880. const curve = curves[i];
  19881. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19882. const pts = curve.getPoints(resolution);
  19883. for (let j = 0; j < pts.length; j++) {
  19884. const point = pts[j];
  19885. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19886. points.push(point);
  19887. last = point;
  19888. }
  19889. }
  19890. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19891. points.push(points[0]);
  19892. }
  19893. return points;
  19894. }
  19895. copy(source) {
  19896. super.copy(source);
  19897. this.curves = [];
  19898. for (let i = 0, l = source.curves.length; i < l; i++) {
  19899. const curve = source.curves[i];
  19900. this.curves.push(curve.clone());
  19901. }
  19902. this.autoClose = source.autoClose;
  19903. return this;
  19904. }
  19905. toJSON() {
  19906. const data = super.toJSON();
  19907. data.autoClose = this.autoClose;
  19908. data.curves = [];
  19909. for (let i = 0, l = this.curves.length; i < l; i++) {
  19910. const curve = this.curves[i];
  19911. data.curves.push(curve.toJSON());
  19912. }
  19913. return data;
  19914. }
  19915. fromJSON(json) {
  19916. super.fromJSON(json);
  19917. this.autoClose = json.autoClose;
  19918. this.curves = [];
  19919. for (let i = 0, l = json.curves.length; i < l; i++) {
  19920. const curve = json.curves[i];
  19921. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19922. }
  19923. return this;
  19924. }
  19925. }
  19926. class Path extends CurvePath {
  19927. constructor(points) {
  19928. super();
  19929. this.type = 'Path';
  19930. this.currentPoint = new Vector2();
  19931. if (points) {
  19932. this.setFromPoints(points);
  19933. }
  19934. }
  19935. setFromPoints(points) {
  19936. this.moveTo(points[0].x, points[0].y);
  19937. for (let i = 1, l = points.length; i < l; i++) {
  19938. this.lineTo(points[i].x, points[i].y);
  19939. }
  19940. return this;
  19941. }
  19942. moveTo(x, y) {
  19943. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19944. return this;
  19945. }
  19946. lineTo(x, y) {
  19947. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19948. this.curves.push(curve);
  19949. this.currentPoint.set(x, y);
  19950. return this;
  19951. }
  19952. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19953. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19954. this.curves.push(curve);
  19955. this.currentPoint.set(aX, aY);
  19956. return this;
  19957. }
  19958. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19959. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19960. this.curves.push(curve);
  19961. this.currentPoint.set(aX, aY);
  19962. return this;
  19963. }
  19964. splineThru(pts /*Array of Vector*/) {
  19965. const npts = [this.currentPoint.clone()].concat(pts);
  19966. const curve = new SplineCurve(npts);
  19967. this.curves.push(curve);
  19968. this.currentPoint.copy(pts[pts.length - 1]);
  19969. return this;
  19970. }
  19971. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19972. const x0 = this.currentPoint.x;
  19973. const y0 = this.currentPoint.y;
  19974. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19975. return this;
  19976. }
  19977. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19978. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19979. return this;
  19980. }
  19981. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19982. const x0 = this.currentPoint.x;
  19983. const y0 = this.currentPoint.y;
  19984. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19985. return this;
  19986. }
  19987. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19988. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19989. if (this.curves.length > 0) {
  19990. // if a previous curve is present, attempt to join
  19991. const firstPoint = curve.getPoint(0);
  19992. if (!firstPoint.equals(this.currentPoint)) {
  19993. this.lineTo(firstPoint.x, firstPoint.y);
  19994. }
  19995. }
  19996. this.curves.push(curve);
  19997. const lastPoint = curve.getPoint(1);
  19998. this.currentPoint.copy(lastPoint);
  19999. return this;
  20000. }
  20001. copy(source) {
  20002. super.copy(source);
  20003. this.currentPoint.copy(source.currentPoint);
  20004. return this;
  20005. }
  20006. toJSON() {
  20007. const data = super.toJSON();
  20008. data.currentPoint = this.currentPoint.toArray();
  20009. return data;
  20010. }
  20011. fromJSON(json) {
  20012. super.fromJSON(json);
  20013. this.currentPoint.fromArray(json.currentPoint);
  20014. return this;
  20015. }
  20016. }
  20017. class LatheGeometry extends BufferGeometry {
  20018. 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) {
  20019. super();
  20020. this.type = 'LatheGeometry';
  20021. this.parameters = {
  20022. points: points,
  20023. segments: segments,
  20024. phiStart: phiStart,
  20025. phiLength: phiLength
  20026. };
  20027. segments = Math.floor(segments);
  20028. // clamp phiLength so it's in range of [ 0, 2PI ]
  20029. phiLength = clamp(phiLength, 0, Math.PI * 2);
  20030. // buffers
  20031. const indices = [];
  20032. const vertices = [];
  20033. const uvs = [];
  20034. const initNormals = [];
  20035. const normals = [];
  20036. // helper variables
  20037. const inverseSegments = 1.0 / segments;
  20038. const vertex = new Vector3();
  20039. const uv = new Vector2();
  20040. const normal = new Vector3();
  20041. const curNormal = new Vector3();
  20042. const prevNormal = new Vector3();
  20043. let dx = 0;
  20044. let dy = 0;
  20045. // pre-compute normals for initial "meridian"
  20046. for (let j = 0; j <= points.length - 1; j++) {
  20047. switch (j) {
  20048. case 0:
  20049. // special handling for 1st vertex on path
  20050. dx = points[j + 1].x - points[j].x;
  20051. dy = points[j + 1].y - points[j].y;
  20052. normal.x = dy * 1.0;
  20053. normal.y = -dx;
  20054. normal.z = dy * 0.0;
  20055. prevNormal.copy(normal);
  20056. normal.normalize();
  20057. initNormals.push(normal.x, normal.y, normal.z);
  20058. break;
  20059. case points.length - 1:
  20060. // special handling for last Vertex on path
  20061. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  20062. break;
  20063. default:
  20064. // default handling for all vertices in between
  20065. dx = points[j + 1].x - points[j].x;
  20066. dy = points[j + 1].y - points[j].y;
  20067. normal.x = dy * 1.0;
  20068. normal.y = -dx;
  20069. normal.z = dy * 0.0;
  20070. curNormal.copy(normal);
  20071. normal.x += prevNormal.x;
  20072. normal.y += prevNormal.y;
  20073. normal.z += prevNormal.z;
  20074. normal.normalize();
  20075. initNormals.push(normal.x, normal.y, normal.z);
  20076. prevNormal.copy(curNormal);
  20077. }
  20078. }
  20079. // generate vertices, uvs and normals
  20080. for (let i = 0; i <= segments; i++) {
  20081. const phi = phiStart + i * inverseSegments * phiLength;
  20082. const sin = Math.sin(phi);
  20083. const cos = Math.cos(phi);
  20084. for (let j = 0; j <= points.length - 1; j++) {
  20085. // vertex
  20086. vertex.x = points[j].x * sin;
  20087. vertex.y = points[j].y;
  20088. vertex.z = points[j].x * cos;
  20089. vertices.push(vertex.x, vertex.y, vertex.z);
  20090. // uv
  20091. uv.x = i / segments;
  20092. uv.y = j / (points.length - 1);
  20093. uvs.push(uv.x, uv.y);
  20094. // normal
  20095. const x = initNormals[3 * j + 0] * sin;
  20096. const y = initNormals[3 * j + 1];
  20097. const z = initNormals[3 * j + 0] * cos;
  20098. normals.push(x, y, z);
  20099. }
  20100. }
  20101. // indices
  20102. for (let i = 0; i < segments; i++) {
  20103. for (let j = 0; j < points.length - 1; j++) {
  20104. const base = j + i * points.length;
  20105. const a = base;
  20106. const b = base + points.length;
  20107. const c = base + points.length + 1;
  20108. const d = base + 1;
  20109. // faces
  20110. indices.push(a, b, d);
  20111. indices.push(c, d, b);
  20112. }
  20113. }
  20114. // build geometry
  20115. this.setIndex(indices);
  20116. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20117. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20118. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20119. }
  20120. static fromJSON(data) {
  20121. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  20122. }
  20123. }
  20124. class CapsuleGeometry extends LatheGeometry {
  20125. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  20126. const path = new Path();
  20127. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  20128. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  20129. super(path.getPoints(capSegments), radialSegments);
  20130. this.type = 'CapsuleGeometry';
  20131. this.parameters = {
  20132. radius: radius,
  20133. height: length,
  20134. capSegments: capSegments,
  20135. radialSegments: radialSegments
  20136. };
  20137. }
  20138. static fromJSON(data) {
  20139. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  20140. }
  20141. }
  20142. class CircleGeometry extends BufferGeometry {
  20143. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  20144. super();
  20145. this.type = 'CircleGeometry';
  20146. this.parameters = {
  20147. radius: radius,
  20148. segments: segments,
  20149. thetaStart: thetaStart,
  20150. thetaLength: thetaLength
  20151. };
  20152. segments = Math.max(3, segments);
  20153. // buffers
  20154. const indices = [];
  20155. const vertices = [];
  20156. const normals = [];
  20157. const uvs = [];
  20158. // helper variables
  20159. const vertex = new Vector3();
  20160. const uv = new Vector2();
  20161. // center point
  20162. vertices.push(0, 0, 0);
  20163. normals.push(0, 0, 1);
  20164. uvs.push(0.5, 0.5);
  20165. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  20166. const segment = thetaStart + s / segments * thetaLength;
  20167. // vertex
  20168. vertex.x = radius * Math.cos(segment);
  20169. vertex.y = radius * Math.sin(segment);
  20170. vertices.push(vertex.x, vertex.y, vertex.z);
  20171. // normal
  20172. normals.push(0, 0, 1);
  20173. // uvs
  20174. uv.x = (vertices[i] / radius + 1) / 2;
  20175. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20176. uvs.push(uv.x, uv.y);
  20177. }
  20178. // indices
  20179. for (let i = 1; i <= segments; i++) {
  20180. indices.push(i, i + 1, 0);
  20181. }
  20182. // build geometry
  20183. this.setIndex(indices);
  20184. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20185. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20186. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20187. }
  20188. static fromJSON(data) {
  20189. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  20190. }
  20191. }
  20192. class CylinderGeometry extends BufferGeometry {
  20193. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  20194. super();
  20195. this.type = 'CylinderGeometry';
  20196. this.parameters = {
  20197. radiusTop: radiusTop,
  20198. radiusBottom: radiusBottom,
  20199. height: height,
  20200. radialSegments: radialSegments,
  20201. heightSegments: heightSegments,
  20202. openEnded: openEnded,
  20203. thetaStart: thetaStart,
  20204. thetaLength: thetaLength
  20205. };
  20206. const scope = this;
  20207. radialSegments = Math.floor(radialSegments);
  20208. heightSegments = Math.floor(heightSegments);
  20209. // buffers
  20210. const indices = [];
  20211. const vertices = [];
  20212. const normals = [];
  20213. const uvs = [];
  20214. // helper variables
  20215. let index = 0;
  20216. const indexArray = [];
  20217. const halfHeight = height / 2;
  20218. let groupStart = 0;
  20219. // generate geometry
  20220. generateTorso();
  20221. if (openEnded === false) {
  20222. if (radiusTop > 0) generateCap(true);
  20223. if (radiusBottom > 0) generateCap(false);
  20224. }
  20225. // build geometry
  20226. this.setIndex(indices);
  20227. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20228. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20229. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20230. function generateTorso() {
  20231. const normal = new Vector3();
  20232. const vertex = new Vector3();
  20233. let groupCount = 0;
  20234. // this will be used to calculate the normal
  20235. const slope = (radiusBottom - radiusTop) / height;
  20236. // generate vertices, normals and uvs
  20237. for (let y = 0; y <= heightSegments; y++) {
  20238. const indexRow = [];
  20239. const v = y / heightSegments;
  20240. // calculate the radius of the current row
  20241. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  20242. for (let x = 0; x <= radialSegments; x++) {
  20243. const u = x / radialSegments;
  20244. const theta = u * thetaLength + thetaStart;
  20245. const sinTheta = Math.sin(theta);
  20246. const cosTheta = Math.cos(theta);
  20247. // vertex
  20248. vertex.x = radius * sinTheta;
  20249. vertex.y = -v * height + halfHeight;
  20250. vertex.z = radius * cosTheta;
  20251. vertices.push(vertex.x, vertex.y, vertex.z);
  20252. // normal
  20253. normal.set(sinTheta, slope, cosTheta).normalize();
  20254. normals.push(normal.x, normal.y, normal.z);
  20255. // uv
  20256. uvs.push(u, 1 - v);
  20257. // save index of vertex in respective row
  20258. indexRow.push(index++);
  20259. }
  20260. // now save vertices of the row in our index array
  20261. indexArray.push(indexRow);
  20262. }
  20263. // generate indices
  20264. for (let x = 0; x < radialSegments; x++) {
  20265. for (let y = 0; y < heightSegments; y++) {
  20266. // we use the index array to access the correct indices
  20267. const a = indexArray[y][x];
  20268. const b = indexArray[y + 1][x];
  20269. const c = indexArray[y + 1][x + 1];
  20270. const d = indexArray[y][x + 1];
  20271. // faces
  20272. indices.push(a, b, d);
  20273. indices.push(b, c, d);
  20274. // update group counter
  20275. groupCount += 6;
  20276. }
  20277. }
  20278. // add a group to the geometry. this will ensure multi material support
  20279. scope.addGroup(groupStart, groupCount, 0);
  20280. // calculate new start value for groups
  20281. groupStart += groupCount;
  20282. }
  20283. function generateCap(top) {
  20284. // save the index of the first center vertex
  20285. const centerIndexStart = index;
  20286. const uv = new Vector2();
  20287. const vertex = new Vector3();
  20288. let groupCount = 0;
  20289. const radius = top === true ? radiusTop : radiusBottom;
  20290. const sign = top === true ? 1 : -1;
  20291. // first we generate the center vertex data of the cap.
  20292. // because the geometry needs one set of uvs per face,
  20293. // we must generate a center vertex per face/segment
  20294. for (let x = 1; x <= radialSegments; x++) {
  20295. // vertex
  20296. vertices.push(0, halfHeight * sign, 0);
  20297. // normal
  20298. normals.push(0, sign, 0);
  20299. // uv
  20300. uvs.push(0.5, 0.5);
  20301. // increase index
  20302. index++;
  20303. }
  20304. // save the index of the last center vertex
  20305. const centerIndexEnd = index;
  20306. // now we generate the surrounding vertices, normals and uvs
  20307. for (let x = 0; x <= radialSegments; x++) {
  20308. const u = x / radialSegments;
  20309. const theta = u * thetaLength + thetaStart;
  20310. const cosTheta = Math.cos(theta);
  20311. const sinTheta = Math.sin(theta);
  20312. // vertex
  20313. vertex.x = radius * sinTheta;
  20314. vertex.y = halfHeight * sign;
  20315. vertex.z = radius * cosTheta;
  20316. vertices.push(vertex.x, vertex.y, vertex.z);
  20317. // normal
  20318. normals.push(0, sign, 0);
  20319. // uv
  20320. uv.x = cosTheta * 0.5 + 0.5;
  20321. uv.y = sinTheta * 0.5 * sign + 0.5;
  20322. uvs.push(uv.x, uv.y);
  20323. // increase index
  20324. index++;
  20325. }
  20326. // generate indices
  20327. for (let x = 0; x < radialSegments; x++) {
  20328. const c = centerIndexStart + x;
  20329. const i = centerIndexEnd + x;
  20330. if (top === true) {
  20331. // face top
  20332. indices.push(i, i + 1, c);
  20333. } else {
  20334. // face bottom
  20335. indices.push(i + 1, i, c);
  20336. }
  20337. groupCount += 3;
  20338. }
  20339. // add a group to the geometry. this will ensure multi material support
  20340. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2);
  20341. // calculate new start value for groups
  20342. groupStart += groupCount;
  20343. }
  20344. }
  20345. static fromJSON(data) {
  20346. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  20347. }
  20348. }
  20349. class ConeGeometry extends CylinderGeometry {
  20350. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  20351. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20352. this.type = 'ConeGeometry';
  20353. this.parameters = {
  20354. radius: radius,
  20355. height: height,
  20356. radialSegments: radialSegments,
  20357. heightSegments: heightSegments,
  20358. openEnded: openEnded,
  20359. thetaStart: thetaStart,
  20360. thetaLength: thetaLength
  20361. };
  20362. }
  20363. static fromJSON(data) {
  20364. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  20365. }
  20366. }
  20367. class PolyhedronGeometry extends BufferGeometry {
  20368. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  20369. super();
  20370. this.type = 'PolyhedronGeometry';
  20371. this.parameters = {
  20372. vertices: vertices,
  20373. indices: indices,
  20374. radius: radius,
  20375. detail: detail
  20376. };
  20377. // default buffer data
  20378. const vertexBuffer = [];
  20379. const uvBuffer = [];
  20380. // the subdivision creates the vertex buffer data
  20381. subdivide(detail);
  20382. // all vertices should lie on a conceptual sphere with a given radius
  20383. applyRadius(radius);
  20384. // finally, create the uv data
  20385. generateUVs();
  20386. // build non-indexed geometry
  20387. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  20388. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  20389. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  20390. if (detail === 0) {
  20391. this.computeVertexNormals(); // flat normals
  20392. } else {
  20393. this.normalizeNormals(); // smooth normals
  20394. }
  20395. // helper functions
  20396. function subdivide(detail) {
  20397. const a = new Vector3();
  20398. const b = new Vector3();
  20399. const c = new Vector3();
  20400. // iterate over all faces and apply a subdivision with the given detail value
  20401. for (let i = 0; i < indices.length; i += 3) {
  20402. // get the vertices of the face
  20403. getVertexByIndex(indices[i + 0], a);
  20404. getVertexByIndex(indices[i + 1], b);
  20405. getVertexByIndex(indices[i + 2], c);
  20406. // perform subdivision
  20407. subdivideFace(a, b, c, detail);
  20408. }
  20409. }
  20410. function subdivideFace(a, b, c, detail) {
  20411. const cols = detail + 1;
  20412. // we use this multidimensional array as a data structure for creating the subdivision
  20413. const v = [];
  20414. // construct all of the vertices for this subdivision
  20415. for (let i = 0; i <= cols; i++) {
  20416. v[i] = [];
  20417. const aj = a.clone().lerp(c, i / cols);
  20418. const bj = b.clone().lerp(c, i / cols);
  20419. const rows = cols - i;
  20420. for (let j = 0; j <= rows; j++) {
  20421. if (j === 0 && i === cols) {
  20422. v[i][j] = aj;
  20423. } else {
  20424. v[i][j] = aj.clone().lerp(bj, j / rows);
  20425. }
  20426. }
  20427. }
  20428. // construct all of the faces
  20429. for (let i = 0; i < cols; i++) {
  20430. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  20431. const k = Math.floor(j / 2);
  20432. if (j % 2 === 0) {
  20433. pushVertex(v[i][k + 1]);
  20434. pushVertex(v[i + 1][k]);
  20435. pushVertex(v[i][k]);
  20436. } else {
  20437. pushVertex(v[i][k + 1]);
  20438. pushVertex(v[i + 1][k + 1]);
  20439. pushVertex(v[i + 1][k]);
  20440. }
  20441. }
  20442. }
  20443. }
  20444. function applyRadius(radius) {
  20445. const vertex = new Vector3();
  20446. // iterate over the entire buffer and apply the radius to each vertex
  20447. for (let i = 0; i < vertexBuffer.length; i += 3) {
  20448. vertex.x = vertexBuffer[i + 0];
  20449. vertex.y = vertexBuffer[i + 1];
  20450. vertex.z = vertexBuffer[i + 2];
  20451. vertex.normalize().multiplyScalar(radius);
  20452. vertexBuffer[i + 0] = vertex.x;
  20453. vertexBuffer[i + 1] = vertex.y;
  20454. vertexBuffer[i + 2] = vertex.z;
  20455. }
  20456. }
  20457. function generateUVs() {
  20458. const vertex = new Vector3();
  20459. for (let i = 0; i < vertexBuffer.length; i += 3) {
  20460. vertex.x = vertexBuffer[i + 0];
  20461. vertex.y = vertexBuffer[i + 1];
  20462. vertex.z = vertexBuffer[i + 2];
  20463. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  20464. const v = inclination(vertex) / Math.PI + 0.5;
  20465. uvBuffer.push(u, 1 - v);
  20466. }
  20467. correctUVs();
  20468. correctSeam();
  20469. }
  20470. function correctSeam() {
  20471. // handle case when face straddles the seam, see #3269
  20472. for (let i = 0; i < uvBuffer.length; i += 6) {
  20473. // uv data of a single face
  20474. const x0 = uvBuffer[i + 0];
  20475. const x1 = uvBuffer[i + 2];
  20476. const x2 = uvBuffer[i + 4];
  20477. const max = Math.max(x0, x1, x2);
  20478. const min = Math.min(x0, x1, x2);
  20479. // 0.9 is somewhat arbitrary
  20480. if (max > 0.9 && min < 0.1) {
  20481. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  20482. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  20483. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  20484. }
  20485. }
  20486. }
  20487. function pushVertex(vertex) {
  20488. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  20489. }
  20490. function getVertexByIndex(index, vertex) {
  20491. const stride = index * 3;
  20492. vertex.x = vertices[stride + 0];
  20493. vertex.y = vertices[stride + 1];
  20494. vertex.z = vertices[stride + 2];
  20495. }
  20496. function correctUVs() {
  20497. const a = new Vector3();
  20498. const b = new Vector3();
  20499. const c = new Vector3();
  20500. const centroid = new Vector3();
  20501. const uvA = new Vector2();
  20502. const uvB = new Vector2();
  20503. const uvC = new Vector2();
  20504. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  20505. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  20506. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  20507. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  20508. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  20509. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  20510. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  20511. centroid.copy(a).add(b).add(c).divideScalar(3);
  20512. const azi = azimuth(centroid);
  20513. correctUV(uvA, j + 0, a, azi);
  20514. correctUV(uvB, j + 2, b, azi);
  20515. correctUV(uvC, j + 4, c, azi);
  20516. }
  20517. }
  20518. function correctUV(uv, stride, vector, azimuth) {
  20519. if (azimuth < 0 && uv.x === 1) {
  20520. uvBuffer[stride] = uv.x - 1;
  20521. }
  20522. if (vector.x === 0 && vector.z === 0) {
  20523. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  20524. }
  20525. }
  20526. // Angle around the Y axis, counter-clockwise when looking from above.
  20527. function azimuth(vector) {
  20528. return Math.atan2(vector.z, -vector.x);
  20529. }
  20530. // Angle above the XZ plane.
  20531. function inclination(vector) {
  20532. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  20533. }
  20534. }
  20535. static fromJSON(data) {
  20536. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  20537. }
  20538. }
  20539. class DodecahedronGeometry extends PolyhedronGeometry {
  20540. constructor(radius = 1, detail = 0) {
  20541. const t = (1 + Math.sqrt(5)) / 2;
  20542. const r = 1 / t;
  20543. const vertices = [
  20544. // (±1, ±1, ±1)
  20545. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1,
  20546. // (0, ±1/φ, ±φ)
  20547. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t,
  20548. // (±1/φ, ±φ, 0)
  20549. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0,
  20550. // (±φ, 0, ±1/φ)
  20551. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  20552. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  20553. super(vertices, indices, radius, detail);
  20554. this.type = 'DodecahedronGeometry';
  20555. this.parameters = {
  20556. radius: radius,
  20557. detail: detail
  20558. };
  20559. }
  20560. static fromJSON(data) {
  20561. return new DodecahedronGeometry(data.radius, data.detail);
  20562. }
  20563. }
  20564. const _v0 = /*@__PURE__*/new Vector3();
  20565. const _v1$1 = /*@__PURE__*/new Vector3();
  20566. const _normal = /*@__PURE__*/new Vector3();
  20567. const _triangle = /*@__PURE__*/new Triangle();
  20568. class EdgesGeometry extends BufferGeometry {
  20569. constructor(geometry = null, thresholdAngle = 1) {
  20570. super();
  20571. this.type = 'EdgesGeometry';
  20572. this.parameters = {
  20573. geometry: geometry,
  20574. thresholdAngle: thresholdAngle
  20575. };
  20576. if (geometry !== null) {
  20577. const precisionPoints = 4;
  20578. const precision = Math.pow(10, precisionPoints);
  20579. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  20580. const indexAttr = geometry.getIndex();
  20581. const positionAttr = geometry.getAttribute('position');
  20582. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20583. const indexArr = [0, 0, 0];
  20584. const vertKeys = ['a', 'b', 'c'];
  20585. const hashes = new Array(3);
  20586. const edgeData = {};
  20587. const vertices = [];
  20588. for (let i = 0; i < indexCount; i += 3) {
  20589. if (indexAttr) {
  20590. indexArr[0] = indexAttr.getX(i);
  20591. indexArr[1] = indexAttr.getX(i + 1);
  20592. indexArr[2] = indexAttr.getX(i + 2);
  20593. } else {
  20594. indexArr[0] = i;
  20595. indexArr[1] = i + 1;
  20596. indexArr[2] = i + 2;
  20597. }
  20598. const {
  20599. a,
  20600. b,
  20601. c
  20602. } = _triangle;
  20603. a.fromBufferAttribute(positionAttr, indexArr[0]);
  20604. b.fromBufferAttribute(positionAttr, indexArr[1]);
  20605. c.fromBufferAttribute(positionAttr, indexArr[2]);
  20606. _triangle.getNormal(_normal);
  20607. // create hashes for the edge from the vertices
  20608. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  20609. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  20610. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`;
  20611. // skip degenerate triangles
  20612. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  20613. continue;
  20614. }
  20615. // iterate over every edge
  20616. for (let j = 0; j < 3; j++) {
  20617. // get the first and next vertex making up the edge
  20618. const jNext = (j + 1) % 3;
  20619. const vecHash0 = hashes[j];
  20620. const vecHash1 = hashes[jNext];
  20621. const v0 = _triangle[vertKeys[j]];
  20622. const v1 = _triangle[vertKeys[jNext]];
  20623. const hash = `${vecHash0}_${vecHash1}`;
  20624. const reverseHash = `${vecHash1}_${vecHash0}`;
  20625. if (reverseHash in edgeData && edgeData[reverseHash]) {
  20626. // if we found a sibling edge add it into the vertex array if
  20627. // it meets the angle threshold and delete the edge from the map.
  20628. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  20629. vertices.push(v0.x, v0.y, v0.z);
  20630. vertices.push(v1.x, v1.y, v1.z);
  20631. }
  20632. edgeData[reverseHash] = null;
  20633. } else if (!(hash in edgeData)) {
  20634. // if we've already got an edge here then skip adding a new one
  20635. edgeData[hash] = {
  20636. index0: indexArr[j],
  20637. index1: indexArr[jNext],
  20638. normal: _normal.clone()
  20639. };
  20640. }
  20641. }
  20642. }
  20643. // iterate over all remaining, unmatched edges and add them to the vertex array
  20644. for (const key in edgeData) {
  20645. if (edgeData[key]) {
  20646. const {
  20647. index0,
  20648. index1
  20649. } = edgeData[key];
  20650. _v0.fromBufferAttribute(positionAttr, index0);
  20651. _v1$1.fromBufferAttribute(positionAttr, index1);
  20652. vertices.push(_v0.x, _v0.y, _v0.z);
  20653. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  20654. }
  20655. }
  20656. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20657. }
  20658. }
  20659. }
  20660. class Shape extends Path {
  20661. constructor(points) {
  20662. super(points);
  20663. this.uuid = generateUUID();
  20664. this.type = 'Shape';
  20665. this.holes = [];
  20666. }
  20667. getPointsHoles(divisions) {
  20668. const holesPts = [];
  20669. for (let i = 0, l = this.holes.length; i < l; i++) {
  20670. holesPts[i] = this.holes[i].getPoints(divisions);
  20671. }
  20672. return holesPts;
  20673. }
  20674. // get points of shape and holes (keypoints based on segments parameter)
  20675. extractPoints(divisions) {
  20676. return {
  20677. shape: this.getPoints(divisions),
  20678. holes: this.getPointsHoles(divisions)
  20679. };
  20680. }
  20681. copy(source) {
  20682. super.copy(source);
  20683. this.holes = [];
  20684. for (let i = 0, l = source.holes.length; i < l; i++) {
  20685. const hole = source.holes[i];
  20686. this.holes.push(hole.clone());
  20687. }
  20688. return this;
  20689. }
  20690. toJSON() {
  20691. const data = super.toJSON();
  20692. data.uuid = this.uuid;
  20693. data.holes = [];
  20694. for (let i = 0, l = this.holes.length; i < l; i++) {
  20695. const hole = this.holes[i];
  20696. data.holes.push(hole.toJSON());
  20697. }
  20698. return data;
  20699. }
  20700. fromJSON(json) {
  20701. super.fromJSON(json);
  20702. this.uuid = json.uuid;
  20703. this.holes = [];
  20704. for (let i = 0, l = json.holes.length; i < l; i++) {
  20705. const hole = json.holes[i];
  20706. this.holes.push(new Path().fromJSON(hole));
  20707. }
  20708. return this;
  20709. }
  20710. }
  20711. /**
  20712. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20713. */
  20714. const Earcut = {
  20715. triangulate: function (data, holeIndices, dim = 2) {
  20716. const hasHoles = holeIndices && holeIndices.length;
  20717. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  20718. let outerNode = linkedList(data, 0, outerLen, dim, true);
  20719. const triangles = [];
  20720. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  20721. let minX, minY, maxX, maxY, x, y, invSize;
  20722. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  20723. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20724. if (data.length > 80 * dim) {
  20725. minX = maxX = data[0];
  20726. minY = maxY = data[1];
  20727. for (let i = dim; i < outerLen; i += dim) {
  20728. x = data[i];
  20729. y = data[i + 1];
  20730. if (x < minX) minX = x;
  20731. if (y < minY) minY = y;
  20732. if (x > maxX) maxX = x;
  20733. if (y > maxY) maxY = y;
  20734. }
  20735. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20736. invSize = Math.max(maxX - minX, maxY - minY);
  20737. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20738. }
  20739. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  20740. return triangles;
  20741. }
  20742. };
  20743. // create a circular doubly linked list from polygon points in the specified winding order
  20744. function linkedList(data, start, end, dim, clockwise) {
  20745. let i, last;
  20746. if (clockwise === signedArea(data, start, end, dim) > 0) {
  20747. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  20748. } else {
  20749. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  20750. }
  20751. if (last && equals(last, last.next)) {
  20752. removeNode(last);
  20753. last = last.next;
  20754. }
  20755. return last;
  20756. }
  20757. // eliminate colinear or duplicate points
  20758. function filterPoints(start, end) {
  20759. if (!start) return start;
  20760. if (!end) end = start;
  20761. let p = start,
  20762. again;
  20763. do {
  20764. again = false;
  20765. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  20766. removeNode(p);
  20767. p = end = p.prev;
  20768. if (p === p.next) break;
  20769. again = true;
  20770. } else {
  20771. p = p.next;
  20772. }
  20773. } while (again || p !== end);
  20774. return end;
  20775. }
  20776. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20777. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  20778. if (!ear) return;
  20779. // interlink polygon nodes in z-order
  20780. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  20781. let stop = ear,
  20782. prev,
  20783. next;
  20784. // iterate through ears, slicing them one by one
  20785. while (ear.prev !== ear.next) {
  20786. prev = ear.prev;
  20787. next = ear.next;
  20788. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  20789. // cut off the triangle
  20790. triangles.push(prev.i / dim | 0);
  20791. triangles.push(ear.i / dim | 0);
  20792. triangles.push(next.i / dim | 0);
  20793. removeNode(ear);
  20794. // skipping the next vertex leads to less sliver triangles
  20795. ear = next.next;
  20796. stop = next.next;
  20797. continue;
  20798. }
  20799. ear = next;
  20800. // if we looped through the whole remaining polygon and can't find any more ears
  20801. if (ear === stop) {
  20802. // try filtering points and slicing again
  20803. if (!pass) {
  20804. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  20805. // if this didn't work, try curing all small self-intersections locally
  20806. } else if (pass === 1) {
  20807. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  20808. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  20809. // as a last resort, try splitting the remaining polygon into two
  20810. } else if (pass === 2) {
  20811. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  20812. }
  20813. break;
  20814. }
  20815. }
  20816. }
  20817. // check whether a polygon node forms a valid ear with adjacent nodes
  20818. function isEar(ear) {
  20819. const a = ear.prev,
  20820. b = ear,
  20821. c = ear.next;
  20822. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20823. // now make sure we don't have other points inside the potential ear
  20824. const ax = a.x,
  20825. bx = b.x,
  20826. cx = c.x,
  20827. ay = a.y,
  20828. by = b.y,
  20829. cy = c.y;
  20830. // triangle bbox; min & max are calculated like this for speed
  20831. const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx,
  20832. y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy,
  20833. x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx,
  20834. y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
  20835. let p = c.next;
  20836. while (p !== a) {
  20837. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20838. p = p.next;
  20839. }
  20840. return true;
  20841. }
  20842. function isEarHashed(ear, minX, minY, invSize) {
  20843. const a = ear.prev,
  20844. b = ear,
  20845. c = ear.next;
  20846. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20847. const ax = a.x,
  20848. bx = b.x,
  20849. cx = c.x,
  20850. ay = a.y,
  20851. by = b.y,
  20852. cy = c.y;
  20853. // triangle bbox; min & max are calculated like this for speed
  20854. const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx,
  20855. y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy,
  20856. x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx,
  20857. y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
  20858. // z-order range for the current triangle bbox;
  20859. const minZ = zOrder(x0, y0, minX, minY, invSize),
  20860. maxZ = zOrder(x1, y1, minX, minY, invSize);
  20861. let p = ear.prevZ,
  20862. n = ear.nextZ;
  20863. // look for points inside the triangle in both directions
  20864. while (p && p.z >= minZ && n && n.z <= maxZ) {
  20865. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20866. p = p.prevZ;
  20867. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20868. n = n.nextZ;
  20869. }
  20870. // look for remaining points in decreasing z-order
  20871. while (p && p.z >= minZ) {
  20872. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20873. p = p.prevZ;
  20874. }
  20875. // look for remaining points in increasing z-order
  20876. while (n && n.z <= maxZ) {
  20877. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20878. n = n.nextZ;
  20879. }
  20880. return true;
  20881. }
  20882. // go through all polygon nodes and cure small local self-intersections
  20883. function cureLocalIntersections(start, triangles, dim) {
  20884. let p = start;
  20885. do {
  20886. const a = p.prev,
  20887. b = p.next.next;
  20888. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  20889. triangles.push(a.i / dim | 0);
  20890. triangles.push(p.i / dim | 0);
  20891. triangles.push(b.i / dim | 0);
  20892. // remove two nodes involved
  20893. removeNode(p);
  20894. removeNode(p.next);
  20895. p = start = b;
  20896. }
  20897. p = p.next;
  20898. } while (p !== start);
  20899. return filterPoints(p);
  20900. }
  20901. // try splitting polygon into two and triangulate them independently
  20902. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  20903. // look for a valid diagonal that divides the polygon into two
  20904. let a = start;
  20905. do {
  20906. let b = a.next.next;
  20907. while (b !== a.prev) {
  20908. if (a.i !== b.i && isValidDiagonal(a, b)) {
  20909. // split the polygon in two by the diagonal
  20910. let c = splitPolygon(a, b);
  20911. // filter colinear points around the cuts
  20912. a = filterPoints(a, a.next);
  20913. c = filterPoints(c, c.next);
  20914. // run earcut on each half
  20915. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  20916. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  20917. return;
  20918. }
  20919. b = b.next;
  20920. }
  20921. a = a.next;
  20922. } while (a !== start);
  20923. }
  20924. // link every hole into the outer loop, producing a single-ring polygon without holes
  20925. function eliminateHoles(data, holeIndices, outerNode, dim) {
  20926. const queue = [];
  20927. let i, len, start, end, list;
  20928. for (i = 0, len = holeIndices.length; i < len; i++) {
  20929. start = holeIndices[i] * dim;
  20930. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  20931. list = linkedList(data, start, end, dim, false);
  20932. if (list === list.next) list.steiner = true;
  20933. queue.push(getLeftmost(list));
  20934. }
  20935. queue.sort(compareX);
  20936. // process holes from left to right
  20937. for (i = 0; i < queue.length; i++) {
  20938. outerNode = eliminateHole(queue[i], outerNode);
  20939. }
  20940. return outerNode;
  20941. }
  20942. function compareX(a, b) {
  20943. return a.x - b.x;
  20944. }
  20945. // find a bridge between vertices that connects hole with an outer ring and link it
  20946. function eliminateHole(hole, outerNode) {
  20947. const bridge = findHoleBridge(hole, outerNode);
  20948. if (!bridge) {
  20949. return outerNode;
  20950. }
  20951. const bridgeReverse = splitPolygon(bridge, hole);
  20952. // filter collinear points around the cuts
  20953. filterPoints(bridgeReverse, bridgeReverse.next);
  20954. return filterPoints(bridge, bridge.next);
  20955. }
  20956. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20957. function findHoleBridge(hole, outerNode) {
  20958. let p = outerNode,
  20959. qx = -Infinity,
  20960. m;
  20961. const hx = hole.x,
  20962. hy = hole.y;
  20963. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20964. // segment's endpoint with lesser x will be potential connection point
  20965. do {
  20966. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  20967. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  20968. if (x <= hx && x > qx) {
  20969. qx = x;
  20970. m = p.x < p.next.x ? p : p.next;
  20971. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  20972. }
  20973. }
  20974. p = p.next;
  20975. } while (p !== outerNode);
  20976. if (!m) return null;
  20977. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20978. // if there are no points found, we have a valid connection;
  20979. // otherwise choose the point of the minimum angle with the ray as connection point
  20980. const stop = m,
  20981. mx = m.x,
  20982. my = m.y;
  20983. let tanMin = Infinity,
  20984. tan;
  20985. p = m;
  20986. do {
  20987. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  20988. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  20989. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  20990. m = p;
  20991. tanMin = tan;
  20992. }
  20993. }
  20994. p = p.next;
  20995. } while (p !== stop);
  20996. return m;
  20997. }
  20998. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20999. function sectorContainsSector(m, p) {
  21000. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  21001. }
  21002. // interlink polygon nodes in z-order
  21003. function indexCurve(start, minX, minY, invSize) {
  21004. let p = start;
  21005. do {
  21006. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  21007. p.prevZ = p.prev;
  21008. p.nextZ = p.next;
  21009. p = p.next;
  21010. } while (p !== start);
  21011. p.prevZ.nextZ = null;
  21012. p.prevZ = null;
  21013. sortLinked(p);
  21014. }
  21015. // Simon Tatham's linked list merge sort algorithm
  21016. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21017. function sortLinked(list) {
  21018. let i,
  21019. p,
  21020. q,
  21021. e,
  21022. tail,
  21023. numMerges,
  21024. pSize,
  21025. qSize,
  21026. inSize = 1;
  21027. do {
  21028. p = list;
  21029. list = null;
  21030. tail = null;
  21031. numMerges = 0;
  21032. while (p) {
  21033. numMerges++;
  21034. q = p;
  21035. pSize = 0;
  21036. for (i = 0; i < inSize; i++) {
  21037. pSize++;
  21038. q = q.nextZ;
  21039. if (!q) break;
  21040. }
  21041. qSize = inSize;
  21042. while (pSize > 0 || qSize > 0 && q) {
  21043. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  21044. e = p;
  21045. p = p.nextZ;
  21046. pSize--;
  21047. } else {
  21048. e = q;
  21049. q = q.nextZ;
  21050. qSize--;
  21051. }
  21052. if (tail) tail.nextZ = e;else list = e;
  21053. e.prevZ = tail;
  21054. tail = e;
  21055. }
  21056. p = q;
  21057. }
  21058. tail.nextZ = null;
  21059. inSize *= 2;
  21060. } while (numMerges > 1);
  21061. return list;
  21062. }
  21063. // z-order of a point given coords and inverse of the longer side of data bbox
  21064. function zOrder(x, y, minX, minY, invSize) {
  21065. // coords are transformed into non-negative 15-bit integer range
  21066. x = (x - minX) * invSize | 0;
  21067. y = (y - minY) * invSize | 0;
  21068. x = (x | x << 8) & 0x00FF00FF;
  21069. x = (x | x << 4) & 0x0F0F0F0F;
  21070. x = (x | x << 2) & 0x33333333;
  21071. x = (x | x << 1) & 0x55555555;
  21072. y = (y | y << 8) & 0x00FF00FF;
  21073. y = (y | y << 4) & 0x0F0F0F0F;
  21074. y = (y | y << 2) & 0x33333333;
  21075. y = (y | y << 1) & 0x55555555;
  21076. return x | y << 1;
  21077. }
  21078. // find the leftmost node of a polygon ring
  21079. function getLeftmost(start) {
  21080. let p = start,
  21081. leftmost = start;
  21082. do {
  21083. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  21084. p = p.next;
  21085. } while (p !== start);
  21086. return leftmost;
  21087. }
  21088. // check if a point lies within a convex triangle
  21089. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  21090. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py);
  21091. }
  21092. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21093. function isValidDiagonal(a, b) {
  21094. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (
  21095. // dones't intersect other edges
  21096. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (
  21097. // locally visible
  21098. area(a.prev, a, b.prev) || area(a, b.prev, b)) ||
  21099. // does not create opposite-facing sectors
  21100. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  21101. }
  21102. // signed area of a triangle
  21103. function area(p, q, r) {
  21104. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  21105. }
  21106. // check if two points are equal
  21107. function equals(p1, p2) {
  21108. return p1.x === p2.x && p1.y === p2.y;
  21109. }
  21110. // check if two segments intersect
  21111. function intersects(p1, q1, p2, q2) {
  21112. const o1 = sign(area(p1, q1, p2));
  21113. const o2 = sign(area(p1, q1, q2));
  21114. const o3 = sign(area(p2, q2, p1));
  21115. const o4 = sign(area(p2, q2, q1));
  21116. if (o1 !== o2 && o3 !== o4) return true; // general case
  21117. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21118. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21119. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21120. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21121. return false;
  21122. }
  21123. // for collinear points p, q, r, check if point q lies on segment pr
  21124. function onSegment(p, q, r) {
  21125. 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);
  21126. }
  21127. function sign(num) {
  21128. return num > 0 ? 1 : num < 0 ? -1 : 0;
  21129. }
  21130. // check if a polygon diagonal intersects any polygon segments
  21131. function intersectsPolygon(a, b) {
  21132. let p = a;
  21133. do {
  21134. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  21135. p = p.next;
  21136. } while (p !== a);
  21137. return false;
  21138. }
  21139. // check if a polygon diagonal is locally inside the polygon
  21140. function locallyInside(a, b) {
  21141. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  21142. }
  21143. // check if the middle point of a polygon diagonal is inside the polygon
  21144. function middleInside(a, b) {
  21145. let p = a,
  21146. inside = false;
  21147. const px = (a.x + b.x) / 2,
  21148. py = (a.y + b.y) / 2;
  21149. do {
  21150. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  21151. p = p.next;
  21152. } while (p !== a);
  21153. return inside;
  21154. }
  21155. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21156. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21157. function splitPolygon(a, b) {
  21158. const a2 = new Node(a.i, a.x, a.y),
  21159. b2 = new Node(b.i, b.x, b.y),
  21160. an = a.next,
  21161. bp = b.prev;
  21162. a.next = b;
  21163. b.prev = a;
  21164. a2.next = an;
  21165. an.prev = a2;
  21166. b2.next = a2;
  21167. a2.prev = b2;
  21168. bp.next = b2;
  21169. b2.prev = bp;
  21170. return b2;
  21171. }
  21172. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21173. function insertNode(i, x, y, last) {
  21174. const p = new Node(i, x, y);
  21175. if (!last) {
  21176. p.prev = p;
  21177. p.next = p;
  21178. } else {
  21179. p.next = last.next;
  21180. p.prev = last;
  21181. last.next.prev = p;
  21182. last.next = p;
  21183. }
  21184. return p;
  21185. }
  21186. function removeNode(p) {
  21187. p.next.prev = p.prev;
  21188. p.prev.next = p.next;
  21189. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  21190. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  21191. }
  21192. function Node(i, x, y) {
  21193. // vertex index in coordinates array
  21194. this.i = i;
  21195. // vertex coordinates
  21196. this.x = x;
  21197. this.y = y;
  21198. // previous and next vertex nodes in a polygon ring
  21199. this.prev = null;
  21200. this.next = null;
  21201. // z-order curve value
  21202. this.z = 0;
  21203. // previous and next nodes in z-order
  21204. this.prevZ = null;
  21205. this.nextZ = null;
  21206. // indicates whether this is a steiner point
  21207. this.steiner = false;
  21208. }
  21209. function signedArea(data, start, end, dim) {
  21210. let sum = 0;
  21211. for (let i = start, j = end - dim; i < end; i += dim) {
  21212. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  21213. j = i;
  21214. }
  21215. return sum;
  21216. }
  21217. class ShapeUtils {
  21218. // calculate area of the contour polygon
  21219. static area(contour) {
  21220. const n = contour.length;
  21221. let a = 0.0;
  21222. for (let p = n - 1, q = 0; q < n; p = q++) {
  21223. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  21224. }
  21225. return a * 0.5;
  21226. }
  21227. static isClockWise(pts) {
  21228. return ShapeUtils.area(pts) < 0;
  21229. }
  21230. static triangulateShape(contour, holes) {
  21231. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21232. const holeIndices = []; // array of hole indices
  21233. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21234. removeDupEndPts(contour);
  21235. addContour(vertices, contour);
  21236. //
  21237. let holeIndex = contour.length;
  21238. holes.forEach(removeDupEndPts);
  21239. for (let i = 0; i < holes.length; i++) {
  21240. holeIndices.push(holeIndex);
  21241. holeIndex += holes[i].length;
  21242. addContour(vertices, holes[i]);
  21243. }
  21244. //
  21245. const triangles = Earcut.triangulate(vertices, holeIndices);
  21246. //
  21247. for (let i = 0; i < triangles.length; i += 3) {
  21248. faces.push(triangles.slice(i, i + 3));
  21249. }
  21250. return faces;
  21251. }
  21252. }
  21253. function removeDupEndPts(points) {
  21254. const l = points.length;
  21255. if (l > 2 && points[l - 1].equals(points[0])) {
  21256. points.pop();
  21257. }
  21258. }
  21259. function addContour(vertices, contour) {
  21260. for (let i = 0; i < contour.length; i++) {
  21261. vertices.push(contour[i].x);
  21262. vertices.push(contour[i].y);
  21263. }
  21264. }
  21265. /**
  21266. * Creates extruded geometry from a path shape.
  21267. *
  21268. * parameters = {
  21269. *
  21270. * curveSegments: <int>, // number of points on the curves
  21271. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21272. * depth: <float>, // Depth to extrude the shape
  21273. *
  21274. * bevelEnabled: <bool>, // turn on bevel
  21275. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21276. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21277. * bevelOffset: <float>, // how far from shape outline does bevel start
  21278. * bevelSegments: <int>, // number of bevel layers
  21279. *
  21280. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21281. *
  21282. * UVGenerator: <Object> // object that provides UV generator functions
  21283. *
  21284. * }
  21285. */
  21286. class ExtrudeGeometry extends BufferGeometry {
  21287. 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 = {}) {
  21288. super();
  21289. this.type = 'ExtrudeGeometry';
  21290. this.parameters = {
  21291. shapes: shapes,
  21292. options: options
  21293. };
  21294. shapes = Array.isArray(shapes) ? shapes : [shapes];
  21295. const scope = this;
  21296. const verticesArray = [];
  21297. const uvArray = [];
  21298. for (let i = 0, l = shapes.length; i < l; i++) {
  21299. const shape = shapes[i];
  21300. addShape(shape);
  21301. }
  21302. // build geometry
  21303. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  21304. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  21305. this.computeVertexNormals();
  21306. // functions
  21307. function addShape(shape) {
  21308. const placeholder = [];
  21309. // options
  21310. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21311. const steps = options.steps !== undefined ? options.steps : 1;
  21312. const depth = options.depth !== undefined ? options.depth : 1;
  21313. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21314. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21315. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21316. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21317. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21318. const extrudePath = options.extrudePath;
  21319. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21320. //
  21321. let extrudePts,
  21322. extrudeByPath = false;
  21323. let splineTube, binormal, normal, position2;
  21324. if (extrudePath) {
  21325. extrudePts = extrudePath.getSpacedPoints(steps);
  21326. extrudeByPath = true;
  21327. bevelEnabled = false; // bevels not supported for path extrusion
  21328. // SETUP TNB variables
  21329. // TODO1 - have a .isClosed in spline?
  21330. splineTube = extrudePath.computeFrenetFrames(steps, false);
  21331. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21332. binormal = new Vector3();
  21333. normal = new Vector3();
  21334. position2 = new Vector3();
  21335. }
  21336. // Safeguards if bevels are not enabled
  21337. if (!bevelEnabled) {
  21338. bevelSegments = 0;
  21339. bevelThickness = 0;
  21340. bevelSize = 0;
  21341. bevelOffset = 0;
  21342. }
  21343. // Variables initialization
  21344. const shapePoints = shape.extractPoints(curveSegments);
  21345. let vertices = shapePoints.shape;
  21346. const holes = shapePoints.holes;
  21347. const reverse = !ShapeUtils.isClockWise(vertices);
  21348. if (reverse) {
  21349. vertices = vertices.reverse();
  21350. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21351. for (let h = 0, hl = holes.length; h < hl; h++) {
  21352. const ahole = holes[h];
  21353. if (ShapeUtils.isClockWise(ahole)) {
  21354. holes[h] = ahole.reverse();
  21355. }
  21356. }
  21357. }
  21358. const faces = ShapeUtils.triangulateShape(vertices, holes);
  21359. /* Vertices */
  21360. const contour = vertices; // vertices has all points but contour has only points of circumference
  21361. for (let h = 0, hl = holes.length; h < hl; h++) {
  21362. const ahole = holes[h];
  21363. vertices = vertices.concat(ahole);
  21364. }
  21365. function scalePt2(pt, vec, size) {
  21366. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  21367. return vec.clone().multiplyScalar(size).add(pt);
  21368. }
  21369. const vlen = vertices.length,
  21370. flen = faces.length;
  21371. // Find directions for point movement
  21372. function getBevelVec(inPt, inPrev, inNext) {
  21373. // computes for inPt the corresponding point inPt' on a new contour
  21374. // shifted by 1 unit (length of normalized vector) to the left
  21375. // if we walk along contour clockwise, this new contour is outside the old one
  21376. //
  21377. // inPt' is the intersection of the two lines parallel to the two
  21378. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21379. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21380. // good reading for geometry algorithms (here: line-line intersection)
  21381. // http://geomalgorithms.com/a05-_intersect-1.html
  21382. const v_prev_x = inPt.x - inPrev.x,
  21383. v_prev_y = inPt.y - inPrev.y;
  21384. const v_next_x = inNext.x - inPt.x,
  21385. v_next_y = inNext.y - inPt.y;
  21386. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y;
  21387. // check for collinear edges
  21388. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  21389. if (Math.abs(collinear0) > Number.EPSILON) {
  21390. // not collinear
  21391. // length of vectors for normalizing
  21392. const v_prev_len = Math.sqrt(v_prev_lensq);
  21393. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y);
  21394. // shift adjacent points by unit vectors to the left
  21395. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  21396. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  21397. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  21398. const ptNextShift_y = inNext.y + v_next_x / v_next_len;
  21399. // scaling factor for v_prev to intersection point
  21400. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x);
  21401. // vector from inPt to intersection point
  21402. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  21403. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y;
  21404. // Don't normalize!, otherwise sharp corners become ugly
  21405. // but prevent crazy spikes
  21406. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  21407. if (v_trans_lensq <= 2) {
  21408. return new Vector2(v_trans_x, v_trans_y);
  21409. } else {
  21410. shrink_by = Math.sqrt(v_trans_lensq / 2);
  21411. }
  21412. } else {
  21413. // handle special case of collinear edges
  21414. let direction_eq = false; // assumes: opposite
  21415. if (v_prev_x > Number.EPSILON) {
  21416. if (v_next_x > Number.EPSILON) {
  21417. direction_eq = true;
  21418. }
  21419. } else {
  21420. if (v_prev_x < -Number.EPSILON) {
  21421. if (v_next_x < -Number.EPSILON) {
  21422. direction_eq = true;
  21423. }
  21424. } else {
  21425. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  21426. direction_eq = true;
  21427. }
  21428. }
  21429. }
  21430. if (direction_eq) {
  21431. // console.log("Warning: lines are a straight sequence");
  21432. v_trans_x = -v_prev_y;
  21433. v_trans_y = v_prev_x;
  21434. shrink_by = Math.sqrt(v_prev_lensq);
  21435. } else {
  21436. // console.log("Warning: lines are a straight spike");
  21437. v_trans_x = v_prev_x;
  21438. v_trans_y = v_prev_y;
  21439. shrink_by = Math.sqrt(v_prev_lensq / 2);
  21440. }
  21441. }
  21442. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  21443. }
  21444. const contourMovements = [];
  21445. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  21446. if (j === il) j = 0;
  21447. if (k === il) k = 0;
  21448. // (j)---(i)---(k)
  21449. // console.log('i,j,k', i, j , k)
  21450. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  21451. }
  21452. const holesMovements = [];
  21453. let oneHoleMovements,
  21454. verticesMovements = contourMovements.concat();
  21455. for (let h = 0, hl = holes.length; h < hl; h++) {
  21456. const ahole = holes[h];
  21457. oneHoleMovements = [];
  21458. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  21459. if (j === il) j = 0;
  21460. if (k === il) k = 0;
  21461. // (j)---(i)---(k)
  21462. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  21463. }
  21464. holesMovements.push(oneHoleMovements);
  21465. verticesMovements = verticesMovements.concat(oneHoleMovements);
  21466. }
  21467. // Loop bevelSegments, 1 for the front, 1 for the back
  21468. for (let b = 0; b < bevelSegments; b++) {
  21469. //for ( b = bevelSegments; b > 0; b -- ) {
  21470. const t = b / bevelSegments;
  21471. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  21472. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset;
  21473. // contract shape
  21474. for (let i = 0, il = contour.length; i < il; i++) {
  21475. const vert = scalePt2(contour[i], contourMovements[i], bs);
  21476. v(vert.x, vert.y, -z);
  21477. }
  21478. // expand holes
  21479. for (let h = 0, hl = holes.length; h < hl; h++) {
  21480. const ahole = holes[h];
  21481. oneHoleMovements = holesMovements[h];
  21482. for (let i = 0, il = ahole.length; i < il; i++) {
  21483. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  21484. v(vert.x, vert.y, -z);
  21485. }
  21486. }
  21487. }
  21488. const bs = bevelSize + bevelOffset;
  21489. // Back facing vertices
  21490. for (let i = 0; i < vlen; i++) {
  21491. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  21492. if (!extrudeByPath) {
  21493. v(vert.x, vert.y, 0);
  21494. } else {
  21495. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21496. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  21497. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  21498. position2.copy(extrudePts[0]).add(normal).add(binormal);
  21499. v(position2.x, position2.y, position2.z);
  21500. }
  21501. }
  21502. // Add stepped vertices...
  21503. // Including front facing vertices
  21504. for (let s = 1; s <= steps; s++) {
  21505. for (let i = 0; i < vlen; i++) {
  21506. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  21507. if (!extrudeByPath) {
  21508. v(vert.x, vert.y, depth / steps * s);
  21509. } else {
  21510. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21511. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  21512. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  21513. position2.copy(extrudePts[s]).add(normal).add(binormal);
  21514. v(position2.x, position2.y, position2.z);
  21515. }
  21516. }
  21517. }
  21518. // Add bevel segments planes
  21519. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21520. for (let b = bevelSegments - 1; b >= 0; b--) {
  21521. const t = b / bevelSegments;
  21522. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  21523. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset;
  21524. // contract shape
  21525. for (let i = 0, il = contour.length; i < il; i++) {
  21526. const vert = scalePt2(contour[i], contourMovements[i], bs);
  21527. v(vert.x, vert.y, depth + z);
  21528. }
  21529. // expand holes
  21530. for (let h = 0, hl = holes.length; h < hl; h++) {
  21531. const ahole = holes[h];
  21532. oneHoleMovements = holesMovements[h];
  21533. for (let i = 0, il = ahole.length; i < il; i++) {
  21534. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  21535. if (!extrudeByPath) {
  21536. v(vert.x, vert.y, depth + z);
  21537. } else {
  21538. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  21539. }
  21540. }
  21541. }
  21542. }
  21543. /* Faces */
  21544. // Top and bottom faces
  21545. buildLidFaces();
  21546. // Sides faces
  21547. buildSideFaces();
  21548. ///// Internal functions
  21549. function buildLidFaces() {
  21550. const start = verticesArray.length / 3;
  21551. if (bevelEnabled) {
  21552. let layer = 0; // steps + 1
  21553. let offset = vlen * layer;
  21554. // Bottom faces
  21555. for (let i = 0; i < flen; i++) {
  21556. const face = faces[i];
  21557. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  21558. }
  21559. layer = steps + bevelSegments * 2;
  21560. offset = vlen * layer;
  21561. // Top faces
  21562. for (let i = 0; i < flen; i++) {
  21563. const face = faces[i];
  21564. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  21565. }
  21566. } else {
  21567. // Bottom faces
  21568. for (let i = 0; i < flen; i++) {
  21569. const face = faces[i];
  21570. f3(face[2], face[1], face[0]);
  21571. }
  21572. // Top faces
  21573. for (let i = 0; i < flen; i++) {
  21574. const face = faces[i];
  21575. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  21576. }
  21577. }
  21578. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  21579. }
  21580. // Create faces for the z-sides of the shape
  21581. function buildSideFaces() {
  21582. const start = verticesArray.length / 3;
  21583. let layeroffset = 0;
  21584. sidewalls(contour, layeroffset);
  21585. layeroffset += contour.length;
  21586. for (let h = 0, hl = holes.length; h < hl; h++) {
  21587. const ahole = holes[h];
  21588. sidewalls(ahole, layeroffset);
  21589. //, true
  21590. layeroffset += ahole.length;
  21591. }
  21592. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  21593. }
  21594. function sidewalls(contour, layeroffset) {
  21595. let i = contour.length;
  21596. while (--i >= 0) {
  21597. const j = i;
  21598. let k = i - 1;
  21599. if (k < 0) k = contour.length - 1;
  21600. //console.log('b', i,j, i-1, k,vertices.length);
  21601. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  21602. const slen1 = vlen * s;
  21603. const slen2 = vlen * (s + 1);
  21604. const a = layeroffset + j + slen1,
  21605. b = layeroffset + k + slen1,
  21606. c = layeroffset + k + slen2,
  21607. d = layeroffset + j + slen2;
  21608. f4(a, b, c, d);
  21609. }
  21610. }
  21611. }
  21612. function v(x, y, z) {
  21613. placeholder.push(x);
  21614. placeholder.push(y);
  21615. placeholder.push(z);
  21616. }
  21617. function f3(a, b, c) {
  21618. addVertex(a);
  21619. addVertex(b);
  21620. addVertex(c);
  21621. const nextIndex = verticesArray.length / 3;
  21622. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  21623. addUV(uvs[0]);
  21624. addUV(uvs[1]);
  21625. addUV(uvs[2]);
  21626. }
  21627. function f4(a, b, c, d) {
  21628. addVertex(a);
  21629. addVertex(b);
  21630. addVertex(d);
  21631. addVertex(b);
  21632. addVertex(c);
  21633. addVertex(d);
  21634. const nextIndex = verticesArray.length / 3;
  21635. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  21636. addUV(uvs[0]);
  21637. addUV(uvs[1]);
  21638. addUV(uvs[3]);
  21639. addUV(uvs[1]);
  21640. addUV(uvs[2]);
  21641. addUV(uvs[3]);
  21642. }
  21643. function addVertex(index) {
  21644. verticesArray.push(placeholder[index * 3 + 0]);
  21645. verticesArray.push(placeholder[index * 3 + 1]);
  21646. verticesArray.push(placeholder[index * 3 + 2]);
  21647. }
  21648. function addUV(vector2) {
  21649. uvArray.push(vector2.x);
  21650. uvArray.push(vector2.y);
  21651. }
  21652. }
  21653. }
  21654. toJSON() {
  21655. const data = super.toJSON();
  21656. const shapes = this.parameters.shapes;
  21657. const options = this.parameters.options;
  21658. return toJSON$1(shapes, options, data);
  21659. }
  21660. static fromJSON(data, shapes) {
  21661. const geometryShapes = [];
  21662. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21663. const shape = shapes[data.shapes[j]];
  21664. geometryShapes.push(shape);
  21665. }
  21666. const extrudePath = data.options.extrudePath;
  21667. if (extrudePath !== undefined) {
  21668. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  21669. }
  21670. return new ExtrudeGeometry(geometryShapes, data.options);
  21671. }
  21672. }
  21673. const WorldUVGenerator = {
  21674. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  21675. const a_x = vertices[indexA * 3];
  21676. const a_y = vertices[indexA * 3 + 1];
  21677. const b_x = vertices[indexB * 3];
  21678. const b_y = vertices[indexB * 3 + 1];
  21679. const c_x = vertices[indexC * 3];
  21680. const c_y = vertices[indexC * 3 + 1];
  21681. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  21682. },
  21683. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  21684. const a_x = vertices[indexA * 3];
  21685. const a_y = vertices[indexA * 3 + 1];
  21686. const a_z = vertices[indexA * 3 + 2];
  21687. const b_x = vertices[indexB * 3];
  21688. const b_y = vertices[indexB * 3 + 1];
  21689. const b_z = vertices[indexB * 3 + 2];
  21690. const c_x = vertices[indexC * 3];
  21691. const c_y = vertices[indexC * 3 + 1];
  21692. const c_z = vertices[indexC * 3 + 2];
  21693. const d_x = vertices[indexD * 3];
  21694. const d_y = vertices[indexD * 3 + 1];
  21695. const d_z = vertices[indexD * 3 + 2];
  21696. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  21697. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  21698. } else {
  21699. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  21700. }
  21701. }
  21702. };
  21703. function toJSON$1(shapes, options, data) {
  21704. data.shapes = [];
  21705. if (Array.isArray(shapes)) {
  21706. for (let i = 0, l = shapes.length; i < l; i++) {
  21707. const shape = shapes[i];
  21708. data.shapes.push(shape.uuid);
  21709. }
  21710. } else {
  21711. data.shapes.push(shapes.uuid);
  21712. }
  21713. data.options = Object.assign({}, options);
  21714. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  21715. return data;
  21716. }
  21717. class IcosahedronGeometry extends PolyhedronGeometry {
  21718. constructor(radius = 1, detail = 0) {
  21719. const t = (1 + Math.sqrt(5)) / 2;
  21720. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  21721. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  21722. super(vertices, indices, radius, detail);
  21723. this.type = 'IcosahedronGeometry';
  21724. this.parameters = {
  21725. radius: radius,
  21726. detail: detail
  21727. };
  21728. }
  21729. static fromJSON(data) {
  21730. return new IcosahedronGeometry(data.radius, data.detail);
  21731. }
  21732. }
  21733. class OctahedronGeometry extends PolyhedronGeometry {
  21734. constructor(radius = 1, detail = 0) {
  21735. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  21736. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  21737. super(vertices, indices, radius, detail);
  21738. this.type = 'OctahedronGeometry';
  21739. this.parameters = {
  21740. radius: radius,
  21741. detail: detail
  21742. };
  21743. }
  21744. static fromJSON(data) {
  21745. return new OctahedronGeometry(data.radius, data.detail);
  21746. }
  21747. }
  21748. class RingGeometry extends BufferGeometry {
  21749. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  21750. super();
  21751. this.type = 'RingGeometry';
  21752. this.parameters = {
  21753. innerRadius: innerRadius,
  21754. outerRadius: outerRadius,
  21755. thetaSegments: thetaSegments,
  21756. phiSegments: phiSegments,
  21757. thetaStart: thetaStart,
  21758. thetaLength: thetaLength
  21759. };
  21760. thetaSegments = Math.max(3, thetaSegments);
  21761. phiSegments = Math.max(1, phiSegments);
  21762. // buffers
  21763. const indices = [];
  21764. const vertices = [];
  21765. const normals = [];
  21766. const uvs = [];
  21767. // some helper variables
  21768. let radius = innerRadius;
  21769. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  21770. const vertex = new Vector3();
  21771. const uv = new Vector2();
  21772. // generate vertices, normals and uvs
  21773. for (let j = 0; j <= phiSegments; j++) {
  21774. for (let i = 0; i <= thetaSegments; i++) {
  21775. // values are generate from the inside of the ring to the outside
  21776. const segment = thetaStart + i / thetaSegments * thetaLength;
  21777. // vertex
  21778. vertex.x = radius * Math.cos(segment);
  21779. vertex.y = radius * Math.sin(segment);
  21780. vertices.push(vertex.x, vertex.y, vertex.z);
  21781. // normal
  21782. normals.push(0, 0, 1);
  21783. // uv
  21784. uv.x = (vertex.x / outerRadius + 1) / 2;
  21785. uv.y = (vertex.y / outerRadius + 1) / 2;
  21786. uvs.push(uv.x, uv.y);
  21787. }
  21788. // increase the radius for next row of vertices
  21789. radius += radiusStep;
  21790. }
  21791. // indices
  21792. for (let j = 0; j < phiSegments; j++) {
  21793. const thetaSegmentLevel = j * (thetaSegments + 1);
  21794. for (let i = 0; i < thetaSegments; i++) {
  21795. const segment = i + thetaSegmentLevel;
  21796. const a = segment;
  21797. const b = segment + thetaSegments + 1;
  21798. const c = segment + thetaSegments + 2;
  21799. const d = segment + 1;
  21800. // faces
  21801. indices.push(a, b, d);
  21802. indices.push(b, c, d);
  21803. }
  21804. }
  21805. // build geometry
  21806. this.setIndex(indices);
  21807. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21808. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21809. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21810. }
  21811. static fromJSON(data) {
  21812. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  21813. }
  21814. }
  21815. class ShapeGeometry extends BufferGeometry {
  21816. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  21817. super();
  21818. this.type = 'ShapeGeometry';
  21819. this.parameters = {
  21820. shapes: shapes,
  21821. curveSegments: curveSegments
  21822. };
  21823. // buffers
  21824. const indices = [];
  21825. const vertices = [];
  21826. const normals = [];
  21827. const uvs = [];
  21828. // helper variables
  21829. let groupStart = 0;
  21830. let groupCount = 0;
  21831. // allow single and array values for "shapes" parameter
  21832. if (Array.isArray(shapes) === false) {
  21833. addShape(shapes);
  21834. } else {
  21835. for (let i = 0; i < shapes.length; i++) {
  21836. addShape(shapes[i]);
  21837. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  21838. groupStart += groupCount;
  21839. groupCount = 0;
  21840. }
  21841. }
  21842. // build geometry
  21843. this.setIndex(indices);
  21844. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21845. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21846. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21847. // helper functions
  21848. function addShape(shape) {
  21849. const indexOffset = vertices.length / 3;
  21850. const points = shape.extractPoints(curveSegments);
  21851. let shapeVertices = points.shape;
  21852. const shapeHoles = points.holes;
  21853. // check direction of vertices
  21854. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  21855. shapeVertices = shapeVertices.reverse();
  21856. }
  21857. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21858. const shapeHole = shapeHoles[i];
  21859. if (ShapeUtils.isClockWise(shapeHole) === true) {
  21860. shapeHoles[i] = shapeHole.reverse();
  21861. }
  21862. }
  21863. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles);
  21864. // join vertices of inner and outer paths to a single array
  21865. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21866. const shapeHole = shapeHoles[i];
  21867. shapeVertices = shapeVertices.concat(shapeHole);
  21868. }
  21869. // vertices, normals, uvs
  21870. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  21871. const vertex = shapeVertices[i];
  21872. vertices.push(vertex.x, vertex.y, 0);
  21873. normals.push(0, 0, 1);
  21874. uvs.push(vertex.x, vertex.y); // world uvs
  21875. }
  21876. // indices
  21877. for (let i = 0, l = faces.length; i < l; i++) {
  21878. const face = faces[i];
  21879. const a = face[0] + indexOffset;
  21880. const b = face[1] + indexOffset;
  21881. const c = face[2] + indexOffset;
  21882. indices.push(a, b, c);
  21883. groupCount += 3;
  21884. }
  21885. }
  21886. }
  21887. toJSON() {
  21888. const data = super.toJSON();
  21889. const shapes = this.parameters.shapes;
  21890. return toJSON(shapes, data);
  21891. }
  21892. static fromJSON(data, shapes) {
  21893. const geometryShapes = [];
  21894. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21895. const shape = shapes[data.shapes[j]];
  21896. geometryShapes.push(shape);
  21897. }
  21898. return new ShapeGeometry(geometryShapes, data.curveSegments);
  21899. }
  21900. }
  21901. function toJSON(shapes, data) {
  21902. data.shapes = [];
  21903. if (Array.isArray(shapes)) {
  21904. for (let i = 0, l = shapes.length; i < l; i++) {
  21905. const shape = shapes[i];
  21906. data.shapes.push(shape.uuid);
  21907. }
  21908. } else {
  21909. data.shapes.push(shapes.uuid);
  21910. }
  21911. return data;
  21912. }
  21913. class SphereGeometry extends BufferGeometry {
  21914. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  21915. super();
  21916. this.type = 'SphereGeometry';
  21917. this.parameters = {
  21918. radius: radius,
  21919. widthSegments: widthSegments,
  21920. heightSegments: heightSegments,
  21921. phiStart: phiStart,
  21922. phiLength: phiLength,
  21923. thetaStart: thetaStart,
  21924. thetaLength: thetaLength
  21925. };
  21926. widthSegments = Math.max(3, Math.floor(widthSegments));
  21927. heightSegments = Math.max(2, Math.floor(heightSegments));
  21928. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  21929. let index = 0;
  21930. const grid = [];
  21931. const vertex = new Vector3();
  21932. const normal = new Vector3();
  21933. // buffers
  21934. const indices = [];
  21935. const vertices = [];
  21936. const normals = [];
  21937. const uvs = [];
  21938. // generate vertices, normals and uvs
  21939. for (let iy = 0; iy <= heightSegments; iy++) {
  21940. const verticesRow = [];
  21941. const v = iy / heightSegments;
  21942. // special case for the poles
  21943. let uOffset = 0;
  21944. if (iy == 0 && thetaStart == 0) {
  21945. uOffset = 0.5 / widthSegments;
  21946. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  21947. uOffset = -0.5 / widthSegments;
  21948. }
  21949. for (let ix = 0; ix <= widthSegments; ix++) {
  21950. const u = ix / widthSegments;
  21951. // vertex
  21952. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21953. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  21954. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21955. vertices.push(vertex.x, vertex.y, vertex.z);
  21956. // normal
  21957. normal.copy(vertex).normalize();
  21958. normals.push(normal.x, normal.y, normal.z);
  21959. // uv
  21960. uvs.push(u + uOffset, 1 - v);
  21961. verticesRow.push(index++);
  21962. }
  21963. grid.push(verticesRow);
  21964. }
  21965. // indices
  21966. for (let iy = 0; iy < heightSegments; iy++) {
  21967. for (let ix = 0; ix < widthSegments; ix++) {
  21968. const a = grid[iy][ix + 1];
  21969. const b = grid[iy][ix];
  21970. const c = grid[iy + 1][ix];
  21971. const d = grid[iy + 1][ix + 1];
  21972. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  21973. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  21974. }
  21975. }
  21976. // build geometry
  21977. this.setIndex(indices);
  21978. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21979. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21980. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21981. }
  21982. static fromJSON(data) {
  21983. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  21984. }
  21985. }
  21986. class TetrahedronGeometry extends PolyhedronGeometry {
  21987. constructor(radius = 1, detail = 0) {
  21988. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  21989. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  21990. super(vertices, indices, radius, detail);
  21991. this.type = 'TetrahedronGeometry';
  21992. this.parameters = {
  21993. radius: radius,
  21994. detail: detail
  21995. };
  21996. }
  21997. static fromJSON(data) {
  21998. return new TetrahedronGeometry(data.radius, data.detail);
  21999. }
  22000. }
  22001. class TorusGeometry extends BufferGeometry {
  22002. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  22003. super();
  22004. this.type = 'TorusGeometry';
  22005. this.parameters = {
  22006. radius: radius,
  22007. tube: tube,
  22008. radialSegments: radialSegments,
  22009. tubularSegments: tubularSegments,
  22010. arc: arc
  22011. };
  22012. radialSegments = Math.floor(radialSegments);
  22013. tubularSegments = Math.floor(tubularSegments);
  22014. // buffers
  22015. const indices = [];
  22016. const vertices = [];
  22017. const normals = [];
  22018. const uvs = [];
  22019. // helper variables
  22020. const center = new Vector3();
  22021. const vertex = new Vector3();
  22022. const normal = new Vector3();
  22023. // generate vertices, normals and uvs
  22024. for (let j = 0; j <= radialSegments; j++) {
  22025. for (let i = 0; i <= tubularSegments; i++) {
  22026. const u = i / tubularSegments * arc;
  22027. const v = j / radialSegments * Math.PI * 2;
  22028. // vertex
  22029. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  22030. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  22031. vertex.z = tube * Math.sin(v);
  22032. vertices.push(vertex.x, vertex.y, vertex.z);
  22033. // normal
  22034. center.x = radius * Math.cos(u);
  22035. center.y = radius * Math.sin(u);
  22036. normal.subVectors(vertex, center).normalize();
  22037. normals.push(normal.x, normal.y, normal.z);
  22038. // uv
  22039. uvs.push(i / tubularSegments);
  22040. uvs.push(j / radialSegments);
  22041. }
  22042. }
  22043. // generate indices
  22044. for (let j = 1; j <= radialSegments; j++) {
  22045. for (let i = 1; i <= tubularSegments; i++) {
  22046. // indices
  22047. const a = (tubularSegments + 1) * j + i - 1;
  22048. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  22049. const c = (tubularSegments + 1) * (j - 1) + i;
  22050. const d = (tubularSegments + 1) * j + i;
  22051. // faces
  22052. indices.push(a, b, d);
  22053. indices.push(b, c, d);
  22054. }
  22055. }
  22056. // build geometry
  22057. this.setIndex(indices);
  22058. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22059. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22060. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22061. }
  22062. static fromJSON(data) {
  22063. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  22064. }
  22065. }
  22066. class TorusKnotGeometry extends BufferGeometry {
  22067. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  22068. super();
  22069. this.type = 'TorusKnotGeometry';
  22070. this.parameters = {
  22071. radius: radius,
  22072. tube: tube,
  22073. tubularSegments: tubularSegments,
  22074. radialSegments: radialSegments,
  22075. p: p,
  22076. q: q
  22077. };
  22078. tubularSegments = Math.floor(tubularSegments);
  22079. radialSegments = Math.floor(radialSegments);
  22080. // buffers
  22081. const indices = [];
  22082. const vertices = [];
  22083. const normals = [];
  22084. const uvs = [];
  22085. // helper variables
  22086. const vertex = new Vector3();
  22087. const normal = new Vector3();
  22088. const P1 = new Vector3();
  22089. const P2 = new Vector3();
  22090. const B = new Vector3();
  22091. const T = new Vector3();
  22092. const N = new Vector3();
  22093. // generate vertices, normals and uvs
  22094. for (let i = 0; i <= tubularSegments; ++i) {
  22095. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22096. const u = i / tubularSegments * p * Math.PI * 2;
  22097. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22098. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22099. calculatePositionOnCurve(u, p, q, radius, P1);
  22100. calculatePositionOnCurve(u + 0.01, p, q, radius, P2);
  22101. // calculate orthonormal basis
  22102. T.subVectors(P2, P1);
  22103. N.addVectors(P2, P1);
  22104. B.crossVectors(T, N);
  22105. N.crossVectors(B, T);
  22106. // normalize B, N. T can be ignored, we don't use it
  22107. B.normalize();
  22108. N.normalize();
  22109. for (let j = 0; j <= radialSegments; ++j) {
  22110. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22111. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22112. const v = j / radialSegments * Math.PI * 2;
  22113. const cx = -tube * Math.cos(v);
  22114. const cy = tube * Math.sin(v);
  22115. // now calculate the final vertex position.
  22116. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22117. vertex.x = P1.x + (cx * N.x + cy * B.x);
  22118. vertex.y = P1.y + (cx * N.y + cy * B.y);
  22119. vertex.z = P1.z + (cx * N.z + cy * B.z);
  22120. vertices.push(vertex.x, vertex.y, vertex.z);
  22121. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22122. normal.subVectors(vertex, P1).normalize();
  22123. normals.push(normal.x, normal.y, normal.z);
  22124. // uv
  22125. uvs.push(i / tubularSegments);
  22126. uvs.push(j / radialSegments);
  22127. }
  22128. }
  22129. // generate indices
  22130. for (let j = 1; j <= tubularSegments; j++) {
  22131. for (let i = 1; i <= radialSegments; i++) {
  22132. // indices
  22133. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  22134. const b = (radialSegments + 1) * j + (i - 1);
  22135. const c = (radialSegments + 1) * j + i;
  22136. const d = (radialSegments + 1) * (j - 1) + i;
  22137. // faces
  22138. indices.push(a, b, d);
  22139. indices.push(b, c, d);
  22140. }
  22141. }
  22142. // build geometry
  22143. this.setIndex(indices);
  22144. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22145. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22146. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22147. // this function calculates the current position on the torus curve
  22148. function calculatePositionOnCurve(u, p, q, radius, position) {
  22149. const cu = Math.cos(u);
  22150. const su = Math.sin(u);
  22151. const quOverP = q / p * u;
  22152. const cs = Math.cos(quOverP);
  22153. position.x = radius * (2 + cs) * 0.5 * cu;
  22154. position.y = radius * (2 + cs) * su * 0.5;
  22155. position.z = radius * Math.sin(quOverP) * 0.5;
  22156. }
  22157. }
  22158. static fromJSON(data) {
  22159. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  22160. }
  22161. }
  22162. class TubeGeometry extends BufferGeometry {
  22163. 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) {
  22164. super();
  22165. this.type = 'TubeGeometry';
  22166. this.parameters = {
  22167. path: path,
  22168. tubularSegments: tubularSegments,
  22169. radius: radius,
  22170. radialSegments: radialSegments,
  22171. closed: closed
  22172. };
  22173. const frames = path.computeFrenetFrames(tubularSegments, closed);
  22174. // expose internals
  22175. this.tangents = frames.tangents;
  22176. this.normals = frames.normals;
  22177. this.binormals = frames.binormals;
  22178. // helper variables
  22179. const vertex = new Vector3();
  22180. const normal = new Vector3();
  22181. const uv = new Vector2();
  22182. let P = new Vector3();
  22183. // buffer
  22184. const vertices = [];
  22185. const normals = [];
  22186. const uvs = [];
  22187. const indices = [];
  22188. // create buffer data
  22189. generateBufferData();
  22190. // build geometry
  22191. this.setIndex(indices);
  22192. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22193. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22194. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22195. // functions
  22196. function generateBufferData() {
  22197. for (let i = 0; i < tubularSegments; i++) {
  22198. generateSegment(i);
  22199. }
  22200. // if the geometry is not closed, generate the last row of vertices and normals
  22201. // at the regular position on the given path
  22202. //
  22203. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22204. generateSegment(closed === false ? tubularSegments : 0);
  22205. // uvs are generated in a separate function.
  22206. // this makes it easy compute correct values for closed geometries
  22207. generateUVs();
  22208. // finally create faces
  22209. generateIndices();
  22210. }
  22211. function generateSegment(i) {
  22212. // we use getPointAt to sample evenly distributed points from the given path
  22213. P = path.getPointAt(i / tubularSegments, P);
  22214. // retrieve corresponding normal and binormal
  22215. const N = frames.normals[i];
  22216. const B = frames.binormals[i];
  22217. // generate normals and vertices for the current segment
  22218. for (let j = 0; j <= radialSegments; j++) {
  22219. const v = j / radialSegments * Math.PI * 2;
  22220. const sin = Math.sin(v);
  22221. const cos = -Math.cos(v);
  22222. // normal
  22223. normal.x = cos * N.x + sin * B.x;
  22224. normal.y = cos * N.y + sin * B.y;
  22225. normal.z = cos * N.z + sin * B.z;
  22226. normal.normalize();
  22227. normals.push(normal.x, normal.y, normal.z);
  22228. // vertex
  22229. vertex.x = P.x + radius * normal.x;
  22230. vertex.y = P.y + radius * normal.y;
  22231. vertex.z = P.z + radius * normal.z;
  22232. vertices.push(vertex.x, vertex.y, vertex.z);
  22233. }
  22234. }
  22235. function generateIndices() {
  22236. for (let j = 1; j <= tubularSegments; j++) {
  22237. for (let i = 1; i <= radialSegments; i++) {
  22238. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  22239. const b = (radialSegments + 1) * j + (i - 1);
  22240. const c = (radialSegments + 1) * j + i;
  22241. const d = (radialSegments + 1) * (j - 1) + i;
  22242. // faces
  22243. indices.push(a, b, d);
  22244. indices.push(b, c, d);
  22245. }
  22246. }
  22247. }
  22248. function generateUVs() {
  22249. for (let i = 0; i <= tubularSegments; i++) {
  22250. for (let j = 0; j <= radialSegments; j++) {
  22251. uv.x = i / tubularSegments;
  22252. uv.y = j / radialSegments;
  22253. uvs.push(uv.x, uv.y);
  22254. }
  22255. }
  22256. }
  22257. }
  22258. toJSON() {
  22259. const data = super.toJSON();
  22260. data.path = this.parameters.path.toJSON();
  22261. return data;
  22262. }
  22263. static fromJSON(data) {
  22264. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22265. // User defined curves or instances of CurvePath will not be deserialized.
  22266. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  22267. }
  22268. }
  22269. class WireframeGeometry extends BufferGeometry {
  22270. constructor(geometry = null) {
  22271. super();
  22272. this.type = 'WireframeGeometry';
  22273. this.parameters = {
  22274. geometry: geometry
  22275. };
  22276. if (geometry !== null) {
  22277. // buffer
  22278. const vertices = [];
  22279. const edges = new Set();
  22280. // helper variables
  22281. const start = new Vector3();
  22282. const end = new Vector3();
  22283. if (geometry.index !== null) {
  22284. // indexed BufferGeometry
  22285. const position = geometry.attributes.position;
  22286. const indices = geometry.index;
  22287. let groups = geometry.groups;
  22288. if (groups.length === 0) {
  22289. groups = [{
  22290. start: 0,
  22291. count: indices.count,
  22292. materialIndex: 0
  22293. }];
  22294. }
  22295. // create a data structure that contains all edges without duplicates
  22296. for (let o = 0, ol = groups.length; o < ol; ++o) {
  22297. const group = groups[o];
  22298. const groupStart = group.start;
  22299. const groupCount = group.count;
  22300. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  22301. for (let j = 0; j < 3; j++) {
  22302. const index1 = indices.getX(i + j);
  22303. const index2 = indices.getX(i + (j + 1) % 3);
  22304. start.fromBufferAttribute(position, index1);
  22305. end.fromBufferAttribute(position, index2);
  22306. if (isUniqueEdge(start, end, edges) === true) {
  22307. vertices.push(start.x, start.y, start.z);
  22308. vertices.push(end.x, end.y, end.z);
  22309. }
  22310. }
  22311. }
  22312. }
  22313. } else {
  22314. // non-indexed BufferGeometry
  22315. const position = geometry.attributes.position;
  22316. for (let i = 0, l = position.count / 3; i < l; i++) {
  22317. for (let j = 0; j < 3; j++) {
  22318. // three edges per triangle, an edge is represented as (index1, index2)
  22319. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22320. const index1 = 3 * i + j;
  22321. const index2 = 3 * i + (j + 1) % 3;
  22322. start.fromBufferAttribute(position, index1);
  22323. end.fromBufferAttribute(position, index2);
  22324. if (isUniqueEdge(start, end, edges) === true) {
  22325. vertices.push(start.x, start.y, start.z);
  22326. vertices.push(end.x, end.y, end.z);
  22327. }
  22328. }
  22329. }
  22330. }
  22331. // build geometry
  22332. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22333. }
  22334. }
  22335. }
  22336. function isUniqueEdge(start, end, edges) {
  22337. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22338. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22339. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  22340. return false;
  22341. } else {
  22342. edges.add(hash1);
  22343. edges.add(hash2);
  22344. return true;
  22345. }
  22346. }
  22347. var Geometries = /*#__PURE__*/Object.freeze({
  22348. __proto__: null,
  22349. BoxGeometry: BoxGeometry,
  22350. CapsuleGeometry: CapsuleGeometry,
  22351. CircleGeometry: CircleGeometry,
  22352. ConeGeometry: ConeGeometry,
  22353. CylinderGeometry: CylinderGeometry,
  22354. DodecahedronGeometry: DodecahedronGeometry,
  22355. EdgesGeometry: EdgesGeometry,
  22356. ExtrudeGeometry: ExtrudeGeometry,
  22357. IcosahedronGeometry: IcosahedronGeometry,
  22358. LatheGeometry: LatheGeometry,
  22359. OctahedronGeometry: OctahedronGeometry,
  22360. PlaneGeometry: PlaneGeometry,
  22361. PolyhedronGeometry: PolyhedronGeometry,
  22362. RingGeometry: RingGeometry,
  22363. ShapeGeometry: ShapeGeometry,
  22364. SphereGeometry: SphereGeometry,
  22365. TetrahedronGeometry: TetrahedronGeometry,
  22366. TorusGeometry: TorusGeometry,
  22367. TorusKnotGeometry: TorusKnotGeometry,
  22368. TubeGeometry: TubeGeometry,
  22369. WireframeGeometry: WireframeGeometry
  22370. });
  22371. class ShadowMaterial extends Material {
  22372. constructor(parameters) {
  22373. super();
  22374. this.isShadowMaterial = true;
  22375. this.type = 'ShadowMaterial';
  22376. this.color = new Color(0x000000);
  22377. this.transparent = true;
  22378. this.fog = true;
  22379. this.setValues(parameters);
  22380. }
  22381. copy(source) {
  22382. super.copy(source);
  22383. this.color.copy(source.color);
  22384. this.fog = source.fog;
  22385. return this;
  22386. }
  22387. }
  22388. class RawShaderMaterial extends ShaderMaterial {
  22389. constructor(parameters) {
  22390. super(parameters);
  22391. this.isRawShaderMaterial = true;
  22392. this.type = 'RawShaderMaterial';
  22393. }
  22394. }
  22395. class MeshStandardMaterial extends Material {
  22396. constructor(parameters) {
  22397. super();
  22398. this.isMeshStandardMaterial = true;
  22399. this.defines = {
  22400. 'STANDARD': ''
  22401. };
  22402. this.type = 'MeshStandardMaterial';
  22403. this.color = new Color(0xffffff); // diffuse
  22404. this.roughness = 1.0;
  22405. this.metalness = 0.0;
  22406. this.map = null;
  22407. this.lightMap = null;
  22408. this.lightMapIntensity = 1.0;
  22409. this.aoMap = null;
  22410. this.aoMapIntensity = 1.0;
  22411. this.emissive = new Color(0x000000);
  22412. this.emissiveIntensity = 1.0;
  22413. this.emissiveMap = null;
  22414. this.bumpMap = null;
  22415. this.bumpScale = 1;
  22416. this.normalMap = null;
  22417. this.normalMapType = TangentSpaceNormalMap;
  22418. this.normalScale = new Vector2(1, 1);
  22419. this.displacementMap = null;
  22420. this.displacementScale = 1;
  22421. this.displacementBias = 0;
  22422. this.roughnessMap = null;
  22423. this.metalnessMap = null;
  22424. this.alphaMap = null;
  22425. this.envMap = null;
  22426. this.envMapIntensity = 1.0;
  22427. this.wireframe = false;
  22428. this.wireframeLinewidth = 1;
  22429. this.wireframeLinecap = 'round';
  22430. this.wireframeLinejoin = 'round';
  22431. this.flatShading = false;
  22432. this.fog = true;
  22433. this.setValues(parameters);
  22434. }
  22435. copy(source) {
  22436. super.copy(source);
  22437. this.defines = {
  22438. 'STANDARD': ''
  22439. };
  22440. this.color.copy(source.color);
  22441. this.roughness = source.roughness;
  22442. this.metalness = source.metalness;
  22443. this.map = source.map;
  22444. this.lightMap = source.lightMap;
  22445. this.lightMapIntensity = source.lightMapIntensity;
  22446. this.aoMap = source.aoMap;
  22447. this.aoMapIntensity = source.aoMapIntensity;
  22448. this.emissive.copy(source.emissive);
  22449. this.emissiveMap = source.emissiveMap;
  22450. this.emissiveIntensity = source.emissiveIntensity;
  22451. this.bumpMap = source.bumpMap;
  22452. this.bumpScale = source.bumpScale;
  22453. this.normalMap = source.normalMap;
  22454. this.normalMapType = source.normalMapType;
  22455. this.normalScale.copy(source.normalScale);
  22456. this.displacementMap = source.displacementMap;
  22457. this.displacementScale = source.displacementScale;
  22458. this.displacementBias = source.displacementBias;
  22459. this.roughnessMap = source.roughnessMap;
  22460. this.metalnessMap = source.metalnessMap;
  22461. this.alphaMap = source.alphaMap;
  22462. this.envMap = source.envMap;
  22463. this.envMapIntensity = source.envMapIntensity;
  22464. this.wireframe = source.wireframe;
  22465. this.wireframeLinewidth = source.wireframeLinewidth;
  22466. this.wireframeLinecap = source.wireframeLinecap;
  22467. this.wireframeLinejoin = source.wireframeLinejoin;
  22468. this.flatShading = source.flatShading;
  22469. this.fog = source.fog;
  22470. return this;
  22471. }
  22472. }
  22473. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22474. constructor(parameters) {
  22475. super();
  22476. this.isMeshPhysicalMaterial = true;
  22477. this.defines = {
  22478. 'STANDARD': '',
  22479. 'PHYSICAL': ''
  22480. };
  22481. this.type = 'MeshPhysicalMaterial';
  22482. this.clearcoatMap = null;
  22483. this.clearcoatRoughness = 0.0;
  22484. this.clearcoatRoughnessMap = null;
  22485. this.clearcoatNormalScale = new Vector2(1, 1);
  22486. this.clearcoatNormalMap = null;
  22487. this.ior = 1.5;
  22488. Object.defineProperty(this, 'reflectivity', {
  22489. get: function () {
  22490. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  22491. },
  22492. set: function (reflectivity) {
  22493. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  22494. }
  22495. });
  22496. this.iridescenceMap = null;
  22497. this.iridescenceIOR = 1.3;
  22498. this.iridescenceThicknessRange = [100, 400];
  22499. this.iridescenceThicknessMap = null;
  22500. this.sheenColor = new Color(0x000000);
  22501. this.sheenColorMap = null;
  22502. this.sheenRoughness = 1.0;
  22503. this.sheenRoughnessMap = null;
  22504. this.transmissionMap = null;
  22505. this.thickness = 0;
  22506. this.thicknessMap = null;
  22507. this.attenuationDistance = Infinity;
  22508. this.attenuationColor = new Color(1, 1, 1);
  22509. this.specularIntensity = 1.0;
  22510. this.specularIntensityMap = null;
  22511. this.specularColor = new Color(1, 1, 1);
  22512. this.specularColorMap = null;
  22513. this._sheen = 0.0;
  22514. this._clearcoat = 0;
  22515. this._iridescence = 0;
  22516. this._transmission = 0;
  22517. this.setValues(parameters);
  22518. }
  22519. get sheen() {
  22520. return this._sheen;
  22521. }
  22522. set sheen(value) {
  22523. if (this._sheen > 0 !== value > 0) {
  22524. this.version++;
  22525. }
  22526. this._sheen = value;
  22527. }
  22528. get clearcoat() {
  22529. return this._clearcoat;
  22530. }
  22531. set clearcoat(value) {
  22532. if (this._clearcoat > 0 !== value > 0) {
  22533. this.version++;
  22534. }
  22535. this._clearcoat = value;
  22536. }
  22537. get iridescence() {
  22538. return this._iridescence;
  22539. }
  22540. set iridescence(value) {
  22541. if (this._iridescence > 0 !== value > 0) {
  22542. this.version++;
  22543. }
  22544. this._iridescence = value;
  22545. }
  22546. get transmission() {
  22547. return this._transmission;
  22548. }
  22549. set transmission(value) {
  22550. if (this._transmission > 0 !== value > 0) {
  22551. this.version++;
  22552. }
  22553. this._transmission = value;
  22554. }
  22555. copy(source) {
  22556. super.copy(source);
  22557. this.defines = {
  22558. 'STANDARD': '',
  22559. 'PHYSICAL': ''
  22560. };
  22561. this.clearcoat = source.clearcoat;
  22562. this.clearcoatMap = source.clearcoatMap;
  22563. this.clearcoatRoughness = source.clearcoatRoughness;
  22564. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22565. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22566. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  22567. this.ior = source.ior;
  22568. this.iridescence = source.iridescence;
  22569. this.iridescenceMap = source.iridescenceMap;
  22570. this.iridescenceIOR = source.iridescenceIOR;
  22571. this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
  22572. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22573. this.sheen = source.sheen;
  22574. this.sheenColor.copy(source.sheenColor);
  22575. this.sheenColorMap = source.sheenColorMap;
  22576. this.sheenRoughness = source.sheenRoughness;
  22577. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22578. this.transmission = source.transmission;
  22579. this.transmissionMap = source.transmissionMap;
  22580. this.thickness = source.thickness;
  22581. this.thicknessMap = source.thicknessMap;
  22582. this.attenuationDistance = source.attenuationDistance;
  22583. this.attenuationColor.copy(source.attenuationColor);
  22584. this.specularIntensity = source.specularIntensity;
  22585. this.specularIntensityMap = source.specularIntensityMap;
  22586. this.specularColor.copy(source.specularColor);
  22587. this.specularColorMap = source.specularColorMap;
  22588. return this;
  22589. }
  22590. }
  22591. class MeshPhongMaterial extends Material {
  22592. constructor(parameters) {
  22593. super();
  22594. this.isMeshPhongMaterial = true;
  22595. this.type = 'MeshPhongMaterial';
  22596. this.color = new Color(0xffffff); // diffuse
  22597. this.specular = new Color(0x111111);
  22598. this.shininess = 30;
  22599. this.map = null;
  22600. this.lightMap = null;
  22601. this.lightMapIntensity = 1.0;
  22602. this.aoMap = null;
  22603. this.aoMapIntensity = 1.0;
  22604. this.emissive = new Color(0x000000);
  22605. this.emissiveIntensity = 1.0;
  22606. this.emissiveMap = null;
  22607. this.bumpMap = null;
  22608. this.bumpScale = 1;
  22609. this.normalMap = null;
  22610. this.normalMapType = TangentSpaceNormalMap;
  22611. this.normalScale = new Vector2(1, 1);
  22612. this.displacementMap = null;
  22613. this.displacementScale = 1;
  22614. this.displacementBias = 0;
  22615. this.specularMap = null;
  22616. this.alphaMap = null;
  22617. this.envMap = null;
  22618. this.combine = MultiplyOperation;
  22619. this.reflectivity = 1;
  22620. this.refractionRatio = 0.98;
  22621. this.wireframe = false;
  22622. this.wireframeLinewidth = 1;
  22623. this.wireframeLinecap = 'round';
  22624. this.wireframeLinejoin = 'round';
  22625. this.flatShading = false;
  22626. this.fog = true;
  22627. this.setValues(parameters);
  22628. }
  22629. copy(source) {
  22630. super.copy(source);
  22631. this.color.copy(source.color);
  22632. this.specular.copy(source.specular);
  22633. this.shininess = source.shininess;
  22634. this.map = source.map;
  22635. this.lightMap = source.lightMap;
  22636. this.lightMapIntensity = source.lightMapIntensity;
  22637. this.aoMap = source.aoMap;
  22638. this.aoMapIntensity = source.aoMapIntensity;
  22639. this.emissive.copy(source.emissive);
  22640. this.emissiveMap = source.emissiveMap;
  22641. this.emissiveIntensity = source.emissiveIntensity;
  22642. this.bumpMap = source.bumpMap;
  22643. this.bumpScale = source.bumpScale;
  22644. this.normalMap = source.normalMap;
  22645. this.normalMapType = source.normalMapType;
  22646. this.normalScale.copy(source.normalScale);
  22647. this.displacementMap = source.displacementMap;
  22648. this.displacementScale = source.displacementScale;
  22649. this.displacementBias = source.displacementBias;
  22650. this.specularMap = source.specularMap;
  22651. this.alphaMap = source.alphaMap;
  22652. this.envMap = source.envMap;
  22653. this.combine = source.combine;
  22654. this.reflectivity = source.reflectivity;
  22655. this.refractionRatio = source.refractionRatio;
  22656. this.wireframe = source.wireframe;
  22657. this.wireframeLinewidth = source.wireframeLinewidth;
  22658. this.wireframeLinecap = source.wireframeLinecap;
  22659. this.wireframeLinejoin = source.wireframeLinejoin;
  22660. this.flatShading = source.flatShading;
  22661. this.fog = source.fog;
  22662. return this;
  22663. }
  22664. }
  22665. class MeshToonMaterial extends Material {
  22666. constructor(parameters) {
  22667. super();
  22668. this.isMeshToonMaterial = true;
  22669. this.defines = {
  22670. 'TOON': ''
  22671. };
  22672. this.type = 'MeshToonMaterial';
  22673. this.color = new Color(0xffffff);
  22674. this.map = null;
  22675. this.gradientMap = null;
  22676. this.lightMap = null;
  22677. this.lightMapIntensity = 1.0;
  22678. this.aoMap = null;
  22679. this.aoMapIntensity = 1.0;
  22680. this.emissive = new Color(0x000000);
  22681. this.emissiveIntensity = 1.0;
  22682. this.emissiveMap = null;
  22683. this.bumpMap = null;
  22684. this.bumpScale = 1;
  22685. this.normalMap = null;
  22686. this.normalMapType = TangentSpaceNormalMap;
  22687. this.normalScale = new Vector2(1, 1);
  22688. this.displacementMap = null;
  22689. this.displacementScale = 1;
  22690. this.displacementBias = 0;
  22691. this.alphaMap = null;
  22692. this.wireframe = false;
  22693. this.wireframeLinewidth = 1;
  22694. this.wireframeLinecap = 'round';
  22695. this.wireframeLinejoin = 'round';
  22696. this.fog = true;
  22697. this.setValues(parameters);
  22698. }
  22699. copy(source) {
  22700. super.copy(source);
  22701. this.color.copy(source.color);
  22702. this.map = source.map;
  22703. this.gradientMap = source.gradientMap;
  22704. this.lightMap = source.lightMap;
  22705. this.lightMapIntensity = source.lightMapIntensity;
  22706. this.aoMap = source.aoMap;
  22707. this.aoMapIntensity = source.aoMapIntensity;
  22708. this.emissive.copy(source.emissive);
  22709. this.emissiveMap = source.emissiveMap;
  22710. this.emissiveIntensity = source.emissiveIntensity;
  22711. this.bumpMap = source.bumpMap;
  22712. this.bumpScale = source.bumpScale;
  22713. this.normalMap = source.normalMap;
  22714. this.normalMapType = source.normalMapType;
  22715. this.normalScale.copy(source.normalScale);
  22716. this.displacementMap = source.displacementMap;
  22717. this.displacementScale = source.displacementScale;
  22718. this.displacementBias = source.displacementBias;
  22719. this.alphaMap = source.alphaMap;
  22720. this.wireframe = source.wireframe;
  22721. this.wireframeLinewidth = source.wireframeLinewidth;
  22722. this.wireframeLinecap = source.wireframeLinecap;
  22723. this.wireframeLinejoin = source.wireframeLinejoin;
  22724. this.fog = source.fog;
  22725. return this;
  22726. }
  22727. }
  22728. class MeshNormalMaterial extends Material {
  22729. constructor(parameters) {
  22730. super();
  22731. this.isMeshNormalMaterial = true;
  22732. this.type = 'MeshNormalMaterial';
  22733. this.bumpMap = null;
  22734. this.bumpScale = 1;
  22735. this.normalMap = null;
  22736. this.normalMapType = TangentSpaceNormalMap;
  22737. this.normalScale = new Vector2(1, 1);
  22738. this.displacementMap = null;
  22739. this.displacementScale = 1;
  22740. this.displacementBias = 0;
  22741. this.wireframe = false;
  22742. this.wireframeLinewidth = 1;
  22743. this.flatShading = false;
  22744. this.setValues(parameters);
  22745. }
  22746. copy(source) {
  22747. super.copy(source);
  22748. this.bumpMap = source.bumpMap;
  22749. this.bumpScale = source.bumpScale;
  22750. this.normalMap = source.normalMap;
  22751. this.normalMapType = source.normalMapType;
  22752. this.normalScale.copy(source.normalScale);
  22753. this.displacementMap = source.displacementMap;
  22754. this.displacementScale = source.displacementScale;
  22755. this.displacementBias = source.displacementBias;
  22756. this.wireframe = source.wireframe;
  22757. this.wireframeLinewidth = source.wireframeLinewidth;
  22758. this.flatShading = source.flatShading;
  22759. return this;
  22760. }
  22761. }
  22762. class MeshLambertMaterial extends Material {
  22763. constructor(parameters) {
  22764. super();
  22765. this.isMeshLambertMaterial = true;
  22766. this.type = 'MeshLambertMaterial';
  22767. this.color = new Color(0xffffff); // diffuse
  22768. this.map = null;
  22769. this.lightMap = null;
  22770. this.lightMapIntensity = 1.0;
  22771. this.aoMap = null;
  22772. this.aoMapIntensity = 1.0;
  22773. this.emissive = new Color(0x000000);
  22774. this.emissiveIntensity = 1.0;
  22775. this.emissiveMap = null;
  22776. this.bumpMap = null;
  22777. this.bumpScale = 1;
  22778. this.normalMap = null;
  22779. this.normalMapType = TangentSpaceNormalMap;
  22780. this.normalScale = new Vector2(1, 1);
  22781. this.displacementMap = null;
  22782. this.displacementScale = 1;
  22783. this.displacementBias = 0;
  22784. this.specularMap = null;
  22785. this.alphaMap = null;
  22786. this.envMap = null;
  22787. this.combine = MultiplyOperation;
  22788. this.reflectivity = 1;
  22789. this.refractionRatio = 0.98;
  22790. this.wireframe = false;
  22791. this.wireframeLinewidth = 1;
  22792. this.wireframeLinecap = 'round';
  22793. this.wireframeLinejoin = 'round';
  22794. this.flatShading = false;
  22795. this.fog = true;
  22796. this.setValues(parameters);
  22797. }
  22798. copy(source) {
  22799. super.copy(source);
  22800. this.color.copy(source.color);
  22801. this.map = source.map;
  22802. this.lightMap = source.lightMap;
  22803. this.lightMapIntensity = source.lightMapIntensity;
  22804. this.aoMap = source.aoMap;
  22805. this.aoMapIntensity = source.aoMapIntensity;
  22806. this.emissive.copy(source.emissive);
  22807. this.emissiveMap = source.emissiveMap;
  22808. this.emissiveIntensity = source.emissiveIntensity;
  22809. this.bumpMap = source.bumpMap;
  22810. this.bumpScale = source.bumpScale;
  22811. this.normalMap = source.normalMap;
  22812. this.normalMapType = source.normalMapType;
  22813. this.normalScale.copy(source.normalScale);
  22814. this.displacementMap = source.displacementMap;
  22815. this.displacementScale = source.displacementScale;
  22816. this.displacementBias = source.displacementBias;
  22817. this.specularMap = source.specularMap;
  22818. this.alphaMap = source.alphaMap;
  22819. this.envMap = source.envMap;
  22820. this.combine = source.combine;
  22821. this.reflectivity = source.reflectivity;
  22822. this.refractionRatio = source.refractionRatio;
  22823. this.wireframe = source.wireframe;
  22824. this.wireframeLinewidth = source.wireframeLinewidth;
  22825. this.wireframeLinecap = source.wireframeLinecap;
  22826. this.wireframeLinejoin = source.wireframeLinejoin;
  22827. this.flatShading = source.flatShading;
  22828. this.fog = source.fog;
  22829. return this;
  22830. }
  22831. }
  22832. class MeshMatcapMaterial extends Material {
  22833. constructor(parameters) {
  22834. super();
  22835. this.isMeshMatcapMaterial = true;
  22836. this.defines = {
  22837. 'MATCAP': ''
  22838. };
  22839. this.type = 'MeshMatcapMaterial';
  22840. this.color = new Color(0xffffff); // diffuse
  22841. this.matcap = null;
  22842. this.map = null;
  22843. this.bumpMap = null;
  22844. this.bumpScale = 1;
  22845. this.normalMap = null;
  22846. this.normalMapType = TangentSpaceNormalMap;
  22847. this.normalScale = new Vector2(1, 1);
  22848. this.displacementMap = null;
  22849. this.displacementScale = 1;
  22850. this.displacementBias = 0;
  22851. this.alphaMap = null;
  22852. this.flatShading = false;
  22853. this.fog = true;
  22854. this.setValues(parameters);
  22855. }
  22856. copy(source) {
  22857. super.copy(source);
  22858. this.defines = {
  22859. 'MATCAP': ''
  22860. };
  22861. this.color.copy(source.color);
  22862. this.matcap = source.matcap;
  22863. this.map = source.map;
  22864. this.bumpMap = source.bumpMap;
  22865. this.bumpScale = source.bumpScale;
  22866. this.normalMap = source.normalMap;
  22867. this.normalMapType = source.normalMapType;
  22868. this.normalScale.copy(source.normalScale);
  22869. this.displacementMap = source.displacementMap;
  22870. this.displacementScale = source.displacementScale;
  22871. this.displacementBias = source.displacementBias;
  22872. this.alphaMap = source.alphaMap;
  22873. this.flatShading = source.flatShading;
  22874. this.fog = source.fog;
  22875. return this;
  22876. }
  22877. }
  22878. class LineDashedMaterial extends LineBasicMaterial {
  22879. constructor(parameters) {
  22880. super();
  22881. this.isLineDashedMaterial = true;
  22882. this.type = 'LineDashedMaterial';
  22883. this.scale = 1;
  22884. this.dashSize = 3;
  22885. this.gapSize = 1;
  22886. this.setValues(parameters);
  22887. }
  22888. copy(source) {
  22889. super.copy(source);
  22890. this.scale = source.scale;
  22891. this.dashSize = source.dashSize;
  22892. this.gapSize = source.gapSize;
  22893. return this;
  22894. }
  22895. }
  22896. // same as Array.prototype.slice, but also works on typed arrays
  22897. function arraySlice(array, from, to) {
  22898. if (isTypedArray(array)) {
  22899. // in ios9 array.subarray(from, undefined) will return empty array
  22900. // but array.subarray(from) or array.subarray(from, len) is correct
  22901. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  22902. }
  22903. return array.slice(from, to);
  22904. }
  22905. // converts an array to a specific type
  22906. function convertArray(array, type, forceClone) {
  22907. if (!array ||
  22908. // let 'undefined' and 'null' pass
  22909. !forceClone && array.constructor === type) return array;
  22910. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  22911. return new type(array); // create typed array
  22912. }
  22913. return Array.prototype.slice.call(array); // create Array
  22914. }
  22915. function isTypedArray(object) {
  22916. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  22917. }
  22918. // returns an array by which times and values can be sorted
  22919. function getKeyframeOrder(times) {
  22920. function compareTime(i, j) {
  22921. return times[i] - times[j];
  22922. }
  22923. const n = times.length;
  22924. const result = new Array(n);
  22925. for (let i = 0; i !== n; ++i) result[i] = i;
  22926. result.sort(compareTime);
  22927. return result;
  22928. }
  22929. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22930. function sortedArray(values, stride, order) {
  22931. const nValues = values.length;
  22932. const result = new values.constructor(nValues);
  22933. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  22934. const srcOffset = order[i] * stride;
  22935. for (let j = 0; j !== stride; ++j) {
  22936. result[dstOffset++] = values[srcOffset + j];
  22937. }
  22938. }
  22939. return result;
  22940. }
  22941. // function for parsing AOS keyframe formats
  22942. function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  22943. let i = 1,
  22944. key = jsonKeys[0];
  22945. while (key !== undefined && key[valuePropertyName] === undefined) {
  22946. key = jsonKeys[i++];
  22947. }
  22948. if (key === undefined) return; // no data
  22949. let value = key[valuePropertyName];
  22950. if (value === undefined) return; // no data
  22951. if (Array.isArray(value)) {
  22952. do {
  22953. value = key[valuePropertyName];
  22954. if (value !== undefined) {
  22955. times.push(key.time);
  22956. values.push.apply(values, value); // push all elements
  22957. }
  22958. key = jsonKeys[i++];
  22959. } while (key !== undefined);
  22960. } else if (value.toArray !== undefined) {
  22961. // ...assume THREE.Math-ish
  22962. do {
  22963. value = key[valuePropertyName];
  22964. if (value !== undefined) {
  22965. times.push(key.time);
  22966. value.toArray(values, values.length);
  22967. }
  22968. key = jsonKeys[i++];
  22969. } while (key !== undefined);
  22970. } else {
  22971. // otherwise push as-is
  22972. do {
  22973. value = key[valuePropertyName];
  22974. if (value !== undefined) {
  22975. times.push(key.time);
  22976. values.push(value);
  22977. }
  22978. key = jsonKeys[i++];
  22979. } while (key !== undefined);
  22980. }
  22981. }
  22982. function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  22983. const clip = sourceClip.clone();
  22984. clip.name = name;
  22985. const tracks = [];
  22986. for (let i = 0; i < clip.tracks.length; ++i) {
  22987. const track = clip.tracks[i];
  22988. const valueSize = track.getValueSize();
  22989. const times = [];
  22990. const values = [];
  22991. for (let j = 0; j < track.times.length; ++j) {
  22992. const frame = track.times[j] * fps;
  22993. if (frame < startFrame || frame >= endFrame) continue;
  22994. times.push(track.times[j]);
  22995. for (let k = 0; k < valueSize; ++k) {
  22996. values.push(track.values[j * valueSize + k]);
  22997. }
  22998. }
  22999. if (times.length === 0) continue;
  23000. track.times = convertArray(times, track.times.constructor);
  23001. track.values = convertArray(values, track.values.constructor);
  23002. tracks.push(track);
  23003. }
  23004. clip.tracks = tracks;
  23005. // find minimum .times value across all tracks in the trimmed clip
  23006. let minStartTime = Infinity;
  23007. for (let i = 0; i < clip.tracks.length; ++i) {
  23008. if (minStartTime > clip.tracks[i].times[0]) {
  23009. minStartTime = clip.tracks[i].times[0];
  23010. }
  23011. }
  23012. // shift all tracks such that clip begins at t=0
  23013. for (let i = 0; i < clip.tracks.length; ++i) {
  23014. clip.tracks[i].shift(-1 * minStartTime);
  23015. }
  23016. clip.resetDuration();
  23017. return clip;
  23018. }
  23019. function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  23020. if (fps <= 0) fps = 30;
  23021. const numTracks = referenceClip.tracks.length;
  23022. const referenceTime = referenceFrame / fps;
  23023. // Make each track's values relative to the values at the reference frame
  23024. for (let i = 0; i < numTracks; ++i) {
  23025. const referenceTrack = referenceClip.tracks[i];
  23026. const referenceTrackType = referenceTrack.ValueTypeName;
  23027. // Skip this track if it's non-numeric
  23028. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue;
  23029. // Find the track in the target clip whose name and type matches the reference track
  23030. const targetTrack = targetClip.tracks.find(function (track) {
  23031. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  23032. });
  23033. if (targetTrack === undefined) continue;
  23034. let referenceOffset = 0;
  23035. const referenceValueSize = referenceTrack.getValueSize();
  23036. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  23037. referenceOffset = referenceValueSize / 3;
  23038. }
  23039. let targetOffset = 0;
  23040. const targetValueSize = targetTrack.getValueSize();
  23041. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  23042. targetOffset = targetValueSize / 3;
  23043. }
  23044. const lastIndex = referenceTrack.times.length - 1;
  23045. let referenceValue;
  23046. // Find the value to subtract out of the track
  23047. if (referenceTime <= referenceTrack.times[0]) {
  23048. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23049. const startIndex = referenceOffset;
  23050. const endIndex = referenceValueSize - referenceOffset;
  23051. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  23052. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  23053. // Reference frame is after the last keyframe, so just use the last keyframe
  23054. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23055. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23056. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  23057. } else {
  23058. // Interpolate to the reference value
  23059. const interpolant = referenceTrack.createInterpolant();
  23060. const startIndex = referenceOffset;
  23061. const endIndex = referenceValueSize - referenceOffset;
  23062. interpolant.evaluate(referenceTime);
  23063. referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  23064. }
  23065. // Conjugate the quaternion
  23066. if (referenceTrackType === 'quaternion') {
  23067. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  23068. referenceQuat.toArray(referenceValue);
  23069. }
  23070. // Subtract the reference value from all of the track values
  23071. const numTimes = targetTrack.times.length;
  23072. for (let j = 0; j < numTimes; ++j) {
  23073. const valueStart = j * targetValueSize + targetOffset;
  23074. if (referenceTrackType === 'quaternion') {
  23075. // Multiply the conjugate for quaternion track types
  23076. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  23077. } else {
  23078. const valueEnd = targetValueSize - targetOffset * 2;
  23079. // Subtract each value for all other numeric track types
  23080. for (let k = 0; k < valueEnd; ++k) {
  23081. targetTrack.values[valueStart + k] -= referenceValue[k];
  23082. }
  23083. }
  23084. }
  23085. }
  23086. targetClip.blendMode = AdditiveAnimationBlendMode;
  23087. return targetClip;
  23088. }
  23089. var AnimationUtils = /*#__PURE__*/Object.freeze({
  23090. __proto__: null,
  23091. arraySlice: arraySlice,
  23092. convertArray: convertArray,
  23093. isTypedArray: isTypedArray,
  23094. getKeyframeOrder: getKeyframeOrder,
  23095. sortedArray: sortedArray,
  23096. flattenJSON: flattenJSON,
  23097. subclip: subclip,
  23098. makeClipAdditive: makeClipAdditive
  23099. });
  23100. /**
  23101. * Abstract base class of interpolants over parametric samples.
  23102. *
  23103. * The parameter domain is one dimensional, typically the time or a path
  23104. * along a curve defined by the data.
  23105. *
  23106. * The sample values can have any dimensionality and derived classes may
  23107. * apply special interpretations to the data.
  23108. *
  23109. * This class provides the interval seek in a Template Method, deferring
  23110. * the actual interpolation to derived classes.
  23111. *
  23112. * Time complexity is O(1) for linear access crossing at most two points
  23113. * and O(log N) for random access, where N is the number of positions.
  23114. *
  23115. * References:
  23116. *
  23117. * http://www.oodesign.com/template-method-pattern.html
  23118. *
  23119. */
  23120. class Interpolant {
  23121. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23122. this.parameterPositions = parameterPositions;
  23123. this._cachedIndex = 0;
  23124. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  23125. this.sampleValues = sampleValues;
  23126. this.valueSize = sampleSize;
  23127. this.settings = null;
  23128. this.DefaultSettings_ = {};
  23129. }
  23130. evaluate(t) {
  23131. const pp = this.parameterPositions;
  23132. let i1 = this._cachedIndex,
  23133. t1 = pp[i1],
  23134. t0 = pp[i1 - 1];
  23135. validate_interval: {
  23136. seek: {
  23137. let right;
  23138. linear_scan: {
  23139. //- See http://jsperf.com/comparison-to-undefined/3
  23140. //- slower code:
  23141. //-
  23142. //- if ( t >= t1 || t1 === undefined ) {
  23143. forward_scan: if (!(t < t1)) {
  23144. for (let giveUpAt = i1 + 2;;) {
  23145. if (t1 === undefined) {
  23146. if (t < t0) break forward_scan;
  23147. // after end
  23148. i1 = pp.length;
  23149. this._cachedIndex = i1;
  23150. return this.copySampleValue_(i1 - 1);
  23151. }
  23152. if (i1 === giveUpAt) break; // this loop
  23153. t0 = t1;
  23154. t1 = pp[++i1];
  23155. if (t < t1) {
  23156. // we have arrived at the sought interval
  23157. break seek;
  23158. }
  23159. }
  23160. // prepare binary search on the right side of the index
  23161. right = pp.length;
  23162. break linear_scan;
  23163. }
  23164. //- slower code:
  23165. //- if ( t < t0 || t0 === undefined ) {
  23166. if (!(t >= t0)) {
  23167. // looping?
  23168. const t1global = pp[1];
  23169. if (t < t1global) {
  23170. i1 = 2; // + 1, using the scan for the details
  23171. t0 = t1global;
  23172. }
  23173. // linear reverse scan
  23174. for (let giveUpAt = i1 - 2;;) {
  23175. if (t0 === undefined) {
  23176. // before start
  23177. this._cachedIndex = 0;
  23178. return this.copySampleValue_(0);
  23179. }
  23180. if (i1 === giveUpAt) break; // this loop
  23181. t1 = t0;
  23182. t0 = pp[--i1 - 1];
  23183. if (t >= t0) {
  23184. // we have arrived at the sought interval
  23185. break seek;
  23186. }
  23187. }
  23188. // prepare binary search on the left side of the index
  23189. right = i1;
  23190. i1 = 0;
  23191. break linear_scan;
  23192. }
  23193. // the interval is valid
  23194. break validate_interval;
  23195. } // linear scan
  23196. // binary search
  23197. while (i1 < right) {
  23198. const mid = i1 + right >>> 1;
  23199. if (t < pp[mid]) {
  23200. right = mid;
  23201. } else {
  23202. i1 = mid + 1;
  23203. }
  23204. }
  23205. t1 = pp[i1];
  23206. t0 = pp[i1 - 1];
  23207. // check boundary cases, again
  23208. if (t0 === undefined) {
  23209. this._cachedIndex = 0;
  23210. return this.copySampleValue_(0);
  23211. }
  23212. if (t1 === undefined) {
  23213. i1 = pp.length;
  23214. this._cachedIndex = i1;
  23215. return this.copySampleValue_(i1 - 1);
  23216. }
  23217. } // seek
  23218. this._cachedIndex = i1;
  23219. this.intervalChanged_(i1, t0, t1);
  23220. } // validate_interval
  23221. return this.interpolate_(i1, t0, t, t1);
  23222. }
  23223. getSettings_() {
  23224. return this.settings || this.DefaultSettings_;
  23225. }
  23226. copySampleValue_(index) {
  23227. // copies a sample value to the result buffer
  23228. const result = this.resultBuffer,
  23229. values = this.sampleValues,
  23230. stride = this.valueSize,
  23231. offset = index * stride;
  23232. for (let i = 0; i !== stride; ++i) {
  23233. result[i] = values[offset + i];
  23234. }
  23235. return result;
  23236. }
  23237. // Template methods for derived classes:
  23238. interpolate_() {
  23239. throw new Error('call to abstract method');
  23240. // implementations shall return this.resultBuffer
  23241. }
  23242. intervalChanged_() {
  23243. // empty
  23244. }
  23245. }
  23246. /**
  23247. * Fast and simple cubic spline interpolant.
  23248. *
  23249. * It was derived from a Hermitian construction setting the first derivative
  23250. * at each sample position to the linear slope between neighboring positions
  23251. * over their parameter interval.
  23252. */
  23253. class CubicInterpolant extends Interpolant {
  23254. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23255. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23256. this._weightPrev = -0;
  23257. this._offsetPrev = -0;
  23258. this._weightNext = -0;
  23259. this._offsetNext = -0;
  23260. this.DefaultSettings_ = {
  23261. endingStart: ZeroCurvatureEnding,
  23262. endingEnd: ZeroCurvatureEnding
  23263. };
  23264. }
  23265. intervalChanged_(i1, t0, t1) {
  23266. const pp = this.parameterPositions;
  23267. let iPrev = i1 - 2,
  23268. iNext = i1 + 1,
  23269. tPrev = pp[iPrev],
  23270. tNext = pp[iNext];
  23271. if (tPrev === undefined) {
  23272. switch (this.getSettings_().endingStart) {
  23273. case ZeroSlopeEnding:
  23274. // f'(t0) = 0
  23275. iPrev = i1;
  23276. tPrev = 2 * t0 - t1;
  23277. break;
  23278. case WrapAroundEnding:
  23279. // use the other end of the curve
  23280. iPrev = pp.length - 2;
  23281. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  23282. break;
  23283. default:
  23284. // ZeroCurvatureEnding
  23285. // f''(t0) = 0 a.k.a. Natural Spline
  23286. iPrev = i1;
  23287. tPrev = t1;
  23288. }
  23289. }
  23290. if (tNext === undefined) {
  23291. switch (this.getSettings_().endingEnd) {
  23292. case ZeroSlopeEnding:
  23293. // f'(tN) = 0
  23294. iNext = i1;
  23295. tNext = 2 * t1 - t0;
  23296. break;
  23297. case WrapAroundEnding:
  23298. // use the other end of the curve
  23299. iNext = 1;
  23300. tNext = t1 + pp[1] - pp[0];
  23301. break;
  23302. default:
  23303. // ZeroCurvatureEnding
  23304. // f''(tN) = 0, a.k.a. Natural Spline
  23305. iNext = i1 - 1;
  23306. tNext = t0;
  23307. }
  23308. }
  23309. const halfDt = (t1 - t0) * 0.5,
  23310. stride = this.valueSize;
  23311. this._weightPrev = halfDt / (t0 - tPrev);
  23312. this._weightNext = halfDt / (tNext - t1);
  23313. this._offsetPrev = iPrev * stride;
  23314. this._offsetNext = iNext * stride;
  23315. }
  23316. interpolate_(i1, t0, t, t1) {
  23317. const result = this.resultBuffer,
  23318. values = this.sampleValues,
  23319. stride = this.valueSize,
  23320. o1 = i1 * stride,
  23321. o0 = o1 - stride,
  23322. oP = this._offsetPrev,
  23323. oN = this._offsetNext,
  23324. wP = this._weightPrev,
  23325. wN = this._weightNext,
  23326. p = (t - t0) / (t1 - t0),
  23327. pp = p * p,
  23328. ppp = pp * p;
  23329. // evaluate polynomials
  23330. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  23331. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  23332. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  23333. const sN = wN * ppp - wN * pp;
  23334. // combine data linearly
  23335. for (let i = 0; i !== stride; ++i) {
  23336. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  23337. }
  23338. return result;
  23339. }
  23340. }
  23341. class LinearInterpolant extends Interpolant {
  23342. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23343. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23344. }
  23345. interpolate_(i1, t0, t, t1) {
  23346. const result = this.resultBuffer,
  23347. values = this.sampleValues,
  23348. stride = this.valueSize,
  23349. offset1 = i1 * stride,
  23350. offset0 = offset1 - stride,
  23351. weight1 = (t - t0) / (t1 - t0),
  23352. weight0 = 1 - weight1;
  23353. for (let i = 0; i !== stride; ++i) {
  23354. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  23355. }
  23356. return result;
  23357. }
  23358. }
  23359. /**
  23360. *
  23361. * Interpolant that evaluates to the sample value at the position preceding
  23362. * the parameter.
  23363. */
  23364. class DiscreteInterpolant extends Interpolant {
  23365. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23366. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23367. }
  23368. interpolate_(i1 /*, t0, t, t1 */) {
  23369. return this.copySampleValue_(i1 - 1);
  23370. }
  23371. }
  23372. class KeyframeTrack {
  23373. constructor(name, times, values, interpolation) {
  23374. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  23375. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  23376. this.name = name;
  23377. this.times = convertArray(times, this.TimeBufferType);
  23378. this.values = convertArray(values, this.ValueBufferType);
  23379. this.setInterpolation(interpolation || this.DefaultInterpolation);
  23380. }
  23381. // Serialization (in static context, because of constructor invocation
  23382. // and automatic invocation of .toJSON):
  23383. static toJSON(track) {
  23384. const trackType = track.constructor;
  23385. let json;
  23386. // derived classes can define a static toJSON method
  23387. if (trackType.toJSON !== this.toJSON) {
  23388. json = trackType.toJSON(track);
  23389. } else {
  23390. // by default, we assume the data can be serialized as-is
  23391. json = {
  23392. 'name': track.name,
  23393. 'times': convertArray(track.times, Array),
  23394. 'values': convertArray(track.values, Array)
  23395. };
  23396. const interpolation = track.getInterpolation();
  23397. if (interpolation !== track.DefaultInterpolation) {
  23398. json.interpolation = interpolation;
  23399. }
  23400. }
  23401. json.type = track.ValueTypeName; // mandatory
  23402. return json;
  23403. }
  23404. InterpolantFactoryMethodDiscrete(result) {
  23405. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  23406. }
  23407. InterpolantFactoryMethodLinear(result) {
  23408. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  23409. }
  23410. InterpolantFactoryMethodSmooth(result) {
  23411. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  23412. }
  23413. setInterpolation(interpolation) {
  23414. let factoryMethod;
  23415. switch (interpolation) {
  23416. case InterpolateDiscrete:
  23417. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23418. break;
  23419. case InterpolateLinear:
  23420. factoryMethod = this.InterpolantFactoryMethodLinear;
  23421. break;
  23422. case InterpolateSmooth:
  23423. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23424. break;
  23425. }
  23426. if (factoryMethod === undefined) {
  23427. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  23428. if (this.createInterpolant === undefined) {
  23429. // fall back to default, unless the default itself is messed up
  23430. if (interpolation !== this.DefaultInterpolation) {
  23431. this.setInterpolation(this.DefaultInterpolation);
  23432. } else {
  23433. throw new Error(message); // fatal, in this case
  23434. }
  23435. }
  23436. console.warn('THREE.KeyframeTrack:', message);
  23437. return this;
  23438. }
  23439. this.createInterpolant = factoryMethod;
  23440. return this;
  23441. }
  23442. getInterpolation() {
  23443. switch (this.createInterpolant) {
  23444. case this.InterpolantFactoryMethodDiscrete:
  23445. return InterpolateDiscrete;
  23446. case this.InterpolantFactoryMethodLinear:
  23447. return InterpolateLinear;
  23448. case this.InterpolantFactoryMethodSmooth:
  23449. return InterpolateSmooth;
  23450. }
  23451. }
  23452. getValueSize() {
  23453. return this.values.length / this.times.length;
  23454. }
  23455. // move all keyframes either forwards or backwards in time
  23456. shift(timeOffset) {
  23457. if (timeOffset !== 0.0) {
  23458. const times = this.times;
  23459. for (let i = 0, n = times.length; i !== n; ++i) {
  23460. times[i] += timeOffset;
  23461. }
  23462. }
  23463. return this;
  23464. }
  23465. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23466. scale(timeScale) {
  23467. if (timeScale !== 1.0) {
  23468. const times = this.times;
  23469. for (let i = 0, n = times.length; i !== n; ++i) {
  23470. times[i] *= timeScale;
  23471. }
  23472. }
  23473. return this;
  23474. }
  23475. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23476. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23477. trim(startTime, endTime) {
  23478. const times = this.times,
  23479. nKeys = times.length;
  23480. let from = 0,
  23481. to = nKeys - 1;
  23482. while (from !== nKeys && times[from] < startTime) {
  23483. ++from;
  23484. }
  23485. while (to !== -1 && times[to] > endTime) {
  23486. --to;
  23487. }
  23488. ++to; // inclusive -> exclusive bound
  23489. if (from !== 0 || to !== nKeys) {
  23490. // empty tracks are forbidden, so keep at least one keyframe
  23491. if (from >= to) {
  23492. to = Math.max(to, 1);
  23493. from = to - 1;
  23494. }
  23495. const stride = this.getValueSize();
  23496. this.times = arraySlice(times, from, to);
  23497. this.values = arraySlice(this.values, from * stride, to * stride);
  23498. }
  23499. return this;
  23500. }
  23501. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23502. validate() {
  23503. let valid = true;
  23504. const valueSize = this.getValueSize();
  23505. if (valueSize - Math.floor(valueSize) !== 0) {
  23506. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  23507. valid = false;
  23508. }
  23509. const times = this.times,
  23510. values = this.values,
  23511. nKeys = times.length;
  23512. if (nKeys === 0) {
  23513. console.error('THREE.KeyframeTrack: Track is empty.', this);
  23514. valid = false;
  23515. }
  23516. let prevTime = null;
  23517. for (let i = 0; i !== nKeys; i++) {
  23518. const currTime = times[i];
  23519. if (typeof currTime === 'number' && isNaN(currTime)) {
  23520. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  23521. valid = false;
  23522. break;
  23523. }
  23524. if (prevTime !== null && prevTime > currTime) {
  23525. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  23526. valid = false;
  23527. break;
  23528. }
  23529. prevTime = currTime;
  23530. }
  23531. if (values !== undefined) {
  23532. if (isTypedArray(values)) {
  23533. for (let i = 0, n = values.length; i !== n; ++i) {
  23534. const value = values[i];
  23535. if (isNaN(value)) {
  23536. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  23537. valid = false;
  23538. break;
  23539. }
  23540. }
  23541. }
  23542. }
  23543. return valid;
  23544. }
  23545. // removes equivalent sequential keys as common in morph target sequences
  23546. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23547. optimize() {
  23548. // times or values may be shared with other tracks, so overwriting is unsafe
  23549. const times = arraySlice(this.times),
  23550. values = arraySlice(this.values),
  23551. stride = this.getValueSize(),
  23552. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23553. lastIndex = times.length - 1;
  23554. let writeIndex = 1;
  23555. for (let i = 1; i < lastIndex; ++i) {
  23556. let keep = false;
  23557. const time = times[i];
  23558. const timeNext = times[i + 1];
  23559. // remove adjacent keyframes scheduled at the same time
  23560. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  23561. if (!smoothInterpolation) {
  23562. // remove unnecessary keyframes same as their neighbors
  23563. const offset = i * stride,
  23564. offsetP = offset - stride,
  23565. offsetN = offset + stride;
  23566. for (let j = 0; j !== stride; ++j) {
  23567. const value = values[offset + j];
  23568. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  23569. keep = true;
  23570. break;
  23571. }
  23572. }
  23573. } else {
  23574. keep = true;
  23575. }
  23576. }
  23577. // in-place compaction
  23578. if (keep) {
  23579. if (i !== writeIndex) {
  23580. times[writeIndex] = times[i];
  23581. const readOffset = i * stride,
  23582. writeOffset = writeIndex * stride;
  23583. for (let j = 0; j !== stride; ++j) {
  23584. values[writeOffset + j] = values[readOffset + j];
  23585. }
  23586. }
  23587. ++writeIndex;
  23588. }
  23589. }
  23590. // flush last keyframe (compaction looks ahead)
  23591. if (lastIndex > 0) {
  23592. times[writeIndex] = times[lastIndex];
  23593. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  23594. values[writeOffset + j] = values[readOffset + j];
  23595. }
  23596. ++writeIndex;
  23597. }
  23598. if (writeIndex !== times.length) {
  23599. this.times = arraySlice(times, 0, writeIndex);
  23600. this.values = arraySlice(values, 0, writeIndex * stride);
  23601. } else {
  23602. this.times = times;
  23603. this.values = values;
  23604. }
  23605. return this;
  23606. }
  23607. clone() {
  23608. const times = arraySlice(this.times, 0);
  23609. const values = arraySlice(this.values, 0);
  23610. const TypedKeyframeTrack = this.constructor;
  23611. const track = new TypedKeyframeTrack(this.name, times, values);
  23612. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23613. track.createInterpolant = this.createInterpolant;
  23614. return track;
  23615. }
  23616. }
  23617. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23618. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23619. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23620. /**
  23621. * A Track of Boolean keyframe values.
  23622. */
  23623. class BooleanKeyframeTrack extends KeyframeTrack {}
  23624. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23625. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23626. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23627. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23628. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23629. /**
  23630. * A Track of keyframe values that represent color.
  23631. */
  23632. class ColorKeyframeTrack extends KeyframeTrack {}
  23633. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23634. /**
  23635. * A Track of numeric keyframe values.
  23636. */
  23637. class NumberKeyframeTrack extends KeyframeTrack {}
  23638. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23639. /**
  23640. * Spherical linear unit quaternion interpolant.
  23641. */
  23642. class QuaternionLinearInterpolant extends Interpolant {
  23643. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23644. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23645. }
  23646. interpolate_(i1, t0, t, t1) {
  23647. const result = this.resultBuffer,
  23648. values = this.sampleValues,
  23649. stride = this.valueSize,
  23650. alpha = (t - t0) / (t1 - t0);
  23651. let offset = i1 * stride;
  23652. for (let end = offset + stride; offset !== end; offset += 4) {
  23653. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  23654. }
  23655. return result;
  23656. }
  23657. }
  23658. /**
  23659. * A Track of quaternion keyframe values.
  23660. */
  23661. class QuaternionKeyframeTrack extends KeyframeTrack {
  23662. InterpolantFactoryMethodLinear(result) {
  23663. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  23664. }
  23665. }
  23666. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23667. // ValueBufferType is inherited
  23668. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23669. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23670. /**
  23671. * A Track that interpolates Strings
  23672. */
  23673. class StringKeyframeTrack extends KeyframeTrack {}
  23674. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23675. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23676. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23677. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23678. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23679. /**
  23680. * A Track of vectored keyframe values.
  23681. */
  23682. class VectorKeyframeTrack extends KeyframeTrack {}
  23683. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23684. class AnimationClip {
  23685. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  23686. this.name = name;
  23687. this.tracks = tracks;
  23688. this.duration = duration;
  23689. this.blendMode = blendMode;
  23690. this.uuid = generateUUID();
  23691. // this means it should figure out its duration by scanning the tracks
  23692. if (this.duration < 0) {
  23693. this.resetDuration();
  23694. }
  23695. }
  23696. static parse(json) {
  23697. const tracks = [],
  23698. jsonTracks = json.tracks,
  23699. frameTime = 1.0 / (json.fps || 1.0);
  23700. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  23701. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  23702. }
  23703. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  23704. clip.uuid = json.uuid;
  23705. return clip;
  23706. }
  23707. static toJSON(clip) {
  23708. const tracks = [],
  23709. clipTracks = clip.tracks;
  23710. const json = {
  23711. 'name': clip.name,
  23712. 'duration': clip.duration,
  23713. 'tracks': tracks,
  23714. 'uuid': clip.uuid,
  23715. 'blendMode': clip.blendMode
  23716. };
  23717. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  23718. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  23719. }
  23720. return json;
  23721. }
  23722. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  23723. const numMorphTargets = morphTargetSequence.length;
  23724. const tracks = [];
  23725. for (let i = 0; i < numMorphTargets; i++) {
  23726. let times = [];
  23727. let values = [];
  23728. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  23729. values.push(0, 1, 0);
  23730. const order = getKeyframeOrder(times);
  23731. times = sortedArray(times, 1, order);
  23732. values = sortedArray(values, 1, order);
  23733. // if there is a key at the first frame, duplicate it as the
  23734. // last frame as well for perfect loop.
  23735. if (!noLoop && times[0] === 0) {
  23736. times.push(numMorphTargets);
  23737. values.push(values[0]);
  23738. }
  23739. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  23740. }
  23741. return new this(name, -1, tracks);
  23742. }
  23743. static findByName(objectOrClipArray, name) {
  23744. let clipArray = objectOrClipArray;
  23745. if (!Array.isArray(objectOrClipArray)) {
  23746. const o = objectOrClipArray;
  23747. clipArray = o.geometry && o.geometry.animations || o.animations;
  23748. }
  23749. for (let i = 0; i < clipArray.length; i++) {
  23750. if (clipArray[i].name === name) {
  23751. return clipArray[i];
  23752. }
  23753. }
  23754. return null;
  23755. }
  23756. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  23757. const animationToMorphTargets = {};
  23758. // tested with https://regex101.com/ on trick sequences
  23759. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23760. const pattern = /^([\w-]*?)([\d]+)$/;
  23761. // sort morph target names into animation groups based
  23762. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23763. for (let i = 0, il = morphTargets.length; i < il; i++) {
  23764. const morphTarget = morphTargets[i];
  23765. const parts = morphTarget.name.match(pattern);
  23766. if (parts && parts.length > 1) {
  23767. const name = parts[1];
  23768. let animationMorphTargets = animationToMorphTargets[name];
  23769. if (!animationMorphTargets) {
  23770. animationToMorphTargets[name] = animationMorphTargets = [];
  23771. }
  23772. animationMorphTargets.push(morphTarget);
  23773. }
  23774. }
  23775. const clips = [];
  23776. for (const name in animationToMorphTargets) {
  23777. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  23778. }
  23779. return clips;
  23780. }
  23781. // parse the animation.hierarchy format
  23782. static parseAnimation(animation, bones) {
  23783. if (!animation) {
  23784. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  23785. return null;
  23786. }
  23787. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  23788. // only return track if there are actually keys.
  23789. if (animationKeys.length !== 0) {
  23790. const times = [];
  23791. const values = [];
  23792. flattenJSON(animationKeys, times, values, propertyName);
  23793. // empty keys are filtered out, so check again
  23794. if (times.length !== 0) {
  23795. destTracks.push(new trackType(trackName, times, values));
  23796. }
  23797. }
  23798. };
  23799. const tracks = [];
  23800. const clipName = animation.name || 'default';
  23801. const fps = animation.fps || 30;
  23802. const blendMode = animation.blendMode;
  23803. // automatic length determination in AnimationClip.
  23804. let duration = animation.length || -1;
  23805. const hierarchyTracks = animation.hierarchy || [];
  23806. for (let h = 0; h < hierarchyTracks.length; h++) {
  23807. const animationKeys = hierarchyTracks[h].keys;
  23808. // skip empty tracks
  23809. if (!animationKeys || animationKeys.length === 0) continue;
  23810. // process morph targets
  23811. if (animationKeys[0].morphTargets) {
  23812. // figure out all morph targets used in this track
  23813. const morphTargetNames = {};
  23814. let k;
  23815. for (k = 0; k < animationKeys.length; k++) {
  23816. if (animationKeys[k].morphTargets) {
  23817. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  23818. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  23819. }
  23820. }
  23821. }
  23822. // create a track for each morph target with all zero
  23823. // morphTargetInfluences except for the keys in which
  23824. // the morphTarget is named.
  23825. for (const morphTargetName in morphTargetNames) {
  23826. const times = [];
  23827. const values = [];
  23828. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  23829. const animationKey = animationKeys[k];
  23830. times.push(animationKey.time);
  23831. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  23832. }
  23833. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  23834. }
  23835. duration = morphTargetNames.length * fps;
  23836. } else {
  23837. // ...assume skeletal animation
  23838. const boneName = '.bones[' + bones[h].name + ']';
  23839. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  23840. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  23841. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  23842. }
  23843. }
  23844. if (tracks.length === 0) {
  23845. return null;
  23846. }
  23847. const clip = new this(clipName, duration, tracks, blendMode);
  23848. return clip;
  23849. }
  23850. resetDuration() {
  23851. const tracks = this.tracks;
  23852. let duration = 0;
  23853. for (let i = 0, n = tracks.length; i !== n; ++i) {
  23854. const track = this.tracks[i];
  23855. duration = Math.max(duration, track.times[track.times.length - 1]);
  23856. }
  23857. this.duration = duration;
  23858. return this;
  23859. }
  23860. trim() {
  23861. for (let i = 0; i < this.tracks.length; i++) {
  23862. this.tracks[i].trim(0, this.duration);
  23863. }
  23864. return this;
  23865. }
  23866. validate() {
  23867. let valid = true;
  23868. for (let i = 0; i < this.tracks.length; i++) {
  23869. valid = valid && this.tracks[i].validate();
  23870. }
  23871. return valid;
  23872. }
  23873. optimize() {
  23874. for (let i = 0; i < this.tracks.length; i++) {
  23875. this.tracks[i].optimize();
  23876. }
  23877. return this;
  23878. }
  23879. clone() {
  23880. const tracks = [];
  23881. for (let i = 0; i < this.tracks.length; i++) {
  23882. tracks.push(this.tracks[i].clone());
  23883. }
  23884. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  23885. }
  23886. toJSON() {
  23887. return this.constructor.toJSON(this);
  23888. }
  23889. }
  23890. function getTrackTypeForValueTypeName(typeName) {
  23891. switch (typeName.toLowerCase()) {
  23892. case 'scalar':
  23893. case 'double':
  23894. case 'float':
  23895. case 'number':
  23896. case 'integer':
  23897. return NumberKeyframeTrack;
  23898. case 'vector':
  23899. case 'vector2':
  23900. case 'vector3':
  23901. case 'vector4':
  23902. return VectorKeyframeTrack;
  23903. case 'color':
  23904. return ColorKeyframeTrack;
  23905. case 'quaternion':
  23906. return QuaternionKeyframeTrack;
  23907. case 'bool':
  23908. case 'boolean':
  23909. return BooleanKeyframeTrack;
  23910. case 'string':
  23911. return StringKeyframeTrack;
  23912. }
  23913. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  23914. }
  23915. function parseKeyframeTrack(json) {
  23916. if (json.type === undefined) {
  23917. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  23918. }
  23919. const trackType = getTrackTypeForValueTypeName(json.type);
  23920. if (json.times === undefined) {
  23921. const times = [],
  23922. values = [];
  23923. flattenJSON(json.keys, times, values, 'value');
  23924. json.times = times;
  23925. json.values = values;
  23926. }
  23927. // derived classes can define a static parse method
  23928. if (trackType.parse !== undefined) {
  23929. return trackType.parse(json);
  23930. } else {
  23931. // by default, we assume a constructor compatible with the base
  23932. return new trackType(json.name, json.times, json.values, json.interpolation);
  23933. }
  23934. }
  23935. const Cache = {
  23936. enabled: false,
  23937. files: {},
  23938. add: function (key, file) {
  23939. if (this.enabled === false) return;
  23940. // console.log( 'THREE.Cache', 'Adding key:', key );
  23941. this.files[key] = file;
  23942. },
  23943. get: function (key) {
  23944. if (this.enabled === false) return;
  23945. // console.log( 'THREE.Cache', 'Checking key:', key );
  23946. return this.files[key];
  23947. },
  23948. remove: function (key) {
  23949. delete this.files[key];
  23950. },
  23951. clear: function () {
  23952. this.files = {};
  23953. }
  23954. };
  23955. class LoadingManager {
  23956. constructor(onLoad, onProgress, onError) {
  23957. const scope = this;
  23958. let isLoading = false;
  23959. let itemsLoaded = 0;
  23960. let itemsTotal = 0;
  23961. let urlModifier = undefined;
  23962. const handlers = [];
  23963. // Refer to #5689 for the reason why we don't set .onStart
  23964. // in the constructor
  23965. this.onStart = undefined;
  23966. this.onLoad = onLoad;
  23967. this.onProgress = onProgress;
  23968. this.onError = onError;
  23969. this.itemStart = function (url) {
  23970. itemsTotal++;
  23971. if (isLoading === false) {
  23972. if (scope.onStart !== undefined) {
  23973. scope.onStart(url, itemsLoaded, itemsTotal);
  23974. }
  23975. }
  23976. isLoading = true;
  23977. };
  23978. this.itemEnd = function (url) {
  23979. itemsLoaded++;
  23980. if (scope.onProgress !== undefined) {
  23981. scope.onProgress(url, itemsLoaded, itemsTotal);
  23982. }
  23983. if (itemsLoaded === itemsTotal) {
  23984. isLoading = false;
  23985. if (scope.onLoad !== undefined) {
  23986. scope.onLoad();
  23987. }
  23988. }
  23989. };
  23990. this.itemError = function (url) {
  23991. if (scope.onError !== undefined) {
  23992. scope.onError(url);
  23993. }
  23994. };
  23995. this.resolveURL = function (url) {
  23996. if (urlModifier) {
  23997. return urlModifier(url);
  23998. }
  23999. return url;
  24000. };
  24001. this.setURLModifier = function (transform) {
  24002. urlModifier = transform;
  24003. return this;
  24004. };
  24005. this.addHandler = function (regex, loader) {
  24006. handlers.push(regex, loader);
  24007. return this;
  24008. };
  24009. this.removeHandler = function (regex) {
  24010. const index = handlers.indexOf(regex);
  24011. if (index !== -1) {
  24012. handlers.splice(index, 2);
  24013. }
  24014. return this;
  24015. };
  24016. this.getHandler = function (file) {
  24017. for (let i = 0, l = handlers.length; i < l; i += 2) {
  24018. const regex = handlers[i];
  24019. const loader = handlers[i + 1];
  24020. if (regex.global) regex.lastIndex = 0; // see #17920
  24021. if (regex.test(file)) {
  24022. return loader;
  24023. }
  24024. }
  24025. return null;
  24026. };
  24027. }
  24028. }
  24029. const DefaultLoadingManager = /*@__PURE__*/new LoadingManager();
  24030. class Loader {
  24031. constructor(manager) {
  24032. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  24033. this.crossOrigin = 'anonymous';
  24034. this.withCredentials = false;
  24035. this.path = '';
  24036. this.resourcePath = '';
  24037. this.requestHeader = {};
  24038. }
  24039. load() {}
  24040. loadAsync(url, onProgress) {
  24041. const scope = this;
  24042. return new Promise(function (resolve, reject) {
  24043. scope.load(url, resolve, onProgress, reject);
  24044. });
  24045. }
  24046. parse() {}
  24047. setCrossOrigin(crossOrigin) {
  24048. this.crossOrigin = crossOrigin;
  24049. return this;
  24050. }
  24051. setWithCredentials(value) {
  24052. this.withCredentials = value;
  24053. return this;
  24054. }
  24055. setPath(path) {
  24056. this.path = path;
  24057. return this;
  24058. }
  24059. setResourcePath(resourcePath) {
  24060. this.resourcePath = resourcePath;
  24061. return this;
  24062. }
  24063. setRequestHeader(requestHeader) {
  24064. this.requestHeader = requestHeader;
  24065. return this;
  24066. }
  24067. }
  24068. const loading = {};
  24069. class HttpError extends Error {
  24070. constructor(message, response) {
  24071. super(message);
  24072. this.response = response;
  24073. }
  24074. }
  24075. class FileLoader extends Loader {
  24076. constructor(manager) {
  24077. super(manager);
  24078. }
  24079. load(url, onLoad, onProgress, onError) {
  24080. if (url === undefined) url = '';
  24081. if (this.path !== undefined) url = this.path + url;
  24082. url = this.manager.resolveURL(url);
  24083. const cached = Cache.get(url);
  24084. if (cached !== undefined) {
  24085. this.manager.itemStart(url);
  24086. setTimeout(() => {
  24087. if (onLoad) onLoad(cached);
  24088. this.manager.itemEnd(url);
  24089. }, 0);
  24090. return cached;
  24091. }
  24092. // Check if request is duplicate
  24093. if (loading[url] !== undefined) {
  24094. loading[url].push({
  24095. onLoad: onLoad,
  24096. onProgress: onProgress,
  24097. onError: onError
  24098. });
  24099. return;
  24100. }
  24101. // Initialise array for duplicate requests
  24102. loading[url] = [];
  24103. loading[url].push({
  24104. onLoad: onLoad,
  24105. onProgress: onProgress,
  24106. onError: onError
  24107. });
  24108. // create request
  24109. const req = new Request(url, {
  24110. headers: new Headers(this.requestHeader),
  24111. credentials: this.withCredentials ? 'include' : 'same-origin'
  24112. // An abort controller could be added within a future PR
  24113. });
  24114. // record states ( avoid data race )
  24115. const mimeType = this.mimeType;
  24116. const responseType = this.responseType;
  24117. // start the fetch
  24118. fetch(req).then(response => {
  24119. if (response.status === 200 || response.status === 0) {
  24120. // Some browsers return HTTP Status 0 when using non-http protocol
  24121. // e.g. 'file://' or 'data://'. Handle as success.
  24122. if (response.status === 0) {
  24123. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  24124. }
  24125. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24126. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  24127. return response;
  24128. }
  24129. const callbacks = loading[url];
  24130. const reader = response.body.getReader();
  24131. // Nginx needs X-File-Size check
  24132. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24133. const contentLength = response.headers.get('Content-Length') || response.headers.get('X-File-Size');
  24134. const total = contentLength ? parseInt(contentLength) : 0;
  24135. const lengthComputable = total !== 0;
  24136. let loaded = 0;
  24137. // periodically read data into the new stream tracking while download progress
  24138. const stream = new ReadableStream({
  24139. start(controller) {
  24140. readData();
  24141. function readData() {
  24142. reader.read().then(({
  24143. done,
  24144. value
  24145. }) => {
  24146. if (done) {
  24147. controller.close();
  24148. } else {
  24149. loaded += value.byteLength;
  24150. const event = new ProgressEvent('progress', {
  24151. lengthComputable,
  24152. loaded,
  24153. total
  24154. });
  24155. for (let i = 0, il = callbacks.length; i < il; i++) {
  24156. const callback = callbacks[i];
  24157. if (callback.onProgress) callback.onProgress(event);
  24158. }
  24159. controller.enqueue(value);
  24160. readData();
  24161. }
  24162. });
  24163. }
  24164. }
  24165. });
  24166. return new Response(stream);
  24167. } else {
  24168. throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
  24169. }
  24170. }).then(response => {
  24171. switch (responseType) {
  24172. case 'arraybuffer':
  24173. return response.arrayBuffer();
  24174. case 'blob':
  24175. return response.blob();
  24176. case 'document':
  24177. return response.text().then(text => {
  24178. const parser = new DOMParser();
  24179. return parser.parseFromString(text, mimeType);
  24180. });
  24181. case 'json':
  24182. return response.json();
  24183. default:
  24184. if (mimeType === undefined) {
  24185. return response.text();
  24186. } else {
  24187. // sniff encoding
  24188. const re = /charset="?([^;"\s]*)"?/i;
  24189. const exec = re.exec(mimeType);
  24190. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  24191. const decoder = new TextDecoder(label);
  24192. return response.arrayBuffer().then(ab => decoder.decode(ab));
  24193. }
  24194. }
  24195. }).then(data => {
  24196. // Add to cache only on HTTP success, so that we do not cache
  24197. // error response bodies as proper responses to requests.
  24198. Cache.add(url, data);
  24199. const callbacks = loading[url];
  24200. delete loading[url];
  24201. for (let i = 0, il = callbacks.length; i < il; i++) {
  24202. const callback = callbacks[i];
  24203. if (callback.onLoad) callback.onLoad(data);
  24204. }
  24205. }).catch(err => {
  24206. // Abort errors and other errors are handled the same
  24207. const callbacks = loading[url];
  24208. if (callbacks === undefined) {
  24209. // When onLoad was called and url was deleted in `loading`
  24210. this.manager.itemError(url);
  24211. throw err;
  24212. }
  24213. delete loading[url];
  24214. for (let i = 0, il = callbacks.length; i < il; i++) {
  24215. const callback = callbacks[i];
  24216. if (callback.onError) callback.onError(err);
  24217. }
  24218. this.manager.itemError(url);
  24219. }).finally(() => {
  24220. this.manager.itemEnd(url);
  24221. });
  24222. this.manager.itemStart(url);
  24223. }
  24224. setResponseType(value) {
  24225. this.responseType = value;
  24226. return this;
  24227. }
  24228. setMimeType(value) {
  24229. this.mimeType = value;
  24230. return this;
  24231. }
  24232. }
  24233. class AnimationLoader extends Loader {
  24234. constructor(manager) {
  24235. super(manager);
  24236. }
  24237. load(url, onLoad, onProgress, onError) {
  24238. const scope = this;
  24239. const loader = new FileLoader(this.manager);
  24240. loader.setPath(this.path);
  24241. loader.setRequestHeader(this.requestHeader);
  24242. loader.setWithCredentials(this.withCredentials);
  24243. loader.load(url, function (text) {
  24244. try {
  24245. onLoad(scope.parse(JSON.parse(text)));
  24246. } catch (e) {
  24247. if (onError) {
  24248. onError(e);
  24249. } else {
  24250. console.error(e);
  24251. }
  24252. scope.manager.itemError(url);
  24253. }
  24254. }, onProgress, onError);
  24255. }
  24256. parse(json) {
  24257. const animations = [];
  24258. for (let i = 0; i < json.length; i++) {
  24259. const clip = AnimationClip.parse(json[i]);
  24260. animations.push(clip);
  24261. }
  24262. return animations;
  24263. }
  24264. }
  24265. /**
  24266. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24267. *
  24268. * Sub classes have to implement the parse() method which will be used in load().
  24269. */
  24270. class CompressedTextureLoader extends Loader {
  24271. constructor(manager) {
  24272. super(manager);
  24273. }
  24274. load(url, onLoad, onProgress, onError) {
  24275. const scope = this;
  24276. const images = [];
  24277. const texture = new CompressedTexture();
  24278. const loader = new FileLoader(this.manager);
  24279. loader.setPath(this.path);
  24280. loader.setResponseType('arraybuffer');
  24281. loader.setRequestHeader(this.requestHeader);
  24282. loader.setWithCredentials(scope.withCredentials);
  24283. let loaded = 0;
  24284. function loadTexture(i) {
  24285. loader.load(url[i], function (buffer) {
  24286. const texDatas = scope.parse(buffer, true);
  24287. images[i] = {
  24288. width: texDatas.width,
  24289. height: texDatas.height,
  24290. format: texDatas.format,
  24291. mipmaps: texDatas.mipmaps
  24292. };
  24293. loaded += 1;
  24294. if (loaded === 6) {
  24295. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  24296. texture.image = images;
  24297. texture.format = texDatas.format;
  24298. texture.needsUpdate = true;
  24299. if (onLoad) onLoad(texture);
  24300. }
  24301. }, onProgress, onError);
  24302. }
  24303. if (Array.isArray(url)) {
  24304. for (let i = 0, il = url.length; i < il; ++i) {
  24305. loadTexture(i);
  24306. }
  24307. } else {
  24308. // compressed cubemap texture stored in a single DDS file
  24309. loader.load(url, function (buffer) {
  24310. const texDatas = scope.parse(buffer, true);
  24311. if (texDatas.isCubemap) {
  24312. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24313. for (let f = 0; f < faces; f++) {
  24314. images[f] = {
  24315. mipmaps: []
  24316. };
  24317. for (let i = 0; i < texDatas.mipmapCount; i++) {
  24318. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  24319. images[f].format = texDatas.format;
  24320. images[f].width = texDatas.width;
  24321. images[f].height = texDatas.height;
  24322. }
  24323. }
  24324. texture.image = images;
  24325. } else {
  24326. texture.image.width = texDatas.width;
  24327. texture.image.height = texDatas.height;
  24328. texture.mipmaps = texDatas.mipmaps;
  24329. }
  24330. if (texDatas.mipmapCount === 1) {
  24331. texture.minFilter = LinearFilter;
  24332. }
  24333. texture.format = texDatas.format;
  24334. texture.needsUpdate = true;
  24335. if (onLoad) onLoad(texture);
  24336. }, onProgress, onError);
  24337. }
  24338. return texture;
  24339. }
  24340. }
  24341. class ImageLoader extends Loader {
  24342. constructor(manager) {
  24343. super(manager);
  24344. }
  24345. load(url, onLoad, onProgress, onError) {
  24346. if (this.path !== undefined) url = this.path + url;
  24347. url = this.manager.resolveURL(url);
  24348. const scope = this;
  24349. const cached = Cache.get(url);
  24350. if (cached !== undefined) {
  24351. scope.manager.itemStart(url);
  24352. setTimeout(function () {
  24353. if (onLoad) onLoad(cached);
  24354. scope.manager.itemEnd(url);
  24355. }, 0);
  24356. return cached;
  24357. }
  24358. const image = createElementNS('img');
  24359. function onImageLoad() {
  24360. removeEventListeners();
  24361. Cache.add(url, this);
  24362. if (onLoad) onLoad(this);
  24363. scope.manager.itemEnd(url);
  24364. }
  24365. function onImageError(event) {
  24366. removeEventListeners();
  24367. if (onError) onError(event);
  24368. scope.manager.itemError(url);
  24369. scope.manager.itemEnd(url);
  24370. }
  24371. function removeEventListeners() {
  24372. image.removeEventListener('load', onImageLoad, false);
  24373. image.removeEventListener('error', onImageError, false);
  24374. }
  24375. image.addEventListener('load', onImageLoad, false);
  24376. image.addEventListener('error', onImageError, false);
  24377. if (url.slice(0, 5) !== 'data:') {
  24378. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  24379. }
  24380. scope.manager.itemStart(url);
  24381. image.src = url;
  24382. return image;
  24383. }
  24384. }
  24385. class CubeTextureLoader extends Loader {
  24386. constructor(manager) {
  24387. super(manager);
  24388. }
  24389. load(urls, onLoad, onProgress, onError) {
  24390. const texture = new CubeTexture();
  24391. const loader = new ImageLoader(this.manager);
  24392. loader.setCrossOrigin(this.crossOrigin);
  24393. loader.setPath(this.path);
  24394. let loaded = 0;
  24395. function loadTexture(i) {
  24396. loader.load(urls[i], function (image) {
  24397. texture.images[i] = image;
  24398. loaded++;
  24399. if (loaded === 6) {
  24400. texture.needsUpdate = true;
  24401. if (onLoad) onLoad(texture);
  24402. }
  24403. }, undefined, onError);
  24404. }
  24405. for (let i = 0; i < urls.length; ++i) {
  24406. loadTexture(i);
  24407. }
  24408. return texture;
  24409. }
  24410. }
  24411. /**
  24412. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24413. *
  24414. * Sub classes have to implement the parse() method which will be used in load().
  24415. */
  24416. class DataTextureLoader extends Loader {
  24417. constructor(manager) {
  24418. super(manager);
  24419. }
  24420. load(url, onLoad, onProgress, onError) {
  24421. const scope = this;
  24422. const texture = new DataTexture();
  24423. const loader = new FileLoader(this.manager);
  24424. loader.setResponseType('arraybuffer');
  24425. loader.setRequestHeader(this.requestHeader);
  24426. loader.setPath(this.path);
  24427. loader.setWithCredentials(scope.withCredentials);
  24428. loader.load(url, function (buffer) {
  24429. const texData = scope.parse(buffer);
  24430. if (!texData) return;
  24431. if (texData.image !== undefined) {
  24432. texture.image = texData.image;
  24433. } else if (texData.data !== undefined) {
  24434. texture.image.width = texData.width;
  24435. texture.image.height = texData.height;
  24436. texture.image.data = texData.data;
  24437. }
  24438. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24439. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24440. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24441. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24442. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24443. if (texData.encoding !== undefined) {
  24444. texture.encoding = texData.encoding;
  24445. }
  24446. if (texData.flipY !== undefined) {
  24447. texture.flipY = texData.flipY;
  24448. }
  24449. if (texData.format !== undefined) {
  24450. texture.format = texData.format;
  24451. }
  24452. if (texData.type !== undefined) {
  24453. texture.type = texData.type;
  24454. }
  24455. if (texData.mipmaps !== undefined) {
  24456. texture.mipmaps = texData.mipmaps;
  24457. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24458. }
  24459. if (texData.mipmapCount === 1) {
  24460. texture.minFilter = LinearFilter;
  24461. }
  24462. if (texData.generateMipmaps !== undefined) {
  24463. texture.generateMipmaps = texData.generateMipmaps;
  24464. }
  24465. texture.needsUpdate = true;
  24466. if (onLoad) onLoad(texture, texData);
  24467. }, onProgress, onError);
  24468. return texture;
  24469. }
  24470. }
  24471. class TextureLoader extends Loader {
  24472. constructor(manager) {
  24473. super(manager);
  24474. }
  24475. load(url, onLoad, onProgress, onError) {
  24476. const texture = new Texture();
  24477. const loader = new ImageLoader(this.manager);
  24478. loader.setCrossOrigin(this.crossOrigin);
  24479. loader.setPath(this.path);
  24480. loader.load(url, function (image) {
  24481. texture.image = image;
  24482. texture.needsUpdate = true;
  24483. if (onLoad !== undefined) {
  24484. onLoad(texture);
  24485. }
  24486. }, onProgress, onError);
  24487. return texture;
  24488. }
  24489. }
  24490. class Light extends Object3D {
  24491. constructor(color, intensity = 1) {
  24492. super();
  24493. this.isLight = true;
  24494. this.type = 'Light';
  24495. this.color = new Color(color);
  24496. this.intensity = intensity;
  24497. }
  24498. dispose() {
  24499. // Empty here in base class; some subclasses override.
  24500. }
  24501. copy(source, recursive) {
  24502. super.copy(source, recursive);
  24503. this.color.copy(source.color);
  24504. this.intensity = source.intensity;
  24505. return this;
  24506. }
  24507. toJSON(meta) {
  24508. const data = super.toJSON(meta);
  24509. data.object.color = this.color.getHex();
  24510. data.object.intensity = this.intensity;
  24511. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  24512. if (this.distance !== undefined) data.object.distance = this.distance;
  24513. if (this.angle !== undefined) data.object.angle = this.angle;
  24514. if (this.decay !== undefined) data.object.decay = this.decay;
  24515. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  24516. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  24517. return data;
  24518. }
  24519. }
  24520. class HemisphereLight extends Light {
  24521. constructor(skyColor, groundColor, intensity) {
  24522. super(skyColor, intensity);
  24523. this.isHemisphereLight = true;
  24524. this.type = 'HemisphereLight';
  24525. this.position.copy(Object3D.DefaultUp);
  24526. this.updateMatrix();
  24527. this.groundColor = new Color(groundColor);
  24528. }
  24529. copy(source, recursive) {
  24530. super.copy(source, recursive);
  24531. this.groundColor.copy(source.groundColor);
  24532. return this;
  24533. }
  24534. }
  24535. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  24536. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  24537. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  24538. class LightShadow {
  24539. constructor(camera) {
  24540. this.camera = camera;
  24541. this.bias = 0;
  24542. this.normalBias = 0;
  24543. this.radius = 1;
  24544. this.blurSamples = 8;
  24545. this.mapSize = new Vector2(512, 512);
  24546. this.map = null;
  24547. this.mapPass = null;
  24548. this.matrix = new Matrix4();
  24549. this.autoUpdate = true;
  24550. this.needsUpdate = false;
  24551. this._frustum = new Frustum();
  24552. this._frameExtents = new Vector2(1, 1);
  24553. this._viewportCount = 1;
  24554. this._viewports = [new Vector4(0, 0, 1, 1)];
  24555. }
  24556. getViewportCount() {
  24557. return this._viewportCount;
  24558. }
  24559. getFrustum() {
  24560. return this._frustum;
  24561. }
  24562. updateMatrices(light) {
  24563. const shadowCamera = this.camera;
  24564. const shadowMatrix = this.matrix;
  24565. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  24566. shadowCamera.position.copy(_lightPositionWorld$1);
  24567. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  24568. shadowCamera.lookAt(_lookTarget$1);
  24569. shadowCamera.updateMatrixWorld();
  24570. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  24571. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  24572. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  24573. shadowMatrix.multiply(_projScreenMatrix$1);
  24574. }
  24575. getViewport(viewportIndex) {
  24576. return this._viewports[viewportIndex];
  24577. }
  24578. getFrameExtents() {
  24579. return this._frameExtents;
  24580. }
  24581. dispose() {
  24582. if (this.map) {
  24583. this.map.dispose();
  24584. }
  24585. if (this.mapPass) {
  24586. this.mapPass.dispose();
  24587. }
  24588. }
  24589. copy(source) {
  24590. this.camera = source.camera.clone();
  24591. this.bias = source.bias;
  24592. this.radius = source.radius;
  24593. this.mapSize.copy(source.mapSize);
  24594. return this;
  24595. }
  24596. clone() {
  24597. return new this.constructor().copy(this);
  24598. }
  24599. toJSON() {
  24600. const object = {};
  24601. if (this.bias !== 0) object.bias = this.bias;
  24602. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  24603. if (this.radius !== 1) object.radius = this.radius;
  24604. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24605. object.camera = this.camera.toJSON(false).object;
  24606. delete object.camera.matrix;
  24607. return object;
  24608. }
  24609. }
  24610. class SpotLightShadow extends LightShadow {
  24611. constructor() {
  24612. super(new PerspectiveCamera(50, 1, 0.5, 500));
  24613. this.isSpotLightShadow = true;
  24614. this.focus = 1;
  24615. }
  24616. updateMatrices(light) {
  24617. const camera = this.camera;
  24618. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24619. const aspect = this.mapSize.width / this.mapSize.height;
  24620. const far = light.distance || camera.far;
  24621. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24622. camera.fov = fov;
  24623. camera.aspect = aspect;
  24624. camera.far = far;
  24625. camera.updateProjectionMatrix();
  24626. }
  24627. super.updateMatrices(light);
  24628. }
  24629. copy(source) {
  24630. super.copy(source);
  24631. this.focus = source.focus;
  24632. return this;
  24633. }
  24634. }
  24635. class SpotLight extends Light {
  24636. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) {
  24637. super(color, intensity);
  24638. this.isSpotLight = true;
  24639. this.type = 'SpotLight';
  24640. this.position.copy(Object3D.DefaultUp);
  24641. this.updateMatrix();
  24642. this.target = new Object3D();
  24643. this.distance = distance;
  24644. this.angle = angle;
  24645. this.penumbra = penumbra;
  24646. this.decay = decay;
  24647. this.map = null;
  24648. this.shadow = new SpotLightShadow();
  24649. }
  24650. get power() {
  24651. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24652. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24653. return this.intensity * Math.PI;
  24654. }
  24655. set power(power) {
  24656. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24657. this.intensity = power / Math.PI;
  24658. }
  24659. dispose() {
  24660. this.shadow.dispose();
  24661. }
  24662. copy(source, recursive) {
  24663. super.copy(source, recursive);
  24664. this.distance = source.distance;
  24665. this.angle = source.angle;
  24666. this.penumbra = source.penumbra;
  24667. this.decay = source.decay;
  24668. this.target = source.target.clone();
  24669. this.shadow = source.shadow.clone();
  24670. return this;
  24671. }
  24672. }
  24673. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  24674. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  24675. const _lookTarget = /*@__PURE__*/new Vector3();
  24676. class PointLightShadow extends LightShadow {
  24677. constructor() {
  24678. super(new PerspectiveCamera(90, 1, 0.5, 500));
  24679. this.isPointLightShadow = true;
  24680. this._frameExtents = new Vector2(4, 2);
  24681. this._viewportCount = 6;
  24682. this._viewports = [
  24683. // These viewports map a cube-map onto a 2D texture with the
  24684. // following orientation:
  24685. //
  24686. // xzXZ
  24687. // y Y
  24688. //
  24689. // X - Positive x direction
  24690. // x - Negative x direction
  24691. // Y - Positive y direction
  24692. // y - Negative y direction
  24693. // Z - Positive z direction
  24694. // z - Negative z direction
  24695. // positive X
  24696. new Vector4(2, 1, 1, 1),
  24697. // negative X
  24698. new Vector4(0, 1, 1, 1),
  24699. // positive Z
  24700. new Vector4(3, 1, 1, 1),
  24701. // negative Z
  24702. new Vector4(1, 1, 1, 1),
  24703. // positive Y
  24704. new Vector4(3, 0, 1, 1),
  24705. // negative Y
  24706. new Vector4(1, 0, 1, 1)];
  24707. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  24708. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  24709. }
  24710. updateMatrices(light, viewportIndex = 0) {
  24711. const camera = this.camera;
  24712. const shadowMatrix = this.matrix;
  24713. const far = light.distance || camera.far;
  24714. if (far !== camera.far) {
  24715. camera.far = far;
  24716. camera.updateProjectionMatrix();
  24717. }
  24718. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24719. camera.position.copy(_lightPositionWorld);
  24720. _lookTarget.copy(camera.position);
  24721. _lookTarget.add(this._cubeDirections[viewportIndex]);
  24722. camera.up.copy(this._cubeUps[viewportIndex]);
  24723. camera.lookAt(_lookTarget);
  24724. camera.updateMatrixWorld();
  24725. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  24726. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24727. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  24728. }
  24729. }
  24730. class PointLight extends Light {
  24731. constructor(color, intensity, distance = 0, decay = 2) {
  24732. super(color, intensity);
  24733. this.isPointLight = true;
  24734. this.type = 'PointLight';
  24735. this.distance = distance;
  24736. this.decay = decay;
  24737. this.shadow = new PointLightShadow();
  24738. }
  24739. get power() {
  24740. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24741. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24742. return this.intensity * 4 * Math.PI;
  24743. }
  24744. set power(power) {
  24745. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24746. this.intensity = power / (4 * Math.PI);
  24747. }
  24748. dispose() {
  24749. this.shadow.dispose();
  24750. }
  24751. copy(source, recursive) {
  24752. super.copy(source, recursive);
  24753. this.distance = source.distance;
  24754. this.decay = source.decay;
  24755. this.shadow = source.shadow.clone();
  24756. return this;
  24757. }
  24758. }
  24759. class DirectionalLightShadow extends LightShadow {
  24760. constructor() {
  24761. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24762. this.isDirectionalLightShadow = true;
  24763. }
  24764. }
  24765. class DirectionalLight extends Light {
  24766. constructor(color, intensity) {
  24767. super(color, intensity);
  24768. this.isDirectionalLight = true;
  24769. this.type = 'DirectionalLight';
  24770. this.position.copy(Object3D.DefaultUp);
  24771. this.updateMatrix();
  24772. this.target = new Object3D();
  24773. this.shadow = new DirectionalLightShadow();
  24774. }
  24775. dispose() {
  24776. this.shadow.dispose();
  24777. }
  24778. copy(source) {
  24779. super.copy(source);
  24780. this.target = source.target.clone();
  24781. this.shadow = source.shadow.clone();
  24782. return this;
  24783. }
  24784. }
  24785. class AmbientLight extends Light {
  24786. constructor(color, intensity) {
  24787. super(color, intensity);
  24788. this.isAmbientLight = true;
  24789. this.type = 'AmbientLight';
  24790. }
  24791. }
  24792. class RectAreaLight extends Light {
  24793. constructor(color, intensity, width = 10, height = 10) {
  24794. super(color, intensity);
  24795. this.isRectAreaLight = true;
  24796. this.type = 'RectAreaLight';
  24797. this.width = width;
  24798. this.height = height;
  24799. }
  24800. get power() {
  24801. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24802. return this.intensity * this.width * this.height * Math.PI;
  24803. }
  24804. set power(power) {
  24805. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24806. this.intensity = power / (this.width * this.height * Math.PI);
  24807. }
  24808. copy(source) {
  24809. super.copy(source);
  24810. this.width = source.width;
  24811. this.height = source.height;
  24812. return this;
  24813. }
  24814. toJSON(meta) {
  24815. const data = super.toJSON(meta);
  24816. data.object.width = this.width;
  24817. data.object.height = this.height;
  24818. return data;
  24819. }
  24820. }
  24821. /**
  24822. * Primary reference:
  24823. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24824. *
  24825. * Secondary reference:
  24826. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24827. */
  24828. // 3-band SH defined by 9 coefficients
  24829. class SphericalHarmonics3 {
  24830. constructor() {
  24831. this.isSphericalHarmonics3 = true;
  24832. this.coefficients = [];
  24833. for (let i = 0; i < 9; i++) {
  24834. this.coefficients.push(new Vector3());
  24835. }
  24836. }
  24837. set(coefficients) {
  24838. for (let i = 0; i < 9; i++) {
  24839. this.coefficients[i].copy(coefficients[i]);
  24840. }
  24841. return this;
  24842. }
  24843. zero() {
  24844. for (let i = 0; i < 9; i++) {
  24845. this.coefficients[i].set(0, 0, 0);
  24846. }
  24847. return this;
  24848. }
  24849. // get the radiance in the direction of the normal
  24850. // target is a Vector3
  24851. getAt(normal, target) {
  24852. // normal is assumed to be unit length
  24853. const x = normal.x,
  24854. y = normal.y,
  24855. z = normal.z;
  24856. const coeff = this.coefficients;
  24857. // band 0
  24858. target.copy(coeff[0]).multiplyScalar(0.282095);
  24859. // band 1
  24860. target.addScaledVector(coeff[1], 0.488603 * y);
  24861. target.addScaledVector(coeff[2], 0.488603 * z);
  24862. target.addScaledVector(coeff[3], 0.488603 * x);
  24863. // band 2
  24864. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24865. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24866. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24867. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24868. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24869. return target;
  24870. }
  24871. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24872. // target is a Vector3
  24873. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24874. getIrradianceAt(normal, target) {
  24875. // normal is assumed to be unit length
  24876. const x = normal.x,
  24877. y = normal.y,
  24878. z = normal.z;
  24879. const coeff = this.coefficients;
  24880. // band 0
  24881. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24882. // band 1
  24883. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24884. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24885. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x);
  24886. // band 2
  24887. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24888. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24889. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24890. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24891. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24892. return target;
  24893. }
  24894. add(sh) {
  24895. for (let i = 0; i < 9; i++) {
  24896. this.coefficients[i].add(sh.coefficients[i]);
  24897. }
  24898. return this;
  24899. }
  24900. addScaledSH(sh, s) {
  24901. for (let i = 0; i < 9; i++) {
  24902. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24903. }
  24904. return this;
  24905. }
  24906. scale(s) {
  24907. for (let i = 0; i < 9; i++) {
  24908. this.coefficients[i].multiplyScalar(s);
  24909. }
  24910. return this;
  24911. }
  24912. lerp(sh, alpha) {
  24913. for (let i = 0; i < 9; i++) {
  24914. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24915. }
  24916. return this;
  24917. }
  24918. equals(sh) {
  24919. for (let i = 0; i < 9; i++) {
  24920. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24921. return false;
  24922. }
  24923. }
  24924. return true;
  24925. }
  24926. copy(sh) {
  24927. return this.set(sh.coefficients);
  24928. }
  24929. clone() {
  24930. return new this.constructor().copy(this);
  24931. }
  24932. fromArray(array, offset = 0) {
  24933. const coefficients = this.coefficients;
  24934. for (let i = 0; i < 9; i++) {
  24935. coefficients[i].fromArray(array, offset + i * 3);
  24936. }
  24937. return this;
  24938. }
  24939. toArray(array = [], offset = 0) {
  24940. const coefficients = this.coefficients;
  24941. for (let i = 0; i < 9; i++) {
  24942. coefficients[i].toArray(array, offset + i * 3);
  24943. }
  24944. return array;
  24945. }
  24946. // evaluate the basis functions
  24947. // shBasis is an Array[ 9 ]
  24948. static getBasisAt(normal, shBasis) {
  24949. // normal is assumed to be unit length
  24950. const x = normal.x,
  24951. y = normal.y,
  24952. z = normal.z;
  24953. // band 0
  24954. shBasis[0] = 0.282095;
  24955. // band 1
  24956. shBasis[1] = 0.488603 * y;
  24957. shBasis[2] = 0.488603 * z;
  24958. shBasis[3] = 0.488603 * x;
  24959. // band 2
  24960. shBasis[4] = 1.092548 * x * y;
  24961. shBasis[5] = 1.092548 * y * z;
  24962. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24963. shBasis[7] = 1.092548 * x * z;
  24964. shBasis[8] = 0.546274 * (x * x - y * y);
  24965. }
  24966. }
  24967. class LightProbe extends Light {
  24968. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  24969. super(undefined, intensity);
  24970. this.isLightProbe = true;
  24971. this.sh = sh;
  24972. }
  24973. copy(source) {
  24974. super.copy(source);
  24975. this.sh.copy(source.sh);
  24976. return this;
  24977. }
  24978. fromJSON(json) {
  24979. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24980. this.sh.fromArray(json.sh);
  24981. return this;
  24982. }
  24983. toJSON(meta) {
  24984. const data = super.toJSON(meta);
  24985. data.object.sh = this.sh.toArray();
  24986. return data;
  24987. }
  24988. }
  24989. class MaterialLoader extends Loader {
  24990. constructor(manager) {
  24991. super(manager);
  24992. this.textures = {};
  24993. }
  24994. load(url, onLoad, onProgress, onError) {
  24995. const scope = this;
  24996. const loader = new FileLoader(scope.manager);
  24997. loader.setPath(scope.path);
  24998. loader.setRequestHeader(scope.requestHeader);
  24999. loader.setWithCredentials(scope.withCredentials);
  25000. loader.load(url, function (text) {
  25001. try {
  25002. onLoad(scope.parse(JSON.parse(text)));
  25003. } catch (e) {
  25004. if (onError) {
  25005. onError(e);
  25006. } else {
  25007. console.error(e);
  25008. }
  25009. scope.manager.itemError(url);
  25010. }
  25011. }, onProgress, onError);
  25012. }
  25013. parse(json) {
  25014. const textures = this.textures;
  25015. function getTexture(name) {
  25016. if (textures[name] === undefined) {
  25017. console.warn('THREE.MaterialLoader: Undefined texture', name);
  25018. }
  25019. return textures[name];
  25020. }
  25021. const material = MaterialLoader.createMaterialFromType(json.type);
  25022. if (json.uuid !== undefined) material.uuid = json.uuid;
  25023. if (json.name !== undefined) material.name = json.name;
  25024. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  25025. if (json.roughness !== undefined) material.roughness = json.roughness;
  25026. if (json.metalness !== undefined) material.metalness = json.metalness;
  25027. if (json.sheen !== undefined) material.sheen = json.sheen;
  25028. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  25029. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  25030. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  25031. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  25032. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  25033. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  25034. if (json.shininess !== undefined) material.shininess = json.shininess;
  25035. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  25036. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  25037. if (json.iridescence !== undefined) material.iridescence = json.iridescence;
  25038. if (json.iridescenceIOR !== undefined) material.iridescenceIOR = json.iridescenceIOR;
  25039. if (json.iridescenceThicknessRange !== undefined) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25040. if (json.transmission !== undefined) material.transmission = json.transmission;
  25041. if (json.thickness !== undefined) material.thickness = json.thickness;
  25042. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  25043. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  25044. if (json.fog !== undefined) material.fog = json.fog;
  25045. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  25046. if (json.blending !== undefined) material.blending = json.blending;
  25047. if (json.combine !== undefined) material.combine = json.combine;
  25048. if (json.side !== undefined) material.side = json.side;
  25049. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  25050. if (json.opacity !== undefined) material.opacity = json.opacity;
  25051. if (json.transparent !== undefined) material.transparent = json.transparent;
  25052. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  25053. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  25054. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  25055. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  25056. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  25057. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  25058. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  25059. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  25060. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  25061. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  25062. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  25063. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  25064. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  25065. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  25066. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  25067. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  25068. if (json.rotation !== undefined) material.rotation = json.rotation;
  25069. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  25070. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  25071. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  25072. if (json.scale !== undefined) material.scale = json.scale;
  25073. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  25074. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25075. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25076. if (json.dithering !== undefined) material.dithering = json.dithering;
  25077. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  25078. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  25079. if (json.visible !== undefined) material.visible = json.visible;
  25080. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  25081. if (json.userData !== undefined) material.userData = json.userData;
  25082. if (json.vertexColors !== undefined) {
  25083. if (typeof json.vertexColors === 'number') {
  25084. material.vertexColors = json.vertexColors > 0 ? true : false;
  25085. } else {
  25086. material.vertexColors = json.vertexColors;
  25087. }
  25088. }
  25089. // Shader Material
  25090. if (json.uniforms !== undefined) {
  25091. for (const name in json.uniforms) {
  25092. const uniform = json.uniforms[name];
  25093. material.uniforms[name] = {};
  25094. switch (uniform.type) {
  25095. case 't':
  25096. material.uniforms[name].value = getTexture(uniform.value);
  25097. break;
  25098. case 'c':
  25099. material.uniforms[name].value = new Color().setHex(uniform.value);
  25100. break;
  25101. case 'v2':
  25102. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  25103. break;
  25104. case 'v3':
  25105. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  25106. break;
  25107. case 'v4':
  25108. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  25109. break;
  25110. case 'm3':
  25111. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  25112. break;
  25113. case 'm4':
  25114. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  25115. break;
  25116. default:
  25117. material.uniforms[name].value = uniform.value;
  25118. }
  25119. }
  25120. }
  25121. if (json.defines !== undefined) material.defines = json.defines;
  25122. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  25123. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  25124. if (json.glslVersion !== undefined) material.glslVersion = json.glslVersion;
  25125. if (json.extensions !== undefined) {
  25126. for (const key in json.extensions) {
  25127. material.extensions[key] = json.extensions[key];
  25128. }
  25129. }
  25130. // for PointsMaterial
  25131. if (json.size !== undefined) material.size = json.size;
  25132. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation;
  25133. // maps
  25134. if (json.map !== undefined) material.map = getTexture(json.map);
  25135. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  25136. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  25137. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  25138. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  25139. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  25140. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  25141. if (json.normalScale !== undefined) {
  25142. let normalScale = json.normalScale;
  25143. if (Array.isArray(normalScale) === false) {
  25144. // Blender exporter used to export a scalar. See #7459
  25145. normalScale = [normalScale, normalScale];
  25146. }
  25147. material.normalScale = new Vector2().fromArray(normalScale);
  25148. }
  25149. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  25150. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  25151. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  25152. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  25153. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  25154. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  25155. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  25156. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  25157. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  25158. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  25159. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  25160. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  25161. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  25162. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  25163. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  25164. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  25165. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  25166. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  25167. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  25168. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  25169. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  25170. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  25171. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  25172. if (json.iridescenceMap !== undefined) material.iridescenceMap = getTexture(json.iridescenceMap);
  25173. if (json.iridescenceThicknessMap !== undefined) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap);
  25174. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  25175. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  25176. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  25177. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  25178. return material;
  25179. }
  25180. setTextures(value) {
  25181. this.textures = value;
  25182. return this;
  25183. }
  25184. static createMaterialFromType(type) {
  25185. const materialLib = {
  25186. ShadowMaterial,
  25187. SpriteMaterial,
  25188. RawShaderMaterial,
  25189. ShaderMaterial,
  25190. PointsMaterial,
  25191. MeshPhysicalMaterial,
  25192. MeshStandardMaterial,
  25193. MeshPhongMaterial,
  25194. MeshToonMaterial,
  25195. MeshNormalMaterial,
  25196. MeshLambertMaterial,
  25197. MeshDepthMaterial,
  25198. MeshDistanceMaterial,
  25199. MeshBasicMaterial,
  25200. MeshMatcapMaterial,
  25201. LineDashedMaterial,
  25202. LineBasicMaterial,
  25203. Material
  25204. };
  25205. return new materialLib[type]();
  25206. }
  25207. }
  25208. class LoaderUtils {
  25209. static decodeText(array) {
  25210. if (typeof TextDecoder !== 'undefined') {
  25211. return new TextDecoder().decode(array);
  25212. }
  25213. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25214. // throws a "maximum call stack size exceeded" error for large arrays.
  25215. let s = '';
  25216. for (let i = 0, il = array.length; i < il; i++) {
  25217. // Implicitly assumes little-endian.
  25218. s += String.fromCharCode(array[i]);
  25219. }
  25220. try {
  25221. // merges multi-byte utf-8 characters.
  25222. return decodeURIComponent(escape(s));
  25223. } catch (e) {
  25224. // see #16358
  25225. return s;
  25226. }
  25227. }
  25228. static extractUrlBase(url) {
  25229. const index = url.lastIndexOf('/');
  25230. if (index === -1) return './';
  25231. return url.slice(0, index + 1);
  25232. }
  25233. static resolveURL(url, path) {
  25234. // Invalid URL
  25235. if (typeof url !== 'string' || url === '') return '';
  25236. // Host Relative URL
  25237. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  25238. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  25239. }
  25240. // Absolute URL http://,https://,//
  25241. if (/^(https?:)?\/\//i.test(url)) return url;
  25242. // Data URI
  25243. if (/^data:.*,.*$/i.test(url)) return url;
  25244. // Blob URL
  25245. if (/^blob:.*$/i.test(url)) return url;
  25246. // Relative URL
  25247. return path + url;
  25248. }
  25249. }
  25250. class InstancedBufferGeometry extends BufferGeometry {
  25251. constructor() {
  25252. super();
  25253. this.isInstancedBufferGeometry = true;
  25254. this.type = 'InstancedBufferGeometry';
  25255. this.instanceCount = Infinity;
  25256. }
  25257. copy(source) {
  25258. super.copy(source);
  25259. this.instanceCount = source.instanceCount;
  25260. return this;
  25261. }
  25262. toJSON() {
  25263. const data = super.toJSON();
  25264. data.instanceCount = this.instanceCount;
  25265. data.isInstancedBufferGeometry = true;
  25266. return data;
  25267. }
  25268. }
  25269. class BufferGeometryLoader extends Loader {
  25270. constructor(manager) {
  25271. super(manager);
  25272. }
  25273. load(url, onLoad, onProgress, onError) {
  25274. const scope = this;
  25275. const loader = new FileLoader(scope.manager);
  25276. loader.setPath(scope.path);
  25277. loader.setRequestHeader(scope.requestHeader);
  25278. loader.setWithCredentials(scope.withCredentials);
  25279. loader.load(url, function (text) {
  25280. try {
  25281. onLoad(scope.parse(JSON.parse(text)));
  25282. } catch (e) {
  25283. if (onError) {
  25284. onError(e);
  25285. } else {
  25286. console.error(e);
  25287. }
  25288. scope.manager.itemError(url);
  25289. }
  25290. }, onProgress, onError);
  25291. }
  25292. parse(json) {
  25293. const interleavedBufferMap = {};
  25294. const arrayBufferMap = {};
  25295. function getInterleavedBuffer(json, uuid) {
  25296. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  25297. const interleavedBuffers = json.interleavedBuffers;
  25298. const interleavedBuffer = interleavedBuffers[uuid];
  25299. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  25300. const array = getTypedArray(interleavedBuffer.type, buffer);
  25301. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  25302. ib.uuid = interleavedBuffer.uuid;
  25303. interleavedBufferMap[uuid] = ib;
  25304. return ib;
  25305. }
  25306. function getArrayBuffer(json, uuid) {
  25307. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  25308. const arrayBuffers = json.arrayBuffers;
  25309. const arrayBuffer = arrayBuffers[uuid];
  25310. const ab = new Uint32Array(arrayBuffer).buffer;
  25311. arrayBufferMap[uuid] = ab;
  25312. return ab;
  25313. }
  25314. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25315. const index = json.data.index;
  25316. if (index !== undefined) {
  25317. const typedArray = getTypedArray(index.type, index.array);
  25318. geometry.setIndex(new BufferAttribute(typedArray, 1));
  25319. }
  25320. const attributes = json.data.attributes;
  25321. for (const key in attributes) {
  25322. const attribute = attributes[key];
  25323. let bufferAttribute;
  25324. if (attribute.isInterleavedBufferAttribute) {
  25325. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  25326. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  25327. } else {
  25328. const typedArray = getTypedArray(attribute.type, attribute.array);
  25329. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25330. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  25331. }
  25332. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  25333. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  25334. if (attribute.updateRange !== undefined) {
  25335. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25336. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25337. }
  25338. geometry.setAttribute(key, bufferAttribute);
  25339. }
  25340. const morphAttributes = json.data.morphAttributes;
  25341. if (morphAttributes) {
  25342. for (const key in morphAttributes) {
  25343. const attributeArray = morphAttributes[key];
  25344. const array = [];
  25345. for (let i = 0, il = attributeArray.length; i < il; i++) {
  25346. const attribute = attributeArray[i];
  25347. let bufferAttribute;
  25348. if (attribute.isInterleavedBufferAttribute) {
  25349. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  25350. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  25351. } else {
  25352. const typedArray = getTypedArray(attribute.type, attribute.array);
  25353. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  25354. }
  25355. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  25356. array.push(bufferAttribute);
  25357. }
  25358. geometry.morphAttributes[key] = array;
  25359. }
  25360. }
  25361. const morphTargetsRelative = json.data.morphTargetsRelative;
  25362. if (morphTargetsRelative) {
  25363. geometry.morphTargetsRelative = true;
  25364. }
  25365. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25366. if (groups !== undefined) {
  25367. for (let i = 0, n = groups.length; i !== n; ++i) {
  25368. const group = groups[i];
  25369. geometry.addGroup(group.start, group.count, group.materialIndex);
  25370. }
  25371. }
  25372. const boundingSphere = json.data.boundingSphere;
  25373. if (boundingSphere !== undefined) {
  25374. const center = new Vector3();
  25375. if (boundingSphere.center !== undefined) {
  25376. center.fromArray(boundingSphere.center);
  25377. }
  25378. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  25379. }
  25380. if (json.name) geometry.name = json.name;
  25381. if (json.userData) geometry.userData = json.userData;
  25382. return geometry;
  25383. }
  25384. }
  25385. class ObjectLoader extends Loader {
  25386. constructor(manager) {
  25387. super(manager);
  25388. }
  25389. load(url, onLoad, onProgress, onError) {
  25390. const scope = this;
  25391. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  25392. this.resourcePath = this.resourcePath || path;
  25393. const loader = new FileLoader(this.manager);
  25394. loader.setPath(this.path);
  25395. loader.setRequestHeader(this.requestHeader);
  25396. loader.setWithCredentials(this.withCredentials);
  25397. loader.load(url, function (text) {
  25398. let json = null;
  25399. try {
  25400. json = JSON.parse(text);
  25401. } catch (error) {
  25402. if (onError !== undefined) onError(error);
  25403. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  25404. return;
  25405. }
  25406. const metadata = json.metadata;
  25407. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  25408. if (onError !== undefined) onError(new Error('THREE.ObjectLoader: Can\'t load ' + url));
  25409. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  25410. return;
  25411. }
  25412. scope.parse(json, onLoad);
  25413. }, onProgress, onError);
  25414. }
  25415. async loadAsync(url, onProgress) {
  25416. const scope = this;
  25417. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  25418. this.resourcePath = this.resourcePath || path;
  25419. const loader = new FileLoader(this.manager);
  25420. loader.setPath(this.path);
  25421. loader.setRequestHeader(this.requestHeader);
  25422. loader.setWithCredentials(this.withCredentials);
  25423. const text = await loader.loadAsync(url, onProgress);
  25424. const json = JSON.parse(text);
  25425. const metadata = json.metadata;
  25426. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  25427. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  25428. }
  25429. return await scope.parseAsync(json);
  25430. }
  25431. parse(json, onLoad) {
  25432. const animations = this.parseAnimations(json.animations);
  25433. const shapes = this.parseShapes(json.shapes);
  25434. const geometries = this.parseGeometries(json.geometries, shapes);
  25435. const images = this.parseImages(json.images, function () {
  25436. if (onLoad !== undefined) onLoad(object);
  25437. });
  25438. const textures = this.parseTextures(json.textures, images);
  25439. const materials = this.parseMaterials(json.materials, textures);
  25440. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  25441. const skeletons = this.parseSkeletons(json.skeletons, object);
  25442. this.bindSkeletons(object, skeletons);
  25443. //
  25444. if (onLoad !== undefined) {
  25445. let hasImages = false;
  25446. for (const uuid in images) {
  25447. if (images[uuid].data instanceof HTMLImageElement) {
  25448. hasImages = true;
  25449. break;
  25450. }
  25451. }
  25452. if (hasImages === false) onLoad(object);
  25453. }
  25454. return object;
  25455. }
  25456. async parseAsync(json) {
  25457. const animations = this.parseAnimations(json.animations);
  25458. const shapes = this.parseShapes(json.shapes);
  25459. const geometries = this.parseGeometries(json.geometries, shapes);
  25460. const images = await this.parseImagesAsync(json.images);
  25461. const textures = this.parseTextures(json.textures, images);
  25462. const materials = this.parseMaterials(json.materials, textures);
  25463. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  25464. const skeletons = this.parseSkeletons(json.skeletons, object);
  25465. this.bindSkeletons(object, skeletons);
  25466. return object;
  25467. }
  25468. parseShapes(json) {
  25469. const shapes = {};
  25470. if (json !== undefined) {
  25471. for (let i = 0, l = json.length; i < l; i++) {
  25472. const shape = new Shape().fromJSON(json[i]);
  25473. shapes[shape.uuid] = shape;
  25474. }
  25475. }
  25476. return shapes;
  25477. }
  25478. parseSkeletons(json, object) {
  25479. const skeletons = {};
  25480. const bones = {};
  25481. // generate bone lookup table
  25482. object.traverse(function (child) {
  25483. if (child.isBone) bones[child.uuid] = child;
  25484. });
  25485. // create skeletons
  25486. if (json !== undefined) {
  25487. for (let i = 0, l = json.length; i < l; i++) {
  25488. const skeleton = new Skeleton().fromJSON(json[i], bones);
  25489. skeletons[skeleton.uuid] = skeleton;
  25490. }
  25491. }
  25492. return skeletons;
  25493. }
  25494. parseGeometries(json, shapes) {
  25495. const geometries = {};
  25496. if (json !== undefined) {
  25497. const bufferGeometryLoader = new BufferGeometryLoader();
  25498. for (let i = 0, l = json.length; i < l; i++) {
  25499. let geometry;
  25500. const data = json[i];
  25501. switch (data.type) {
  25502. case 'BufferGeometry':
  25503. case 'InstancedBufferGeometry':
  25504. geometry = bufferGeometryLoader.parse(data);
  25505. break;
  25506. default:
  25507. if (data.type in Geometries) {
  25508. geometry = Geometries[data.type].fromJSON(data, shapes);
  25509. } else {
  25510. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  25511. }
  25512. }
  25513. geometry.uuid = data.uuid;
  25514. if (data.name !== undefined) geometry.name = data.name;
  25515. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  25516. geometries[data.uuid] = geometry;
  25517. }
  25518. }
  25519. return geometries;
  25520. }
  25521. parseMaterials(json, textures) {
  25522. const cache = {}; // MultiMaterial
  25523. const materials = {};
  25524. if (json !== undefined) {
  25525. const loader = new MaterialLoader();
  25526. loader.setTextures(textures);
  25527. for (let i = 0, l = json.length; i < l; i++) {
  25528. const data = json[i];
  25529. if (cache[data.uuid] === undefined) {
  25530. cache[data.uuid] = loader.parse(data);
  25531. }
  25532. materials[data.uuid] = cache[data.uuid];
  25533. }
  25534. }
  25535. return materials;
  25536. }
  25537. parseAnimations(json) {
  25538. const animations = {};
  25539. if (json !== undefined) {
  25540. for (let i = 0; i < json.length; i++) {
  25541. const data = json[i];
  25542. const clip = AnimationClip.parse(data);
  25543. animations[clip.uuid] = clip;
  25544. }
  25545. }
  25546. return animations;
  25547. }
  25548. parseImages(json, onLoad) {
  25549. const scope = this;
  25550. const images = {};
  25551. let loader;
  25552. function loadImage(url) {
  25553. scope.manager.itemStart(url);
  25554. return loader.load(url, function () {
  25555. scope.manager.itemEnd(url);
  25556. }, undefined, function () {
  25557. scope.manager.itemError(url);
  25558. scope.manager.itemEnd(url);
  25559. });
  25560. }
  25561. function deserializeImage(image) {
  25562. if (typeof image === 'string') {
  25563. const url = image;
  25564. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  25565. return loadImage(path);
  25566. } else {
  25567. if (image.data) {
  25568. return {
  25569. data: getTypedArray(image.type, image.data),
  25570. width: image.width,
  25571. height: image.height
  25572. };
  25573. } else {
  25574. return null;
  25575. }
  25576. }
  25577. }
  25578. if (json !== undefined && json.length > 0) {
  25579. const manager = new LoadingManager(onLoad);
  25580. loader = new ImageLoader(manager);
  25581. loader.setCrossOrigin(this.crossOrigin);
  25582. for (let i = 0, il = json.length; i < il; i++) {
  25583. const image = json[i];
  25584. const url = image.url;
  25585. if (Array.isArray(url)) {
  25586. // load array of images e.g CubeTexture
  25587. const imageArray = [];
  25588. for (let j = 0, jl = url.length; j < jl; j++) {
  25589. const currentUrl = url[j];
  25590. const deserializedImage = deserializeImage(currentUrl);
  25591. if (deserializedImage !== null) {
  25592. if (deserializedImage instanceof HTMLImageElement) {
  25593. imageArray.push(deserializedImage);
  25594. } else {
  25595. // special case: handle array of data textures for cube textures
  25596. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  25597. }
  25598. }
  25599. }
  25600. images[image.uuid] = new Source(imageArray);
  25601. } else {
  25602. // load single image
  25603. const deserializedImage = deserializeImage(image.url);
  25604. images[image.uuid] = new Source(deserializedImage);
  25605. }
  25606. }
  25607. }
  25608. return images;
  25609. }
  25610. async parseImagesAsync(json) {
  25611. const scope = this;
  25612. const images = {};
  25613. let loader;
  25614. async function deserializeImage(image) {
  25615. if (typeof image === 'string') {
  25616. const url = image;
  25617. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  25618. return await loader.loadAsync(path);
  25619. } else {
  25620. if (image.data) {
  25621. return {
  25622. data: getTypedArray(image.type, image.data),
  25623. width: image.width,
  25624. height: image.height
  25625. };
  25626. } else {
  25627. return null;
  25628. }
  25629. }
  25630. }
  25631. if (json !== undefined && json.length > 0) {
  25632. loader = new ImageLoader(this.manager);
  25633. loader.setCrossOrigin(this.crossOrigin);
  25634. for (let i = 0, il = json.length; i < il; i++) {
  25635. const image = json[i];
  25636. const url = image.url;
  25637. if (Array.isArray(url)) {
  25638. // load array of images e.g CubeTexture
  25639. const imageArray = [];
  25640. for (let j = 0, jl = url.length; j < jl; j++) {
  25641. const currentUrl = url[j];
  25642. const deserializedImage = await deserializeImage(currentUrl);
  25643. if (deserializedImage !== null) {
  25644. if (deserializedImage instanceof HTMLImageElement) {
  25645. imageArray.push(deserializedImage);
  25646. } else {
  25647. // special case: handle array of data textures for cube textures
  25648. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  25649. }
  25650. }
  25651. }
  25652. images[image.uuid] = new Source(imageArray);
  25653. } else {
  25654. // load single image
  25655. const deserializedImage = await deserializeImage(image.url);
  25656. images[image.uuid] = new Source(deserializedImage);
  25657. }
  25658. }
  25659. }
  25660. return images;
  25661. }
  25662. parseTextures(json, images) {
  25663. function parseConstant(value, type) {
  25664. if (typeof value === 'number') return value;
  25665. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  25666. return type[value];
  25667. }
  25668. const textures = {};
  25669. if (json !== undefined) {
  25670. for (let i = 0, l = json.length; i < l; i++) {
  25671. const data = json[i];
  25672. if (data.image === undefined) {
  25673. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  25674. }
  25675. if (images[data.image] === undefined) {
  25676. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  25677. }
  25678. const source = images[data.image];
  25679. const image = source.data;
  25680. let texture;
  25681. if (Array.isArray(image)) {
  25682. texture = new CubeTexture();
  25683. if (image.length === 6) texture.needsUpdate = true;
  25684. } else {
  25685. if (image && image.data) {
  25686. texture = new DataTexture();
  25687. } else {
  25688. texture = new Texture();
  25689. }
  25690. if (image) texture.needsUpdate = true; // textures can have undefined image data
  25691. }
  25692. texture.source = source;
  25693. texture.uuid = data.uuid;
  25694. if (data.name !== undefined) texture.name = data.name;
  25695. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  25696. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  25697. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  25698. if (data.center !== undefined) texture.center.fromArray(data.center);
  25699. if (data.rotation !== undefined) texture.rotation = data.rotation;
  25700. if (data.wrap !== undefined) {
  25701. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  25702. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  25703. }
  25704. if (data.format !== undefined) texture.format = data.format;
  25705. if (data.type !== undefined) texture.type = data.type;
  25706. if (data.encoding !== undefined) texture.encoding = data.encoding;
  25707. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  25708. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  25709. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  25710. if (data.flipY !== undefined) texture.flipY = data.flipY;
  25711. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  25712. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  25713. if (data.userData !== undefined) texture.userData = data.userData;
  25714. textures[data.uuid] = texture;
  25715. }
  25716. }
  25717. return textures;
  25718. }
  25719. parseObject(data, geometries, materials, textures, animations) {
  25720. let object;
  25721. function getGeometry(name) {
  25722. if (geometries[name] === undefined) {
  25723. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  25724. }
  25725. return geometries[name];
  25726. }
  25727. function getMaterial(name) {
  25728. if (name === undefined) return undefined;
  25729. if (Array.isArray(name)) {
  25730. const array = [];
  25731. for (let i = 0, l = name.length; i < l; i++) {
  25732. const uuid = name[i];
  25733. if (materials[uuid] === undefined) {
  25734. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  25735. }
  25736. array.push(materials[uuid]);
  25737. }
  25738. return array;
  25739. }
  25740. if (materials[name] === undefined) {
  25741. console.warn('THREE.ObjectLoader: Undefined material', name);
  25742. }
  25743. return materials[name];
  25744. }
  25745. function getTexture(uuid) {
  25746. if (textures[uuid] === undefined) {
  25747. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  25748. }
  25749. return textures[uuid];
  25750. }
  25751. let geometry, material;
  25752. switch (data.type) {
  25753. case 'Scene':
  25754. object = new Scene();
  25755. if (data.background !== undefined) {
  25756. if (Number.isInteger(data.background)) {
  25757. object.background = new Color(data.background);
  25758. } else {
  25759. object.background = getTexture(data.background);
  25760. }
  25761. }
  25762. if (data.environment !== undefined) {
  25763. object.environment = getTexture(data.environment);
  25764. }
  25765. if (data.fog !== undefined) {
  25766. if (data.fog.type === 'Fog') {
  25767. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  25768. } else if (data.fog.type === 'FogExp2') {
  25769. object.fog = new FogExp2(data.fog.color, data.fog.density);
  25770. }
  25771. }
  25772. if (data.backgroundBlurriness !== undefined) object.backgroundBlurriness = data.backgroundBlurriness;
  25773. break;
  25774. case 'PerspectiveCamera':
  25775. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  25776. if (data.focus !== undefined) object.focus = data.focus;
  25777. if (data.zoom !== undefined) object.zoom = data.zoom;
  25778. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  25779. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  25780. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  25781. break;
  25782. case 'OrthographicCamera':
  25783. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  25784. if (data.zoom !== undefined) object.zoom = data.zoom;
  25785. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  25786. break;
  25787. case 'AmbientLight':
  25788. object = new AmbientLight(data.color, data.intensity);
  25789. break;
  25790. case 'DirectionalLight':
  25791. object = new DirectionalLight(data.color, data.intensity);
  25792. break;
  25793. case 'PointLight':
  25794. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25795. break;
  25796. case 'RectAreaLight':
  25797. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25798. break;
  25799. case 'SpotLight':
  25800. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25801. break;
  25802. case 'HemisphereLight':
  25803. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25804. break;
  25805. case 'LightProbe':
  25806. object = new LightProbe().fromJSON(data);
  25807. break;
  25808. case 'SkinnedMesh':
  25809. geometry = getGeometry(data.geometry);
  25810. material = getMaterial(data.material);
  25811. object = new SkinnedMesh(geometry, material);
  25812. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  25813. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  25814. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  25815. break;
  25816. case 'Mesh':
  25817. geometry = getGeometry(data.geometry);
  25818. material = getMaterial(data.material);
  25819. object = new Mesh(geometry, material);
  25820. break;
  25821. case 'InstancedMesh':
  25822. geometry = getGeometry(data.geometry);
  25823. material = getMaterial(data.material);
  25824. const count = data.count;
  25825. const instanceMatrix = data.instanceMatrix;
  25826. const instanceColor = data.instanceColor;
  25827. object = new InstancedMesh(geometry, material, count);
  25828. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  25829. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  25830. break;
  25831. case 'LOD':
  25832. object = new LOD();
  25833. break;
  25834. case 'Line':
  25835. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  25836. break;
  25837. case 'LineLoop':
  25838. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25839. break;
  25840. case 'LineSegments':
  25841. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25842. break;
  25843. case 'PointCloud':
  25844. case 'Points':
  25845. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25846. break;
  25847. case 'Sprite':
  25848. object = new Sprite(getMaterial(data.material));
  25849. break;
  25850. case 'Group':
  25851. object = new Group();
  25852. break;
  25853. case 'Bone':
  25854. object = new Bone();
  25855. break;
  25856. default:
  25857. object = new Object3D();
  25858. }
  25859. object.uuid = data.uuid;
  25860. if (data.name !== undefined) object.name = data.name;
  25861. if (data.matrix !== undefined) {
  25862. object.matrix.fromArray(data.matrix);
  25863. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25864. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25865. } else {
  25866. if (data.position !== undefined) object.position.fromArray(data.position);
  25867. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25868. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25869. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25870. }
  25871. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25872. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25873. if (data.shadow) {
  25874. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25875. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  25876. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25877. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25878. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25879. }
  25880. if (data.visible !== undefined) object.visible = data.visible;
  25881. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25882. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25883. if (data.userData !== undefined) object.userData = data.userData;
  25884. if (data.layers !== undefined) object.layers.mask = data.layers;
  25885. if (data.children !== undefined) {
  25886. const children = data.children;
  25887. for (let i = 0; i < children.length; i++) {
  25888. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  25889. }
  25890. }
  25891. if (data.animations !== undefined) {
  25892. const objectAnimations = data.animations;
  25893. for (let i = 0; i < objectAnimations.length; i++) {
  25894. const uuid = objectAnimations[i];
  25895. object.animations.push(animations[uuid]);
  25896. }
  25897. }
  25898. if (data.type === 'LOD') {
  25899. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  25900. const levels = data.levels;
  25901. for (let l = 0; l < levels.length; l++) {
  25902. const level = levels[l];
  25903. const child = object.getObjectByProperty('uuid', level.object);
  25904. if (child !== undefined) {
  25905. object.addLevel(child, level.distance, level.hysteresis);
  25906. }
  25907. }
  25908. }
  25909. return object;
  25910. }
  25911. bindSkeletons(object, skeletons) {
  25912. if (Object.keys(skeletons).length === 0) return;
  25913. object.traverse(function (child) {
  25914. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  25915. const skeleton = skeletons[child.skeleton];
  25916. if (skeleton === undefined) {
  25917. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  25918. } else {
  25919. child.bind(skeleton, child.bindMatrix);
  25920. }
  25921. }
  25922. });
  25923. }
  25924. }
  25925. const TEXTURE_MAPPING = {
  25926. UVMapping: UVMapping,
  25927. CubeReflectionMapping: CubeReflectionMapping,
  25928. CubeRefractionMapping: CubeRefractionMapping,
  25929. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25930. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25931. CubeUVReflectionMapping: CubeUVReflectionMapping
  25932. };
  25933. const TEXTURE_WRAPPING = {
  25934. RepeatWrapping: RepeatWrapping,
  25935. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25936. MirroredRepeatWrapping: MirroredRepeatWrapping
  25937. };
  25938. const TEXTURE_FILTER = {
  25939. NearestFilter: NearestFilter,
  25940. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25941. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25942. LinearFilter: LinearFilter,
  25943. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25944. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25945. };
  25946. class ImageBitmapLoader extends Loader {
  25947. constructor(manager) {
  25948. super(manager);
  25949. this.isImageBitmapLoader = true;
  25950. if (typeof createImageBitmap === 'undefined') {
  25951. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25952. }
  25953. if (typeof fetch === 'undefined') {
  25954. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25955. }
  25956. this.options = {
  25957. premultiplyAlpha: 'none'
  25958. };
  25959. }
  25960. setOptions(options) {
  25961. this.options = options;
  25962. return this;
  25963. }
  25964. load(url, onLoad, onProgress, onError) {
  25965. if (url === undefined) url = '';
  25966. if (this.path !== undefined) url = this.path + url;
  25967. url = this.manager.resolveURL(url);
  25968. const scope = this;
  25969. const cached = Cache.get(url);
  25970. if (cached !== undefined) {
  25971. scope.manager.itemStart(url);
  25972. setTimeout(function () {
  25973. if (onLoad) onLoad(cached);
  25974. scope.manager.itemEnd(url);
  25975. }, 0);
  25976. return cached;
  25977. }
  25978. const fetchOptions = {};
  25979. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25980. fetchOptions.headers = this.requestHeader;
  25981. fetch(url, fetchOptions).then(function (res) {
  25982. return res.blob();
  25983. }).then(function (blob) {
  25984. return createImageBitmap(blob, Object.assign(scope.options, {
  25985. colorSpaceConversion: 'none'
  25986. }));
  25987. }).then(function (imageBitmap) {
  25988. Cache.add(url, imageBitmap);
  25989. if (onLoad) onLoad(imageBitmap);
  25990. scope.manager.itemEnd(url);
  25991. }).catch(function (e) {
  25992. if (onError) onError(e);
  25993. scope.manager.itemError(url);
  25994. scope.manager.itemEnd(url);
  25995. });
  25996. scope.manager.itemStart(url);
  25997. }
  25998. }
  25999. let _context;
  26000. class AudioContext {
  26001. static getContext() {
  26002. if (_context === undefined) {
  26003. _context = new (window.AudioContext || window.webkitAudioContext)();
  26004. }
  26005. return _context;
  26006. }
  26007. static setContext(value) {
  26008. _context = value;
  26009. }
  26010. }
  26011. class AudioLoader extends Loader {
  26012. constructor(manager) {
  26013. super(manager);
  26014. }
  26015. load(url, onLoad, onProgress, onError) {
  26016. const scope = this;
  26017. const loader = new FileLoader(this.manager);
  26018. loader.setResponseType('arraybuffer');
  26019. loader.setPath(this.path);
  26020. loader.setRequestHeader(this.requestHeader);
  26021. loader.setWithCredentials(this.withCredentials);
  26022. loader.load(url, function (buffer) {
  26023. try {
  26024. // Create a copy of the buffer. The `decodeAudioData` method
  26025. // detaches the buffer when complete, preventing reuse.
  26026. const bufferCopy = buffer.slice(0);
  26027. const context = AudioContext.getContext();
  26028. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  26029. onLoad(audioBuffer);
  26030. });
  26031. } catch (e) {
  26032. if (onError) {
  26033. onError(e);
  26034. } else {
  26035. console.error(e);
  26036. }
  26037. scope.manager.itemError(url);
  26038. }
  26039. }, onProgress, onError);
  26040. }
  26041. }
  26042. class HemisphereLightProbe extends LightProbe {
  26043. constructor(skyColor, groundColor, intensity = 1) {
  26044. super(undefined, intensity);
  26045. this.isHemisphereLightProbe = true;
  26046. const color1 = new Color().set(skyColor);
  26047. const color2 = new Color().set(groundColor);
  26048. const sky = new Vector3(color1.r, color1.g, color1.b);
  26049. const ground = new Vector3(color2.r, color2.g, color2.b);
  26050. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26051. const c0 = Math.sqrt(Math.PI);
  26052. const c1 = c0 * Math.sqrt(0.75);
  26053. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  26054. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  26055. }
  26056. }
  26057. class AmbientLightProbe extends LightProbe {
  26058. constructor(color, intensity = 1) {
  26059. super(undefined, intensity);
  26060. this.isAmbientLightProbe = true;
  26061. const color1 = new Color().set(color);
  26062. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26063. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  26064. }
  26065. }
  26066. const _eyeRight = /*@__PURE__*/new Matrix4();
  26067. const _eyeLeft = /*@__PURE__*/new Matrix4();
  26068. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  26069. class StereoCamera {
  26070. constructor() {
  26071. this.type = 'StereoCamera';
  26072. this.aspect = 1;
  26073. this.eyeSep = 0.064;
  26074. this.cameraL = new PerspectiveCamera();
  26075. this.cameraL.layers.enable(1);
  26076. this.cameraL.matrixAutoUpdate = false;
  26077. this.cameraR = new PerspectiveCamera();
  26078. this.cameraR.layers.enable(2);
  26079. this.cameraR.matrixAutoUpdate = false;
  26080. this._cache = {
  26081. focus: null,
  26082. fov: null,
  26083. aspect: null,
  26084. near: null,
  26085. far: null,
  26086. zoom: null,
  26087. eyeSep: null
  26088. };
  26089. }
  26090. update(camera) {
  26091. const cache = this._cache;
  26092. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26093. if (needsUpdate) {
  26094. cache.focus = camera.focus;
  26095. cache.fov = camera.fov;
  26096. cache.aspect = camera.aspect * this.aspect;
  26097. cache.near = camera.near;
  26098. cache.far = camera.far;
  26099. cache.zoom = camera.zoom;
  26100. cache.eyeSep = this.eyeSep;
  26101. // Off-axis stereoscopic effect based on
  26102. // http://paulbourke.net/stereographics/stereorender/
  26103. _projectionMatrix.copy(camera.projectionMatrix);
  26104. const eyeSepHalf = cache.eyeSep / 2;
  26105. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26106. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  26107. let xmin, xmax;
  26108. // translate xOffset
  26109. _eyeLeft.elements[12] = -eyeSepHalf;
  26110. _eyeRight.elements[12] = eyeSepHalf;
  26111. // for left eye
  26112. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  26113. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26114. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  26115. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  26116. this.cameraL.projectionMatrix.copy(_projectionMatrix);
  26117. // for right eye
  26118. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  26119. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26120. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  26121. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  26122. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  26123. }
  26124. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  26125. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  26126. }
  26127. }
  26128. class Clock {
  26129. constructor(autoStart = true) {
  26130. this.autoStart = autoStart;
  26131. this.startTime = 0;
  26132. this.oldTime = 0;
  26133. this.elapsedTime = 0;
  26134. this.running = false;
  26135. }
  26136. start() {
  26137. this.startTime = now();
  26138. this.oldTime = this.startTime;
  26139. this.elapsedTime = 0;
  26140. this.running = true;
  26141. }
  26142. stop() {
  26143. this.getElapsedTime();
  26144. this.running = false;
  26145. this.autoStart = false;
  26146. }
  26147. getElapsedTime() {
  26148. this.getDelta();
  26149. return this.elapsedTime;
  26150. }
  26151. getDelta() {
  26152. let diff = 0;
  26153. if (this.autoStart && !this.running) {
  26154. this.start();
  26155. return 0;
  26156. }
  26157. if (this.running) {
  26158. const newTime = now();
  26159. diff = (newTime - this.oldTime) / 1000;
  26160. this.oldTime = newTime;
  26161. this.elapsedTime += diff;
  26162. }
  26163. return diff;
  26164. }
  26165. }
  26166. function now() {
  26167. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  26168. }
  26169. const _position$1 = /*@__PURE__*/new Vector3();
  26170. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  26171. const _scale$1 = /*@__PURE__*/new Vector3();
  26172. const _orientation$1 = /*@__PURE__*/new Vector3();
  26173. class AudioListener extends Object3D {
  26174. constructor() {
  26175. super();
  26176. this.type = 'AudioListener';
  26177. this.context = AudioContext.getContext();
  26178. this.gain = this.context.createGain();
  26179. this.gain.connect(this.context.destination);
  26180. this.filter = null;
  26181. this.timeDelta = 0;
  26182. // private
  26183. this._clock = new Clock();
  26184. }
  26185. getInput() {
  26186. return this.gain;
  26187. }
  26188. removeFilter() {
  26189. if (this.filter !== null) {
  26190. this.gain.disconnect(this.filter);
  26191. this.filter.disconnect(this.context.destination);
  26192. this.gain.connect(this.context.destination);
  26193. this.filter = null;
  26194. }
  26195. return this;
  26196. }
  26197. getFilter() {
  26198. return this.filter;
  26199. }
  26200. setFilter(value) {
  26201. if (this.filter !== null) {
  26202. this.gain.disconnect(this.filter);
  26203. this.filter.disconnect(this.context.destination);
  26204. } else {
  26205. this.gain.disconnect(this.context.destination);
  26206. }
  26207. this.filter = value;
  26208. this.gain.connect(this.filter);
  26209. this.filter.connect(this.context.destination);
  26210. return this;
  26211. }
  26212. getMasterVolume() {
  26213. return this.gain.gain.value;
  26214. }
  26215. setMasterVolume(value) {
  26216. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26217. return this;
  26218. }
  26219. updateMatrixWorld(force) {
  26220. super.updateMatrixWorld(force);
  26221. const listener = this.context.listener;
  26222. const up = this.up;
  26223. this.timeDelta = this._clock.getDelta();
  26224. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  26225. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  26226. if (listener.positionX) {
  26227. // code path for Chrome (see #14393)
  26228. const endTime = this.context.currentTime + this.timeDelta;
  26229. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  26230. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  26231. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  26232. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26233. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26234. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26235. listener.upX.linearRampToValueAtTime(up.x, endTime);
  26236. listener.upY.linearRampToValueAtTime(up.y, endTime);
  26237. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  26238. } else {
  26239. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  26240. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  26241. }
  26242. }
  26243. }
  26244. class Audio extends Object3D {
  26245. constructor(listener) {
  26246. super();
  26247. this.type = 'Audio';
  26248. this.listener = listener;
  26249. this.context = listener.context;
  26250. this.gain = this.context.createGain();
  26251. this.gain.connect(listener.getInput());
  26252. this.autoplay = false;
  26253. this.buffer = null;
  26254. this.detune = 0;
  26255. this.loop = false;
  26256. this.loopStart = 0;
  26257. this.loopEnd = 0;
  26258. this.offset = 0;
  26259. this.duration = undefined;
  26260. this.playbackRate = 1;
  26261. this.isPlaying = false;
  26262. this.hasPlaybackControl = true;
  26263. this.source = null;
  26264. this.sourceType = 'empty';
  26265. this._startedAt = 0;
  26266. this._progress = 0;
  26267. this._connected = false;
  26268. this.filters = [];
  26269. }
  26270. getOutput() {
  26271. return this.gain;
  26272. }
  26273. setNodeSource(audioNode) {
  26274. this.hasPlaybackControl = false;
  26275. this.sourceType = 'audioNode';
  26276. this.source = audioNode;
  26277. this.connect();
  26278. return this;
  26279. }
  26280. setMediaElementSource(mediaElement) {
  26281. this.hasPlaybackControl = false;
  26282. this.sourceType = 'mediaNode';
  26283. this.source = this.context.createMediaElementSource(mediaElement);
  26284. this.connect();
  26285. return this;
  26286. }
  26287. setMediaStreamSource(mediaStream) {
  26288. this.hasPlaybackControl = false;
  26289. this.sourceType = 'mediaStreamNode';
  26290. this.source = this.context.createMediaStreamSource(mediaStream);
  26291. this.connect();
  26292. return this;
  26293. }
  26294. setBuffer(audioBuffer) {
  26295. this.buffer = audioBuffer;
  26296. this.sourceType = 'buffer';
  26297. if (this.autoplay) this.play();
  26298. return this;
  26299. }
  26300. play(delay = 0) {
  26301. if (this.isPlaying === true) {
  26302. console.warn('THREE.Audio: Audio is already playing.');
  26303. return;
  26304. }
  26305. if (this.hasPlaybackControl === false) {
  26306. console.warn('THREE.Audio: this Audio has no playback control.');
  26307. return;
  26308. }
  26309. this._startedAt = this.context.currentTime + delay;
  26310. const source = this.context.createBufferSource();
  26311. source.buffer = this.buffer;
  26312. source.loop = this.loop;
  26313. source.loopStart = this.loopStart;
  26314. source.loopEnd = this.loopEnd;
  26315. source.onended = this.onEnded.bind(this);
  26316. source.start(this._startedAt, this._progress + this.offset, this.duration);
  26317. this.isPlaying = true;
  26318. this.source = source;
  26319. this.setDetune(this.detune);
  26320. this.setPlaybackRate(this.playbackRate);
  26321. return this.connect();
  26322. }
  26323. pause() {
  26324. if (this.hasPlaybackControl === false) {
  26325. console.warn('THREE.Audio: this Audio has no playback control.');
  26326. return;
  26327. }
  26328. if (this.isPlaying === true) {
  26329. // update current progress
  26330. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  26331. if (this.loop === true) {
  26332. // ensure _progress does not exceed duration with looped audios
  26333. this._progress = this._progress % (this.duration || this.buffer.duration);
  26334. }
  26335. this.source.stop();
  26336. this.source.onended = null;
  26337. this.isPlaying = false;
  26338. }
  26339. return this;
  26340. }
  26341. stop() {
  26342. if (this.hasPlaybackControl === false) {
  26343. console.warn('THREE.Audio: this Audio has no playback control.');
  26344. return;
  26345. }
  26346. this._progress = 0;
  26347. this.source.stop();
  26348. this.source.onended = null;
  26349. this.isPlaying = false;
  26350. return this;
  26351. }
  26352. connect() {
  26353. if (this.filters.length > 0) {
  26354. this.source.connect(this.filters[0]);
  26355. for (let i = 1, l = this.filters.length; i < l; i++) {
  26356. this.filters[i - 1].connect(this.filters[i]);
  26357. }
  26358. this.filters[this.filters.length - 1].connect(this.getOutput());
  26359. } else {
  26360. this.source.connect(this.getOutput());
  26361. }
  26362. this._connected = true;
  26363. return this;
  26364. }
  26365. disconnect() {
  26366. if (this.filters.length > 0) {
  26367. this.source.disconnect(this.filters[0]);
  26368. for (let i = 1, l = this.filters.length; i < l; i++) {
  26369. this.filters[i - 1].disconnect(this.filters[i]);
  26370. }
  26371. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26372. } else {
  26373. this.source.disconnect(this.getOutput());
  26374. }
  26375. this._connected = false;
  26376. return this;
  26377. }
  26378. getFilters() {
  26379. return this.filters;
  26380. }
  26381. setFilters(value) {
  26382. if (!value) value = [];
  26383. if (this._connected === true) {
  26384. this.disconnect();
  26385. this.filters = value.slice();
  26386. this.connect();
  26387. } else {
  26388. this.filters = value.slice();
  26389. }
  26390. return this;
  26391. }
  26392. setDetune(value) {
  26393. this.detune = value;
  26394. if (this.source.detune === undefined) return; // only set detune when available
  26395. if (this.isPlaying === true) {
  26396. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26397. }
  26398. return this;
  26399. }
  26400. getDetune() {
  26401. return this.detune;
  26402. }
  26403. getFilter() {
  26404. return this.getFilters()[0];
  26405. }
  26406. setFilter(filter) {
  26407. return this.setFilters(filter ? [filter] : []);
  26408. }
  26409. setPlaybackRate(value) {
  26410. if (this.hasPlaybackControl === false) {
  26411. console.warn('THREE.Audio: this Audio has no playback control.');
  26412. return;
  26413. }
  26414. this.playbackRate = value;
  26415. if (this.isPlaying === true) {
  26416. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26417. }
  26418. return this;
  26419. }
  26420. getPlaybackRate() {
  26421. return this.playbackRate;
  26422. }
  26423. onEnded() {
  26424. this.isPlaying = false;
  26425. }
  26426. getLoop() {
  26427. if (this.hasPlaybackControl === false) {
  26428. console.warn('THREE.Audio: this Audio has no playback control.');
  26429. return false;
  26430. }
  26431. return this.loop;
  26432. }
  26433. setLoop(value) {
  26434. if (this.hasPlaybackControl === false) {
  26435. console.warn('THREE.Audio: this Audio has no playback control.');
  26436. return;
  26437. }
  26438. this.loop = value;
  26439. if (this.isPlaying === true) {
  26440. this.source.loop = this.loop;
  26441. }
  26442. return this;
  26443. }
  26444. setLoopStart(value) {
  26445. this.loopStart = value;
  26446. return this;
  26447. }
  26448. setLoopEnd(value) {
  26449. this.loopEnd = value;
  26450. return this;
  26451. }
  26452. getVolume() {
  26453. return this.gain.gain.value;
  26454. }
  26455. setVolume(value) {
  26456. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26457. return this;
  26458. }
  26459. }
  26460. const _position = /*@__PURE__*/new Vector3();
  26461. const _quaternion = /*@__PURE__*/new Quaternion();
  26462. const _scale = /*@__PURE__*/new Vector3();
  26463. const _orientation = /*@__PURE__*/new Vector3();
  26464. class PositionalAudio extends Audio {
  26465. constructor(listener) {
  26466. super(listener);
  26467. this.panner = this.context.createPanner();
  26468. this.panner.panningModel = 'HRTF';
  26469. this.panner.connect(this.gain);
  26470. }
  26471. disconnect() {
  26472. super.disconnect();
  26473. this.panner.disconnect(this.gain);
  26474. }
  26475. getOutput() {
  26476. return this.panner;
  26477. }
  26478. getRefDistance() {
  26479. return this.panner.refDistance;
  26480. }
  26481. setRefDistance(value) {
  26482. this.panner.refDistance = value;
  26483. return this;
  26484. }
  26485. getRolloffFactor() {
  26486. return this.panner.rolloffFactor;
  26487. }
  26488. setRolloffFactor(value) {
  26489. this.panner.rolloffFactor = value;
  26490. return this;
  26491. }
  26492. getDistanceModel() {
  26493. return this.panner.distanceModel;
  26494. }
  26495. setDistanceModel(value) {
  26496. this.panner.distanceModel = value;
  26497. return this;
  26498. }
  26499. getMaxDistance() {
  26500. return this.panner.maxDistance;
  26501. }
  26502. setMaxDistance(value) {
  26503. this.panner.maxDistance = value;
  26504. return this;
  26505. }
  26506. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26507. this.panner.coneInnerAngle = coneInnerAngle;
  26508. this.panner.coneOuterAngle = coneOuterAngle;
  26509. this.panner.coneOuterGain = coneOuterGain;
  26510. return this;
  26511. }
  26512. updateMatrixWorld(force) {
  26513. super.updateMatrixWorld(force);
  26514. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26515. this.matrixWorld.decompose(_position, _quaternion, _scale);
  26516. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  26517. const panner = this.panner;
  26518. if (panner.positionX) {
  26519. // code path for Chrome and Firefox (see #14393)
  26520. const endTime = this.context.currentTime + this.listener.timeDelta;
  26521. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  26522. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  26523. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  26524. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  26525. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  26526. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  26527. } else {
  26528. panner.setPosition(_position.x, _position.y, _position.z);
  26529. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  26530. }
  26531. }
  26532. }
  26533. class AudioAnalyser {
  26534. constructor(audio, fftSize = 2048) {
  26535. this.analyser = audio.context.createAnalyser();
  26536. this.analyser.fftSize = fftSize;
  26537. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26538. audio.getOutput().connect(this.analyser);
  26539. }
  26540. getFrequencyData() {
  26541. this.analyser.getByteFrequencyData(this.data);
  26542. return this.data;
  26543. }
  26544. getAverageFrequency() {
  26545. let value = 0;
  26546. const data = this.getFrequencyData();
  26547. for (let i = 0; i < data.length; i++) {
  26548. value += data[i];
  26549. }
  26550. return value / data.length;
  26551. }
  26552. }
  26553. class PropertyMixer {
  26554. constructor(binding, typeName, valueSize) {
  26555. this.binding = binding;
  26556. this.valueSize = valueSize;
  26557. let mixFunction, mixFunctionAdditive, setIdentity;
  26558. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26559. //
  26560. // interpolators can use .buffer as their .result
  26561. // the data then goes to 'incoming'
  26562. //
  26563. // 'accu0' and 'accu1' are used frame-interleaved for
  26564. // the cumulative result and are compared to detect
  26565. // changes
  26566. //
  26567. // 'orig' stores the original state of the property
  26568. //
  26569. // 'add' is used for additive cumulative results
  26570. //
  26571. // 'work' is optional and is only present for quaternion types. It is used
  26572. // to store intermediate quaternion multiplication results
  26573. switch (typeName) {
  26574. case 'quaternion':
  26575. mixFunction = this._slerp;
  26576. mixFunctionAdditive = this._slerpAdditive;
  26577. setIdentity = this._setAdditiveIdentityQuaternion;
  26578. this.buffer = new Float64Array(valueSize * 6);
  26579. this._workIndex = 5;
  26580. break;
  26581. case 'string':
  26582. case 'bool':
  26583. mixFunction = this._select;
  26584. // Use the regular mix function and for additive on these types,
  26585. // additive is not relevant for non-numeric types
  26586. mixFunctionAdditive = this._select;
  26587. setIdentity = this._setAdditiveIdentityOther;
  26588. this.buffer = new Array(valueSize * 5);
  26589. break;
  26590. default:
  26591. mixFunction = this._lerp;
  26592. mixFunctionAdditive = this._lerpAdditive;
  26593. setIdentity = this._setAdditiveIdentityNumeric;
  26594. this.buffer = new Float64Array(valueSize * 5);
  26595. }
  26596. this._mixBufferRegion = mixFunction;
  26597. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26598. this._setIdentity = setIdentity;
  26599. this._origIndex = 3;
  26600. this._addIndex = 4;
  26601. this.cumulativeWeight = 0;
  26602. this.cumulativeWeightAdditive = 0;
  26603. this.useCount = 0;
  26604. this.referenceCount = 0;
  26605. }
  26606. // accumulate data in the 'incoming' region into 'accu<i>'
  26607. accumulate(accuIndex, weight) {
  26608. // note: happily accumulating nothing when weight = 0, the caller knows
  26609. // the weight and shouldn't have made the call in the first place
  26610. const buffer = this.buffer,
  26611. stride = this.valueSize,
  26612. offset = accuIndex * stride + stride;
  26613. let currentWeight = this.cumulativeWeight;
  26614. if (currentWeight === 0) {
  26615. // accuN := incoming * weight
  26616. for (let i = 0; i !== stride; ++i) {
  26617. buffer[offset + i] = buffer[i];
  26618. }
  26619. currentWeight = weight;
  26620. } else {
  26621. // accuN := accuN + incoming * weight
  26622. currentWeight += weight;
  26623. const mix = weight / currentWeight;
  26624. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26625. }
  26626. this.cumulativeWeight = currentWeight;
  26627. }
  26628. // accumulate data in the 'incoming' region into 'add'
  26629. accumulateAdditive(weight) {
  26630. const buffer = this.buffer,
  26631. stride = this.valueSize,
  26632. offset = stride * this._addIndex;
  26633. if (this.cumulativeWeightAdditive === 0) {
  26634. // add = identity
  26635. this._setIdentity();
  26636. }
  26637. // add := add + incoming * weight
  26638. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  26639. this.cumulativeWeightAdditive += weight;
  26640. }
  26641. // apply the state of 'accu<i>' to the binding when accus differ
  26642. apply(accuIndex) {
  26643. const stride = this.valueSize,
  26644. buffer = this.buffer,
  26645. offset = accuIndex * stride + stride,
  26646. weight = this.cumulativeWeight,
  26647. weightAdditive = this.cumulativeWeightAdditive,
  26648. binding = this.binding;
  26649. this.cumulativeWeight = 0;
  26650. this.cumulativeWeightAdditive = 0;
  26651. if (weight < 1) {
  26652. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26653. const originalValueOffset = stride * this._origIndex;
  26654. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26655. }
  26656. if (weightAdditive > 0) {
  26657. // accuN := accuN + additive accuN
  26658. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  26659. }
  26660. for (let i = stride, e = stride + stride; i !== e; ++i) {
  26661. if (buffer[i] !== buffer[i + stride]) {
  26662. // value has changed -> update scene graph
  26663. binding.setValue(buffer, offset);
  26664. break;
  26665. }
  26666. }
  26667. }
  26668. // remember the state of the bound property and copy it to both accus
  26669. saveOriginalState() {
  26670. const binding = this.binding;
  26671. const buffer = this.buffer,
  26672. stride = this.valueSize,
  26673. originalValueOffset = stride * this._origIndex;
  26674. binding.getValue(buffer, originalValueOffset);
  26675. // accu[0..1] := orig -- initially detect changes against the original
  26676. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  26677. buffer[i] = buffer[originalValueOffset + i % stride];
  26678. }
  26679. // Add to identity for additive
  26680. this._setIdentity();
  26681. this.cumulativeWeight = 0;
  26682. this.cumulativeWeightAdditive = 0;
  26683. }
  26684. // apply the state previously taken via 'saveOriginalState' to the binding
  26685. restoreOriginalState() {
  26686. const originalValueOffset = this.valueSize * 3;
  26687. this.binding.setValue(this.buffer, originalValueOffset);
  26688. }
  26689. _setAdditiveIdentityNumeric() {
  26690. const startIndex = this._addIndex * this.valueSize;
  26691. const endIndex = startIndex + this.valueSize;
  26692. for (let i = startIndex; i < endIndex; i++) {
  26693. this.buffer[i] = 0;
  26694. }
  26695. }
  26696. _setAdditiveIdentityQuaternion() {
  26697. this._setAdditiveIdentityNumeric();
  26698. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  26699. }
  26700. _setAdditiveIdentityOther() {
  26701. const startIndex = this._origIndex * this.valueSize;
  26702. const targetIndex = this._addIndex * this.valueSize;
  26703. for (let i = 0; i < this.valueSize; i++) {
  26704. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  26705. }
  26706. }
  26707. // mix functions
  26708. _select(buffer, dstOffset, srcOffset, t, stride) {
  26709. if (t >= 0.5) {
  26710. for (let i = 0; i !== stride; ++i) {
  26711. buffer[dstOffset + i] = buffer[srcOffset + i];
  26712. }
  26713. }
  26714. }
  26715. _slerp(buffer, dstOffset, srcOffset, t) {
  26716. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26717. }
  26718. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  26719. const workOffset = this._workIndex * stride;
  26720. // Store result in intermediate buffer offset
  26721. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset);
  26722. // Slerp to the intermediate result
  26723. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  26724. }
  26725. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  26726. const s = 1 - t;
  26727. for (let i = 0; i !== stride; ++i) {
  26728. const j = dstOffset + i;
  26729. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26730. }
  26731. }
  26732. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  26733. for (let i = 0; i !== stride; ++i) {
  26734. const j = dstOffset + i;
  26735. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  26736. }
  26737. }
  26738. }
  26739. // Characters [].:/ are reserved for track binding syntax.
  26740. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26741. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g');
  26742. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26743. // only latin characters, and the unicode \p{L} is not yet supported. So
  26744. // instead, we exclude reserved characters and match everything else.
  26745. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26746. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']';
  26747. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26748. // be matched to parse the rest of the track name.
  26749. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace('WC', _wordChar);
  26750. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26751. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot);
  26752. // Object on target node, and accessor. May not contain reserved
  26753. // characters. Accessor may contain any character except closing bracket.
  26754. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar);
  26755. // Property and accessor. May not contain reserved characters. Accessor may
  26756. // contain any non-bracket characters.
  26757. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26758. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26759. const _supportedObjectNames = ['material', 'materials', 'bones', 'map'];
  26760. class Composite {
  26761. constructor(targetGroup, path, optionalParsedPath) {
  26762. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26763. this._targetGroup = targetGroup;
  26764. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26765. }
  26766. getValue(array, offset) {
  26767. this.bind(); // bind all binding
  26768. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26769. binding = this._bindings[firstValidIndex];
  26770. // and only call .getValue on the first
  26771. if (binding !== undefined) binding.getValue(array, offset);
  26772. }
  26773. setValue(array, offset) {
  26774. const bindings = this._bindings;
  26775. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26776. bindings[i].setValue(array, offset);
  26777. }
  26778. }
  26779. bind() {
  26780. const bindings = this._bindings;
  26781. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26782. bindings[i].bind();
  26783. }
  26784. }
  26785. unbind() {
  26786. const bindings = this._bindings;
  26787. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26788. bindings[i].unbind();
  26789. }
  26790. }
  26791. }
  26792. // Note: This class uses a State pattern on a per-method basis:
  26793. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26794. // prototype version of these methods with one that represents
  26795. // the bound state. When the property is not found, the methods
  26796. // become no-ops.
  26797. class PropertyBinding {
  26798. constructor(rootNode, path, parsedPath) {
  26799. this.path = path;
  26800. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26801. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26802. this.rootNode = rootNode;
  26803. // initial state of these methods that calls 'bind'
  26804. this.getValue = this._getValue_unbound;
  26805. this.setValue = this._setValue_unbound;
  26806. }
  26807. static create(root, path, parsedPath) {
  26808. if (!(root && root.isAnimationObjectGroup)) {
  26809. return new PropertyBinding(root, path, parsedPath);
  26810. } else {
  26811. return new PropertyBinding.Composite(root, path, parsedPath);
  26812. }
  26813. }
  26814. /**
  26815. * Replaces spaces with underscores and removes unsupported characters from
  26816. * node names, to ensure compatibility with parseTrackName().
  26817. *
  26818. * @param {string} name Node name to be sanitized.
  26819. * @return {string}
  26820. */
  26821. static sanitizeNodeName(name) {
  26822. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26823. }
  26824. static parseTrackName(trackName) {
  26825. const matches = _trackRe.exec(trackName);
  26826. if (matches === null) {
  26827. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26828. }
  26829. const results = {
  26830. // directoryName: matches[ 1 ], // (tschw) currently unused
  26831. nodeName: matches[2],
  26832. objectName: matches[3],
  26833. objectIndex: matches[4],
  26834. propertyName: matches[5],
  26835. // required
  26836. propertyIndex: matches[6]
  26837. };
  26838. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26839. if (lastDot !== undefined && lastDot !== -1) {
  26840. const objectName = results.nodeName.substring(lastDot + 1);
  26841. // Object names must be checked against an allowlist. Otherwise, there
  26842. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26843. // 'bar' could be the objectName, or part of a nodeName (which can
  26844. // include '.' characters).
  26845. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26846. results.nodeName = results.nodeName.substring(0, lastDot);
  26847. results.objectName = objectName;
  26848. }
  26849. }
  26850. if (results.propertyName === null || results.propertyName.length === 0) {
  26851. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26852. }
  26853. return results;
  26854. }
  26855. static findNode(root, nodeName) {
  26856. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26857. return root;
  26858. }
  26859. // search into skeleton bones.
  26860. if (root.skeleton) {
  26861. const bone = root.skeleton.getBoneByName(nodeName);
  26862. if (bone !== undefined) {
  26863. return bone;
  26864. }
  26865. }
  26866. // search into node subtree.
  26867. if (root.children) {
  26868. const searchNodeSubtree = function (children) {
  26869. for (let i = 0; i < children.length; i++) {
  26870. const childNode = children[i];
  26871. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26872. return childNode;
  26873. }
  26874. const result = searchNodeSubtree(childNode.children);
  26875. if (result) return result;
  26876. }
  26877. return null;
  26878. };
  26879. const subTreeNode = searchNodeSubtree(root.children);
  26880. if (subTreeNode) {
  26881. return subTreeNode;
  26882. }
  26883. }
  26884. return null;
  26885. }
  26886. // these are used to "bind" a nonexistent property
  26887. _getValue_unavailable() {}
  26888. _setValue_unavailable() {}
  26889. // Getters
  26890. _getValue_direct(buffer, offset) {
  26891. buffer[offset] = this.targetObject[this.propertyName];
  26892. }
  26893. _getValue_array(buffer, offset) {
  26894. const source = this.resolvedProperty;
  26895. for (let i = 0, n = source.length; i !== n; ++i) {
  26896. buffer[offset++] = source[i];
  26897. }
  26898. }
  26899. _getValue_arrayElement(buffer, offset) {
  26900. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26901. }
  26902. _getValue_toArray(buffer, offset) {
  26903. this.resolvedProperty.toArray(buffer, offset);
  26904. }
  26905. // Direct
  26906. _setValue_direct(buffer, offset) {
  26907. this.targetObject[this.propertyName] = buffer[offset];
  26908. }
  26909. _setValue_direct_setNeedsUpdate(buffer, offset) {
  26910. this.targetObject[this.propertyName] = buffer[offset];
  26911. this.targetObject.needsUpdate = true;
  26912. }
  26913. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26914. this.targetObject[this.propertyName] = buffer[offset];
  26915. this.targetObject.matrixWorldNeedsUpdate = true;
  26916. }
  26917. // EntireArray
  26918. _setValue_array(buffer, offset) {
  26919. const dest = this.resolvedProperty;
  26920. for (let i = 0, n = dest.length; i !== n; ++i) {
  26921. dest[i] = buffer[offset++];
  26922. }
  26923. }
  26924. _setValue_array_setNeedsUpdate(buffer, offset) {
  26925. const dest = this.resolvedProperty;
  26926. for (let i = 0, n = dest.length; i !== n; ++i) {
  26927. dest[i] = buffer[offset++];
  26928. }
  26929. this.targetObject.needsUpdate = true;
  26930. }
  26931. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26932. const dest = this.resolvedProperty;
  26933. for (let i = 0, n = dest.length; i !== n; ++i) {
  26934. dest[i] = buffer[offset++];
  26935. }
  26936. this.targetObject.matrixWorldNeedsUpdate = true;
  26937. }
  26938. // ArrayElement
  26939. _setValue_arrayElement(buffer, offset) {
  26940. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26941. }
  26942. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26943. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26944. this.targetObject.needsUpdate = true;
  26945. }
  26946. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26947. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26948. this.targetObject.matrixWorldNeedsUpdate = true;
  26949. }
  26950. // HasToFromArray
  26951. _setValue_fromArray(buffer, offset) {
  26952. this.resolvedProperty.fromArray(buffer, offset);
  26953. }
  26954. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26955. this.resolvedProperty.fromArray(buffer, offset);
  26956. this.targetObject.needsUpdate = true;
  26957. }
  26958. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26959. this.resolvedProperty.fromArray(buffer, offset);
  26960. this.targetObject.matrixWorldNeedsUpdate = true;
  26961. }
  26962. _getValue_unbound(targetArray, offset) {
  26963. this.bind();
  26964. this.getValue(targetArray, offset);
  26965. }
  26966. _setValue_unbound(sourceArray, offset) {
  26967. this.bind();
  26968. this.setValue(sourceArray, offset);
  26969. }
  26970. // create getter / setter pair for a property in the scene graph
  26971. bind() {
  26972. let targetObject = this.node;
  26973. const parsedPath = this.parsedPath;
  26974. const objectName = parsedPath.objectName;
  26975. const propertyName = parsedPath.propertyName;
  26976. let propertyIndex = parsedPath.propertyIndex;
  26977. if (!targetObject) {
  26978. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26979. this.node = targetObject;
  26980. }
  26981. // set fail state so we can just 'return' on error
  26982. this.getValue = this._getValue_unavailable;
  26983. this.setValue = this._setValue_unavailable;
  26984. // ensure there is a value node
  26985. if (!targetObject) {
  26986. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26987. return;
  26988. }
  26989. if (objectName) {
  26990. let objectIndex = parsedPath.objectIndex;
  26991. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26992. switch (objectName) {
  26993. case 'materials':
  26994. if (!targetObject.material) {
  26995. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26996. return;
  26997. }
  26998. if (!targetObject.material.materials) {
  26999. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  27000. return;
  27001. }
  27002. targetObject = targetObject.material.materials;
  27003. break;
  27004. case 'bones':
  27005. if (!targetObject.skeleton) {
  27006. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  27007. return;
  27008. }
  27009. // potential future optimization: skip this if propertyIndex is already an integer
  27010. // and convert the integer string to a true integer.
  27011. targetObject = targetObject.skeleton.bones;
  27012. // support resolving morphTarget names into indices.
  27013. for (let i = 0; i < targetObject.length; i++) {
  27014. if (targetObject[i].name === objectIndex) {
  27015. objectIndex = i;
  27016. break;
  27017. }
  27018. }
  27019. break;
  27020. case 'map':
  27021. if ('map' in targetObject) {
  27022. targetObject = targetObject.map;
  27023. break;
  27024. }
  27025. if (!targetObject.material) {
  27026. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  27027. return;
  27028. }
  27029. if (!targetObject.material.map) {
  27030. console.error('THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this);
  27031. return;
  27032. }
  27033. targetObject = targetObject.material.map;
  27034. break;
  27035. default:
  27036. if (targetObject[objectName] === undefined) {
  27037. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  27038. return;
  27039. }
  27040. targetObject = targetObject[objectName];
  27041. }
  27042. if (objectIndex !== undefined) {
  27043. if (targetObject[objectIndex] === undefined) {
  27044. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  27045. return;
  27046. }
  27047. targetObject = targetObject[objectIndex];
  27048. }
  27049. }
  27050. // resolve property
  27051. const nodeProperty = targetObject[propertyName];
  27052. if (nodeProperty === undefined) {
  27053. const nodeName = parsedPath.nodeName;
  27054. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  27055. return;
  27056. }
  27057. // determine versioning scheme
  27058. let versioning = this.Versioning.None;
  27059. this.targetObject = targetObject;
  27060. if (targetObject.needsUpdate !== undefined) {
  27061. // material
  27062. versioning = this.Versioning.NeedsUpdate;
  27063. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  27064. // node transform
  27065. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27066. }
  27067. // determine how the property gets bound
  27068. let bindingType = this.BindingType.Direct;
  27069. if (propertyIndex !== undefined) {
  27070. // access a sub element of the property array (only primitives are supported right now)
  27071. if (propertyName === 'morphTargetInfluences') {
  27072. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27073. // support resolving morphTarget names into indices.
  27074. if (!targetObject.geometry) {
  27075. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  27076. return;
  27077. }
  27078. if (!targetObject.geometry.morphAttributes) {
  27079. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  27080. return;
  27081. }
  27082. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  27083. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  27084. }
  27085. }
  27086. bindingType = this.BindingType.ArrayElement;
  27087. this.resolvedProperty = nodeProperty;
  27088. this.propertyIndex = propertyIndex;
  27089. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  27090. // must use copy for Object3D.Euler/Quaternion
  27091. bindingType = this.BindingType.HasFromToArray;
  27092. this.resolvedProperty = nodeProperty;
  27093. } else if (Array.isArray(nodeProperty)) {
  27094. bindingType = this.BindingType.EntireArray;
  27095. this.resolvedProperty = nodeProperty;
  27096. } else {
  27097. this.propertyName = propertyName;
  27098. }
  27099. // select getter / setter
  27100. this.getValue = this.GetterByBindingType[bindingType];
  27101. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  27102. }
  27103. unbind() {
  27104. this.node = null;
  27105. // back to the prototype version of getValue / setValue
  27106. // note: avoiding to mutate the shape of 'this' via 'delete'
  27107. this.getValue = this._getValue_unbound;
  27108. this.setValue = this._setValue_unbound;
  27109. }
  27110. }
  27111. PropertyBinding.Composite = Composite;
  27112. PropertyBinding.prototype.BindingType = {
  27113. Direct: 0,
  27114. EntireArray: 1,
  27115. ArrayElement: 2,
  27116. HasFromToArray: 3
  27117. };
  27118. PropertyBinding.prototype.Versioning = {
  27119. None: 0,
  27120. NeedsUpdate: 1,
  27121. MatrixWorldNeedsUpdate: 2
  27122. };
  27123. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  27124. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[
  27125. // Direct
  27126. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [
  27127. // EntireArray
  27128. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [
  27129. // ArrayElement
  27130. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [
  27131. // HasToFromArray
  27132. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  27133. /**
  27134. *
  27135. * A group of objects that receives a shared animation state.
  27136. *
  27137. * Usage:
  27138. *
  27139. * - Add objects you would otherwise pass as 'root' to the
  27140. * constructor or the .clipAction method of AnimationMixer.
  27141. *
  27142. * - Instead pass this object as 'root'.
  27143. *
  27144. * - You can also add and remove objects later when the mixer
  27145. * is running.
  27146. *
  27147. * Note:
  27148. *
  27149. * Objects of this class appear as one object to the mixer,
  27150. * so cache control of the individual objects must be done
  27151. * on the group.
  27152. *
  27153. * Limitation:
  27154. *
  27155. * - The animated properties must be compatible among the
  27156. * all objects in the group.
  27157. *
  27158. * - A single property can either be controlled through a
  27159. * target group or directly, but not both.
  27160. */
  27161. class AnimationObjectGroup {
  27162. constructor() {
  27163. this.isAnimationObjectGroup = true;
  27164. this.uuid = generateUUID();
  27165. // cached objects followed by the active ones
  27166. this._objects = Array.prototype.slice.call(arguments);
  27167. this.nCachedObjects_ = 0; // threshold
  27168. // note: read by PropertyBinding.Composite
  27169. const indices = {};
  27170. this._indicesByUUID = indices; // for bookkeeping
  27171. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27172. indices[arguments[i].uuid] = i;
  27173. }
  27174. this._paths = []; // inside: string
  27175. this._parsedPaths = []; // inside: { we don't care, here }
  27176. this._bindings = []; // inside: Array< PropertyBinding >
  27177. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27178. const scope = this;
  27179. this.stats = {
  27180. objects: {
  27181. get total() {
  27182. return scope._objects.length;
  27183. },
  27184. get inUse() {
  27185. return this.total - scope.nCachedObjects_;
  27186. }
  27187. },
  27188. get bindingsPerObject() {
  27189. return scope._bindings.length;
  27190. }
  27191. };
  27192. }
  27193. add() {
  27194. const objects = this._objects,
  27195. indicesByUUID = this._indicesByUUID,
  27196. paths = this._paths,
  27197. parsedPaths = this._parsedPaths,
  27198. bindings = this._bindings,
  27199. nBindings = bindings.length;
  27200. let knownObject = undefined,
  27201. nObjects = objects.length,
  27202. nCachedObjects = this.nCachedObjects_;
  27203. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27204. const object = arguments[i],
  27205. uuid = object.uuid;
  27206. let index = indicesByUUID[uuid];
  27207. if (index === undefined) {
  27208. // unknown object -> add it to the ACTIVE region
  27209. index = nObjects++;
  27210. indicesByUUID[uuid] = index;
  27211. objects.push(object);
  27212. // accounting is done, now do the same for all bindings
  27213. for (let j = 0, m = nBindings; j !== m; ++j) {
  27214. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  27215. }
  27216. } else if (index < nCachedObjects) {
  27217. knownObject = objects[index];
  27218. // move existing object to the ACTIVE region
  27219. const firstActiveIndex = --nCachedObjects,
  27220. lastCachedObject = objects[firstActiveIndex];
  27221. indicesByUUID[lastCachedObject.uuid] = index;
  27222. objects[index] = lastCachedObject;
  27223. indicesByUUID[uuid] = firstActiveIndex;
  27224. objects[firstActiveIndex] = object;
  27225. // accounting is done, now do the same for all bindings
  27226. for (let j = 0, m = nBindings; j !== m; ++j) {
  27227. const bindingsForPath = bindings[j],
  27228. lastCached = bindingsForPath[firstActiveIndex];
  27229. let binding = bindingsForPath[index];
  27230. bindingsForPath[index] = lastCached;
  27231. if (binding === undefined) {
  27232. // since we do not bother to create new bindings
  27233. // for objects that are cached, the binding may
  27234. // or may not exist
  27235. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  27236. }
  27237. bindingsForPath[firstActiveIndex] = binding;
  27238. }
  27239. } else if (objects[index] !== knownObject) {
  27240. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  27241. } // else the object is already where we want it to be
  27242. } // for arguments
  27243. this.nCachedObjects_ = nCachedObjects;
  27244. }
  27245. remove() {
  27246. const objects = this._objects,
  27247. indicesByUUID = this._indicesByUUID,
  27248. bindings = this._bindings,
  27249. nBindings = bindings.length;
  27250. let nCachedObjects = this.nCachedObjects_;
  27251. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27252. const object = arguments[i],
  27253. uuid = object.uuid,
  27254. index = indicesByUUID[uuid];
  27255. if (index !== undefined && index >= nCachedObjects) {
  27256. // move existing object into the CACHED region
  27257. const lastCachedIndex = nCachedObjects++,
  27258. firstActiveObject = objects[lastCachedIndex];
  27259. indicesByUUID[firstActiveObject.uuid] = index;
  27260. objects[index] = firstActiveObject;
  27261. indicesByUUID[uuid] = lastCachedIndex;
  27262. objects[lastCachedIndex] = object;
  27263. // accounting is done, now do the same for all bindings
  27264. for (let j = 0, m = nBindings; j !== m; ++j) {
  27265. const bindingsForPath = bindings[j],
  27266. firstActive = bindingsForPath[lastCachedIndex],
  27267. binding = bindingsForPath[index];
  27268. bindingsForPath[index] = firstActive;
  27269. bindingsForPath[lastCachedIndex] = binding;
  27270. }
  27271. }
  27272. } // for arguments
  27273. this.nCachedObjects_ = nCachedObjects;
  27274. }
  27275. // remove & forget
  27276. uncache() {
  27277. const objects = this._objects,
  27278. indicesByUUID = this._indicesByUUID,
  27279. bindings = this._bindings,
  27280. nBindings = bindings.length;
  27281. let nCachedObjects = this.nCachedObjects_,
  27282. nObjects = objects.length;
  27283. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27284. const object = arguments[i],
  27285. uuid = object.uuid,
  27286. index = indicesByUUID[uuid];
  27287. if (index !== undefined) {
  27288. delete indicesByUUID[uuid];
  27289. if (index < nCachedObjects) {
  27290. // object is cached, shrink the CACHED region
  27291. const firstActiveIndex = --nCachedObjects,
  27292. lastCachedObject = objects[firstActiveIndex],
  27293. lastIndex = --nObjects,
  27294. lastObject = objects[lastIndex];
  27295. // last cached object takes this object's place
  27296. indicesByUUID[lastCachedObject.uuid] = index;
  27297. objects[index] = lastCachedObject;
  27298. // last object goes to the activated slot and pop
  27299. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  27300. objects[firstActiveIndex] = lastObject;
  27301. objects.pop();
  27302. // accounting is done, now do the same for all bindings
  27303. for (let j = 0, m = nBindings; j !== m; ++j) {
  27304. const bindingsForPath = bindings[j],
  27305. lastCached = bindingsForPath[firstActiveIndex],
  27306. last = bindingsForPath[lastIndex];
  27307. bindingsForPath[index] = lastCached;
  27308. bindingsForPath[firstActiveIndex] = last;
  27309. bindingsForPath.pop();
  27310. }
  27311. } else {
  27312. // object is active, just swap with the last and pop
  27313. const lastIndex = --nObjects,
  27314. lastObject = objects[lastIndex];
  27315. if (lastIndex > 0) {
  27316. indicesByUUID[lastObject.uuid] = index;
  27317. }
  27318. objects[index] = lastObject;
  27319. objects.pop();
  27320. // accounting is done, now do the same for all bindings
  27321. for (let j = 0, m = nBindings; j !== m; ++j) {
  27322. const bindingsForPath = bindings[j];
  27323. bindingsForPath[index] = bindingsForPath[lastIndex];
  27324. bindingsForPath.pop();
  27325. }
  27326. } // cached or active
  27327. } // if object is known
  27328. } // for arguments
  27329. this.nCachedObjects_ = nCachedObjects;
  27330. }
  27331. // Internal interface used by befriended PropertyBinding.Composite:
  27332. subscribe_(path, parsedPath) {
  27333. // returns an array of bindings for the given path that is changed
  27334. // according to the contained objects in the group
  27335. const indicesByPath = this._bindingsIndicesByPath;
  27336. let index = indicesByPath[path];
  27337. const bindings = this._bindings;
  27338. if (index !== undefined) return bindings[index];
  27339. const paths = this._paths,
  27340. parsedPaths = this._parsedPaths,
  27341. objects = this._objects,
  27342. nObjects = objects.length,
  27343. nCachedObjects = this.nCachedObjects_,
  27344. bindingsForPath = new Array(nObjects);
  27345. index = bindings.length;
  27346. indicesByPath[path] = index;
  27347. paths.push(path);
  27348. parsedPaths.push(parsedPath);
  27349. bindings.push(bindingsForPath);
  27350. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  27351. const object = objects[i];
  27352. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  27353. }
  27354. return bindingsForPath;
  27355. }
  27356. unsubscribe_(path) {
  27357. // tells the group to forget about a property path and no longer
  27358. // update the array previously obtained with 'subscribe_'
  27359. const indicesByPath = this._bindingsIndicesByPath,
  27360. index = indicesByPath[path];
  27361. if (index !== undefined) {
  27362. const paths = this._paths,
  27363. parsedPaths = this._parsedPaths,
  27364. bindings = this._bindings,
  27365. lastBindingsIndex = bindings.length - 1,
  27366. lastBindings = bindings[lastBindingsIndex],
  27367. lastBindingsPath = path[lastBindingsIndex];
  27368. indicesByPath[lastBindingsPath] = index;
  27369. bindings[index] = lastBindings;
  27370. bindings.pop();
  27371. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  27372. parsedPaths.pop();
  27373. paths[index] = paths[lastBindingsIndex];
  27374. paths.pop();
  27375. }
  27376. }
  27377. }
  27378. class AnimationAction {
  27379. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  27380. this._mixer = mixer;
  27381. this._clip = clip;
  27382. this._localRoot = localRoot;
  27383. this.blendMode = blendMode;
  27384. const tracks = clip.tracks,
  27385. nTracks = tracks.length,
  27386. interpolants = new Array(nTracks);
  27387. const interpolantSettings = {
  27388. endingStart: ZeroCurvatureEnding,
  27389. endingEnd: ZeroCurvatureEnding
  27390. };
  27391. for (let i = 0; i !== nTracks; ++i) {
  27392. const interpolant = tracks[i].createInterpolant(null);
  27393. interpolants[i] = interpolant;
  27394. interpolant.settings = interpolantSettings;
  27395. }
  27396. this._interpolantSettings = interpolantSettings;
  27397. this._interpolants = interpolants; // bound by the mixer
  27398. // inside: PropertyMixer (managed by the mixer)
  27399. this._propertyBindings = new Array(nTracks);
  27400. this._cacheIndex = null; // for the memory manager
  27401. this._byClipCacheIndex = null; // for the memory manager
  27402. this._timeScaleInterpolant = null;
  27403. this._weightInterpolant = null;
  27404. this.loop = LoopRepeat;
  27405. this._loopCount = -1;
  27406. // global mixer time when the action is to be started
  27407. // it's set back to 'null' upon start of the action
  27408. this._startTime = null;
  27409. // scaled local time of the action
  27410. // gets clamped or wrapped to 0..clip.duration according to loop
  27411. this.time = 0;
  27412. this.timeScale = 1;
  27413. this._effectiveTimeScale = 1;
  27414. this.weight = 1;
  27415. this._effectiveWeight = 1;
  27416. this.repetitions = Infinity; // no. of repetitions when looping
  27417. this.paused = false; // true -> zero effective time scale
  27418. this.enabled = true; // false -> zero effective weight
  27419. this.clampWhenFinished = false; // keep feeding the last frame?
  27420. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  27421. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  27422. }
  27423. // State & Scheduling
  27424. play() {
  27425. this._mixer._activateAction(this);
  27426. return this;
  27427. }
  27428. stop() {
  27429. this._mixer._deactivateAction(this);
  27430. return this.reset();
  27431. }
  27432. reset() {
  27433. this.paused = false;
  27434. this.enabled = true;
  27435. this.time = 0; // restart clip
  27436. this._loopCount = -1; // forget previous loops
  27437. this._startTime = null; // forget scheduling
  27438. return this.stopFading().stopWarping();
  27439. }
  27440. isRunning() {
  27441. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  27442. }
  27443. // return true when play has been called
  27444. isScheduled() {
  27445. return this._mixer._isActiveAction(this);
  27446. }
  27447. startAt(time) {
  27448. this._startTime = time;
  27449. return this;
  27450. }
  27451. setLoop(mode, repetitions) {
  27452. this.loop = mode;
  27453. this.repetitions = repetitions;
  27454. return this;
  27455. }
  27456. // Weight
  27457. // set the weight stopping any scheduled fading
  27458. // although .enabled = false yields an effective weight of zero, this
  27459. // method does *not* change .enabled, because it would be confusing
  27460. setEffectiveWeight(weight) {
  27461. this.weight = weight;
  27462. // note: same logic as when updated at runtime
  27463. this._effectiveWeight = this.enabled ? weight : 0;
  27464. return this.stopFading();
  27465. }
  27466. // return the weight considering fading and .enabled
  27467. getEffectiveWeight() {
  27468. return this._effectiveWeight;
  27469. }
  27470. fadeIn(duration) {
  27471. return this._scheduleFading(duration, 0, 1);
  27472. }
  27473. fadeOut(duration) {
  27474. return this._scheduleFading(duration, 1, 0);
  27475. }
  27476. crossFadeFrom(fadeOutAction, duration, warp) {
  27477. fadeOutAction.fadeOut(duration);
  27478. this.fadeIn(duration);
  27479. if (warp) {
  27480. const fadeInDuration = this._clip.duration,
  27481. fadeOutDuration = fadeOutAction._clip.duration,
  27482. startEndRatio = fadeOutDuration / fadeInDuration,
  27483. endStartRatio = fadeInDuration / fadeOutDuration;
  27484. fadeOutAction.warp(1.0, startEndRatio, duration);
  27485. this.warp(endStartRatio, 1.0, duration);
  27486. }
  27487. return this;
  27488. }
  27489. crossFadeTo(fadeInAction, duration, warp) {
  27490. return fadeInAction.crossFadeFrom(this, duration, warp);
  27491. }
  27492. stopFading() {
  27493. const weightInterpolant = this._weightInterpolant;
  27494. if (weightInterpolant !== null) {
  27495. this._weightInterpolant = null;
  27496. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27497. }
  27498. return this;
  27499. }
  27500. // Time Scale Control
  27501. // set the time scale stopping any scheduled warping
  27502. // although .paused = true yields an effective time scale of zero, this
  27503. // method does *not* change .paused, because it would be confusing
  27504. setEffectiveTimeScale(timeScale) {
  27505. this.timeScale = timeScale;
  27506. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27507. return this.stopWarping();
  27508. }
  27509. // return the time scale considering warping and .paused
  27510. getEffectiveTimeScale() {
  27511. return this._effectiveTimeScale;
  27512. }
  27513. setDuration(duration) {
  27514. this.timeScale = this._clip.duration / duration;
  27515. return this.stopWarping();
  27516. }
  27517. syncWith(action) {
  27518. this.time = action.time;
  27519. this.timeScale = action.timeScale;
  27520. return this.stopWarping();
  27521. }
  27522. halt(duration) {
  27523. return this.warp(this._effectiveTimeScale, 0, duration);
  27524. }
  27525. warp(startTimeScale, endTimeScale, duration) {
  27526. const mixer = this._mixer,
  27527. now = mixer.time,
  27528. timeScale = this.timeScale;
  27529. let interpolant = this._timeScaleInterpolant;
  27530. if (interpolant === null) {
  27531. interpolant = mixer._lendControlInterpolant();
  27532. this._timeScaleInterpolant = interpolant;
  27533. }
  27534. const times = interpolant.parameterPositions,
  27535. values = interpolant.sampleValues;
  27536. times[0] = now;
  27537. times[1] = now + duration;
  27538. values[0] = startTimeScale / timeScale;
  27539. values[1] = endTimeScale / timeScale;
  27540. return this;
  27541. }
  27542. stopWarping() {
  27543. const timeScaleInterpolant = this._timeScaleInterpolant;
  27544. if (timeScaleInterpolant !== null) {
  27545. this._timeScaleInterpolant = null;
  27546. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27547. }
  27548. return this;
  27549. }
  27550. // Object Accessors
  27551. getMixer() {
  27552. return this._mixer;
  27553. }
  27554. getClip() {
  27555. return this._clip;
  27556. }
  27557. getRoot() {
  27558. return this._localRoot || this._mixer._root;
  27559. }
  27560. // Interna
  27561. _update(time, deltaTime, timeDirection, accuIndex) {
  27562. // called by the mixer
  27563. if (!this.enabled) {
  27564. // call ._updateWeight() to update ._effectiveWeight
  27565. this._updateWeight(time);
  27566. return;
  27567. }
  27568. const startTime = this._startTime;
  27569. if (startTime !== null) {
  27570. // check for scheduled start of action
  27571. const timeRunning = (time - startTime) * timeDirection;
  27572. if (timeRunning < 0 || timeDirection === 0) {
  27573. deltaTime = 0;
  27574. } else {
  27575. this._startTime = null; // unschedule
  27576. deltaTime = timeDirection * timeRunning;
  27577. }
  27578. }
  27579. // apply time scale and advance time
  27580. deltaTime *= this._updateTimeScale(time);
  27581. const clipTime = this._updateTime(deltaTime);
  27582. // note: _updateTime may disable the action resulting in
  27583. // an effective weight of 0
  27584. const weight = this._updateWeight(time);
  27585. if (weight > 0) {
  27586. const interpolants = this._interpolants;
  27587. const propertyMixers = this._propertyBindings;
  27588. switch (this.blendMode) {
  27589. case AdditiveAnimationBlendMode:
  27590. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  27591. interpolants[j].evaluate(clipTime);
  27592. propertyMixers[j].accumulateAdditive(weight);
  27593. }
  27594. break;
  27595. case NormalAnimationBlendMode:
  27596. default:
  27597. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  27598. interpolants[j].evaluate(clipTime);
  27599. propertyMixers[j].accumulate(accuIndex, weight);
  27600. }
  27601. }
  27602. }
  27603. }
  27604. _updateWeight(time) {
  27605. let weight = 0;
  27606. if (this.enabled) {
  27607. weight = this.weight;
  27608. const interpolant = this._weightInterpolant;
  27609. if (interpolant !== null) {
  27610. const interpolantValue = interpolant.evaluate(time)[0];
  27611. weight *= interpolantValue;
  27612. if (time > interpolant.parameterPositions[1]) {
  27613. this.stopFading();
  27614. if (interpolantValue === 0) {
  27615. // faded out, disable
  27616. this.enabled = false;
  27617. }
  27618. }
  27619. }
  27620. }
  27621. this._effectiveWeight = weight;
  27622. return weight;
  27623. }
  27624. _updateTimeScale(time) {
  27625. let timeScale = 0;
  27626. if (!this.paused) {
  27627. timeScale = this.timeScale;
  27628. const interpolant = this._timeScaleInterpolant;
  27629. if (interpolant !== null) {
  27630. const interpolantValue = interpolant.evaluate(time)[0];
  27631. timeScale *= interpolantValue;
  27632. if (time > interpolant.parameterPositions[1]) {
  27633. this.stopWarping();
  27634. if (timeScale === 0) {
  27635. // motion has halted, pause
  27636. this.paused = true;
  27637. } else {
  27638. // warp done - apply final time scale
  27639. this.timeScale = timeScale;
  27640. }
  27641. }
  27642. }
  27643. }
  27644. this._effectiveTimeScale = timeScale;
  27645. return timeScale;
  27646. }
  27647. _updateTime(deltaTime) {
  27648. const duration = this._clip.duration;
  27649. const loop = this.loop;
  27650. let time = this.time + deltaTime;
  27651. let loopCount = this._loopCount;
  27652. const pingPong = loop === LoopPingPong;
  27653. if (deltaTime === 0) {
  27654. if (loopCount === -1) return time;
  27655. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27656. }
  27657. if (loop === LoopOnce) {
  27658. if (loopCount === -1) {
  27659. // just started
  27660. this._loopCount = 0;
  27661. this._setEndings(true, true, false);
  27662. }
  27663. handle_stop: {
  27664. if (time >= duration) {
  27665. time = duration;
  27666. } else if (time < 0) {
  27667. time = 0;
  27668. } else {
  27669. this.time = time;
  27670. break handle_stop;
  27671. }
  27672. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27673. this.time = time;
  27674. this._mixer.dispatchEvent({
  27675. type: 'finished',
  27676. action: this,
  27677. direction: deltaTime < 0 ? -1 : 1
  27678. });
  27679. }
  27680. } else {
  27681. // repetitive Repeat or PingPong
  27682. if (loopCount === -1) {
  27683. // just started
  27684. if (deltaTime >= 0) {
  27685. loopCount = 0;
  27686. this._setEndings(true, this.repetitions === 0, pingPong);
  27687. } else {
  27688. // when looping in reverse direction, the initial
  27689. // transition through zero counts as a repetition,
  27690. // so leave loopCount at -1
  27691. this._setEndings(this.repetitions === 0, true, pingPong);
  27692. }
  27693. }
  27694. if (time >= duration || time < 0) {
  27695. // wrap around
  27696. const loopDelta = Math.floor(time / duration); // signed
  27697. time -= duration * loopDelta;
  27698. loopCount += Math.abs(loopDelta);
  27699. const pending = this.repetitions - loopCount;
  27700. if (pending <= 0) {
  27701. // have to stop (switch state, clamp time, fire event)
  27702. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27703. time = deltaTime > 0 ? duration : 0;
  27704. this.time = time;
  27705. this._mixer.dispatchEvent({
  27706. type: 'finished',
  27707. action: this,
  27708. direction: deltaTime > 0 ? 1 : -1
  27709. });
  27710. } else {
  27711. // keep running
  27712. if (pending === 1) {
  27713. // entering the last round
  27714. const atStart = deltaTime < 0;
  27715. this._setEndings(atStart, !atStart, pingPong);
  27716. } else {
  27717. this._setEndings(false, false, pingPong);
  27718. }
  27719. this._loopCount = loopCount;
  27720. this.time = time;
  27721. this._mixer.dispatchEvent({
  27722. type: 'loop',
  27723. action: this,
  27724. loopDelta: loopDelta
  27725. });
  27726. }
  27727. } else {
  27728. this.time = time;
  27729. }
  27730. if (pingPong && (loopCount & 1) === 1) {
  27731. // invert time for the "pong round"
  27732. return duration - time;
  27733. }
  27734. }
  27735. return time;
  27736. }
  27737. _setEndings(atStart, atEnd, pingPong) {
  27738. const settings = this._interpolantSettings;
  27739. if (pingPong) {
  27740. settings.endingStart = ZeroSlopeEnding;
  27741. settings.endingEnd = ZeroSlopeEnding;
  27742. } else {
  27743. // assuming for LoopOnce atStart == atEnd == true
  27744. if (atStart) {
  27745. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27746. } else {
  27747. settings.endingStart = WrapAroundEnding;
  27748. }
  27749. if (atEnd) {
  27750. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27751. } else {
  27752. settings.endingEnd = WrapAroundEnding;
  27753. }
  27754. }
  27755. }
  27756. _scheduleFading(duration, weightNow, weightThen) {
  27757. const mixer = this._mixer,
  27758. now = mixer.time;
  27759. let interpolant = this._weightInterpolant;
  27760. if (interpolant === null) {
  27761. interpolant = mixer._lendControlInterpolant();
  27762. this._weightInterpolant = interpolant;
  27763. }
  27764. const times = interpolant.parameterPositions,
  27765. values = interpolant.sampleValues;
  27766. times[0] = now;
  27767. values[0] = weightNow;
  27768. times[1] = now + duration;
  27769. values[1] = weightThen;
  27770. return this;
  27771. }
  27772. }
  27773. const _controlInterpolantsResultBuffer = new Float32Array(1);
  27774. class AnimationMixer extends EventDispatcher {
  27775. constructor(root) {
  27776. super();
  27777. this._root = root;
  27778. this._initMemoryManager();
  27779. this._accuIndex = 0;
  27780. this.time = 0;
  27781. this.timeScale = 1.0;
  27782. }
  27783. _bindAction(action, prototypeAction) {
  27784. const root = action._localRoot || this._root,
  27785. tracks = action._clip.tracks,
  27786. nTracks = tracks.length,
  27787. bindings = action._propertyBindings,
  27788. interpolants = action._interpolants,
  27789. rootUuid = root.uuid,
  27790. bindingsByRoot = this._bindingsByRootAndName;
  27791. let bindingsByName = bindingsByRoot[rootUuid];
  27792. if (bindingsByName === undefined) {
  27793. bindingsByName = {};
  27794. bindingsByRoot[rootUuid] = bindingsByName;
  27795. }
  27796. for (let i = 0; i !== nTracks; ++i) {
  27797. const track = tracks[i],
  27798. trackName = track.name;
  27799. let binding = bindingsByName[trackName];
  27800. if (binding !== undefined) {
  27801. ++binding.referenceCount;
  27802. bindings[i] = binding;
  27803. } else {
  27804. binding = bindings[i];
  27805. if (binding !== undefined) {
  27806. // existing binding, make sure the cache knows
  27807. if (binding._cacheIndex === null) {
  27808. ++binding.referenceCount;
  27809. this._addInactiveBinding(binding, rootUuid, trackName);
  27810. }
  27811. continue;
  27812. }
  27813. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27814. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27815. ++binding.referenceCount;
  27816. this._addInactiveBinding(binding, rootUuid, trackName);
  27817. bindings[i] = binding;
  27818. }
  27819. interpolants[i].resultBuffer = binding.buffer;
  27820. }
  27821. }
  27822. _activateAction(action) {
  27823. if (!this._isActiveAction(action)) {
  27824. if (action._cacheIndex === null) {
  27825. // this action has been forgotten by the cache, but the user
  27826. // appears to be still using it -> rebind
  27827. const rootUuid = (action._localRoot || this._root).uuid,
  27828. clipUuid = action._clip.uuid,
  27829. actionsForClip = this._actionsByClip[clipUuid];
  27830. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27831. this._addInactiveAction(action, clipUuid, rootUuid);
  27832. }
  27833. const bindings = action._propertyBindings;
  27834. // increment reference counts / sort out state
  27835. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27836. const binding = bindings[i];
  27837. if (binding.useCount++ === 0) {
  27838. this._lendBinding(binding);
  27839. binding.saveOriginalState();
  27840. }
  27841. }
  27842. this._lendAction(action);
  27843. }
  27844. }
  27845. _deactivateAction(action) {
  27846. if (this._isActiveAction(action)) {
  27847. const bindings = action._propertyBindings;
  27848. // decrement reference counts / sort out state
  27849. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27850. const binding = bindings[i];
  27851. if (--binding.useCount === 0) {
  27852. binding.restoreOriginalState();
  27853. this._takeBackBinding(binding);
  27854. }
  27855. }
  27856. this._takeBackAction(action);
  27857. }
  27858. }
  27859. // Memory manager
  27860. _initMemoryManager() {
  27861. this._actions = []; // 'nActiveActions' followed by inactive ones
  27862. this._nActiveActions = 0;
  27863. this._actionsByClip = {};
  27864. // inside:
  27865. // {
  27866. // knownActions: Array< AnimationAction > - used as prototypes
  27867. // actionByRoot: AnimationAction - lookup
  27868. // }
  27869. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27870. this._nActiveBindings = 0;
  27871. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27872. this._controlInterpolants = []; // same game as above
  27873. this._nActiveControlInterpolants = 0;
  27874. const scope = this;
  27875. this.stats = {
  27876. actions: {
  27877. get total() {
  27878. return scope._actions.length;
  27879. },
  27880. get inUse() {
  27881. return scope._nActiveActions;
  27882. }
  27883. },
  27884. bindings: {
  27885. get total() {
  27886. return scope._bindings.length;
  27887. },
  27888. get inUse() {
  27889. return scope._nActiveBindings;
  27890. }
  27891. },
  27892. controlInterpolants: {
  27893. get total() {
  27894. return scope._controlInterpolants.length;
  27895. },
  27896. get inUse() {
  27897. return scope._nActiveControlInterpolants;
  27898. }
  27899. }
  27900. };
  27901. }
  27902. // Memory management for AnimationAction objects
  27903. _isActiveAction(action) {
  27904. const index = action._cacheIndex;
  27905. return index !== null && index < this._nActiveActions;
  27906. }
  27907. _addInactiveAction(action, clipUuid, rootUuid) {
  27908. const actions = this._actions,
  27909. actionsByClip = this._actionsByClip;
  27910. let actionsForClip = actionsByClip[clipUuid];
  27911. if (actionsForClip === undefined) {
  27912. actionsForClip = {
  27913. knownActions: [action],
  27914. actionByRoot: {}
  27915. };
  27916. action._byClipCacheIndex = 0;
  27917. actionsByClip[clipUuid] = actionsForClip;
  27918. } else {
  27919. const knownActions = actionsForClip.knownActions;
  27920. action._byClipCacheIndex = knownActions.length;
  27921. knownActions.push(action);
  27922. }
  27923. action._cacheIndex = actions.length;
  27924. actions.push(action);
  27925. actionsForClip.actionByRoot[rootUuid] = action;
  27926. }
  27927. _removeInactiveAction(action) {
  27928. const actions = this._actions,
  27929. lastInactiveAction = actions[actions.length - 1],
  27930. cacheIndex = action._cacheIndex;
  27931. lastInactiveAction._cacheIndex = cacheIndex;
  27932. actions[cacheIndex] = lastInactiveAction;
  27933. actions.pop();
  27934. action._cacheIndex = null;
  27935. const clipUuid = action._clip.uuid,
  27936. actionsByClip = this._actionsByClip,
  27937. actionsForClip = actionsByClip[clipUuid],
  27938. knownActionsForClip = actionsForClip.knownActions,
  27939. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27940. byClipCacheIndex = action._byClipCacheIndex;
  27941. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27942. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27943. knownActionsForClip.pop();
  27944. action._byClipCacheIndex = null;
  27945. const actionByRoot = actionsForClip.actionByRoot,
  27946. rootUuid = (action._localRoot || this._root).uuid;
  27947. delete actionByRoot[rootUuid];
  27948. if (knownActionsForClip.length === 0) {
  27949. delete actionsByClip[clipUuid];
  27950. }
  27951. this._removeInactiveBindingsForAction(action);
  27952. }
  27953. _removeInactiveBindingsForAction(action) {
  27954. const bindings = action._propertyBindings;
  27955. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27956. const binding = bindings[i];
  27957. if (--binding.referenceCount === 0) {
  27958. this._removeInactiveBinding(binding);
  27959. }
  27960. }
  27961. }
  27962. _lendAction(action) {
  27963. // [ active actions | inactive actions ]
  27964. // [ active actions >| inactive actions ]
  27965. // s a
  27966. // <-swap->
  27967. // a s
  27968. const actions = this._actions,
  27969. prevIndex = action._cacheIndex,
  27970. lastActiveIndex = this._nActiveActions++,
  27971. firstInactiveAction = actions[lastActiveIndex];
  27972. action._cacheIndex = lastActiveIndex;
  27973. actions[lastActiveIndex] = action;
  27974. firstInactiveAction._cacheIndex = prevIndex;
  27975. actions[prevIndex] = firstInactiveAction;
  27976. }
  27977. _takeBackAction(action) {
  27978. // [ active actions | inactive actions ]
  27979. // [ active actions |< inactive actions ]
  27980. // a s
  27981. // <-swap->
  27982. // s a
  27983. const actions = this._actions,
  27984. prevIndex = action._cacheIndex,
  27985. firstInactiveIndex = --this._nActiveActions,
  27986. lastActiveAction = actions[firstInactiveIndex];
  27987. action._cacheIndex = firstInactiveIndex;
  27988. actions[firstInactiveIndex] = action;
  27989. lastActiveAction._cacheIndex = prevIndex;
  27990. actions[prevIndex] = lastActiveAction;
  27991. }
  27992. // Memory management for PropertyMixer objects
  27993. _addInactiveBinding(binding, rootUuid, trackName) {
  27994. const bindingsByRoot = this._bindingsByRootAndName,
  27995. bindings = this._bindings;
  27996. let bindingByName = bindingsByRoot[rootUuid];
  27997. if (bindingByName === undefined) {
  27998. bindingByName = {};
  27999. bindingsByRoot[rootUuid] = bindingByName;
  28000. }
  28001. bindingByName[trackName] = binding;
  28002. binding._cacheIndex = bindings.length;
  28003. bindings.push(binding);
  28004. }
  28005. _removeInactiveBinding(binding) {
  28006. const bindings = this._bindings,
  28007. propBinding = binding.binding,
  28008. rootUuid = propBinding.rootNode.uuid,
  28009. trackName = propBinding.path,
  28010. bindingsByRoot = this._bindingsByRootAndName,
  28011. bindingByName = bindingsByRoot[rootUuid],
  28012. lastInactiveBinding = bindings[bindings.length - 1],
  28013. cacheIndex = binding._cacheIndex;
  28014. lastInactiveBinding._cacheIndex = cacheIndex;
  28015. bindings[cacheIndex] = lastInactiveBinding;
  28016. bindings.pop();
  28017. delete bindingByName[trackName];
  28018. if (Object.keys(bindingByName).length === 0) {
  28019. delete bindingsByRoot[rootUuid];
  28020. }
  28021. }
  28022. _lendBinding(binding) {
  28023. const bindings = this._bindings,
  28024. prevIndex = binding._cacheIndex,
  28025. lastActiveIndex = this._nActiveBindings++,
  28026. firstInactiveBinding = bindings[lastActiveIndex];
  28027. binding._cacheIndex = lastActiveIndex;
  28028. bindings[lastActiveIndex] = binding;
  28029. firstInactiveBinding._cacheIndex = prevIndex;
  28030. bindings[prevIndex] = firstInactiveBinding;
  28031. }
  28032. _takeBackBinding(binding) {
  28033. const bindings = this._bindings,
  28034. prevIndex = binding._cacheIndex,
  28035. firstInactiveIndex = --this._nActiveBindings,
  28036. lastActiveBinding = bindings[firstInactiveIndex];
  28037. binding._cacheIndex = firstInactiveIndex;
  28038. bindings[firstInactiveIndex] = binding;
  28039. lastActiveBinding._cacheIndex = prevIndex;
  28040. bindings[prevIndex] = lastActiveBinding;
  28041. }
  28042. // Memory management of Interpolants for weight and time scale
  28043. _lendControlInterpolant() {
  28044. const interpolants = this._controlInterpolants,
  28045. lastActiveIndex = this._nActiveControlInterpolants++;
  28046. let interpolant = interpolants[lastActiveIndex];
  28047. if (interpolant === undefined) {
  28048. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  28049. interpolant.__cacheIndex = lastActiveIndex;
  28050. interpolants[lastActiveIndex] = interpolant;
  28051. }
  28052. return interpolant;
  28053. }
  28054. _takeBackControlInterpolant(interpolant) {
  28055. const interpolants = this._controlInterpolants,
  28056. prevIndex = interpolant.__cacheIndex,
  28057. firstInactiveIndex = --this._nActiveControlInterpolants,
  28058. lastActiveInterpolant = interpolants[firstInactiveIndex];
  28059. interpolant.__cacheIndex = firstInactiveIndex;
  28060. interpolants[firstInactiveIndex] = interpolant;
  28061. lastActiveInterpolant.__cacheIndex = prevIndex;
  28062. interpolants[prevIndex] = lastActiveInterpolant;
  28063. }
  28064. // return an action for a clip optionally using a custom root target
  28065. // object (this method allocates a lot of dynamic memory in case a
  28066. // previously unknown clip/root combination is specified)
  28067. clipAction(clip, optionalRoot, blendMode) {
  28068. const root = optionalRoot || this._root,
  28069. rootUuid = root.uuid;
  28070. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  28071. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28072. const actionsForClip = this._actionsByClip[clipUuid];
  28073. let prototypeAction = null;
  28074. if (blendMode === undefined) {
  28075. if (clipObject !== null) {
  28076. blendMode = clipObject.blendMode;
  28077. } else {
  28078. blendMode = NormalAnimationBlendMode;
  28079. }
  28080. }
  28081. if (actionsForClip !== undefined) {
  28082. const existingAction = actionsForClip.actionByRoot[rootUuid];
  28083. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  28084. return existingAction;
  28085. }
  28086. // we know the clip, so we don't have to parse all
  28087. // the bindings again but can just copy
  28088. prototypeAction = actionsForClip.knownActions[0];
  28089. // also, take the clip from the prototype action
  28090. if (clipObject === null) clipObject = prototypeAction._clip;
  28091. }
  28092. // clip must be known when specified via string
  28093. if (clipObject === null) return null;
  28094. // allocate all resources required to run it
  28095. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  28096. this._bindAction(newAction, prototypeAction);
  28097. // and make the action known to the memory manager
  28098. this._addInactiveAction(newAction, clipUuid, rootUuid);
  28099. return newAction;
  28100. }
  28101. // get an existing action
  28102. existingAction(clip, optionalRoot) {
  28103. const root = optionalRoot || this._root,
  28104. rootUuid = root.uuid,
  28105. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  28106. clipUuid = clipObject ? clipObject.uuid : clip,
  28107. actionsForClip = this._actionsByClip[clipUuid];
  28108. if (actionsForClip !== undefined) {
  28109. return actionsForClip.actionByRoot[rootUuid] || null;
  28110. }
  28111. return null;
  28112. }
  28113. // deactivates all previously scheduled actions
  28114. stopAllAction() {
  28115. const actions = this._actions,
  28116. nActions = this._nActiveActions;
  28117. for (let i = nActions - 1; i >= 0; --i) {
  28118. actions[i].stop();
  28119. }
  28120. return this;
  28121. }
  28122. // advance the time and update apply the animation
  28123. update(deltaTime) {
  28124. deltaTime *= this.timeScale;
  28125. const actions = this._actions,
  28126. nActions = this._nActiveActions,
  28127. time = this.time += deltaTime,
  28128. timeDirection = Math.sign(deltaTime),
  28129. accuIndex = this._accuIndex ^= 1;
  28130. // run active actions
  28131. for (let i = 0; i !== nActions; ++i) {
  28132. const action = actions[i];
  28133. action._update(time, deltaTime, timeDirection, accuIndex);
  28134. }
  28135. // update scene graph
  28136. const bindings = this._bindings,
  28137. nBindings = this._nActiveBindings;
  28138. for (let i = 0; i !== nBindings; ++i) {
  28139. bindings[i].apply(accuIndex);
  28140. }
  28141. return this;
  28142. }
  28143. // Allows you to seek to a specific time in an animation.
  28144. setTime(timeInSeconds) {
  28145. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28146. for (let i = 0; i < this._actions.length; i++) {
  28147. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28148. }
  28149. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  28150. }
  28151. // return this mixer's root target object
  28152. getRoot() {
  28153. return this._root;
  28154. }
  28155. // free all resources specific to a particular clip
  28156. uncacheClip(clip) {
  28157. const actions = this._actions,
  28158. clipUuid = clip.uuid,
  28159. actionsByClip = this._actionsByClip,
  28160. actionsForClip = actionsByClip[clipUuid];
  28161. if (actionsForClip !== undefined) {
  28162. // note: just calling _removeInactiveAction would mess up the
  28163. // iteration state and also require updating the state we can
  28164. // just throw away
  28165. const actionsToRemove = actionsForClip.knownActions;
  28166. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  28167. const action = actionsToRemove[i];
  28168. this._deactivateAction(action);
  28169. const cacheIndex = action._cacheIndex,
  28170. lastInactiveAction = actions[actions.length - 1];
  28171. action._cacheIndex = null;
  28172. action._byClipCacheIndex = null;
  28173. lastInactiveAction._cacheIndex = cacheIndex;
  28174. actions[cacheIndex] = lastInactiveAction;
  28175. actions.pop();
  28176. this._removeInactiveBindingsForAction(action);
  28177. }
  28178. delete actionsByClip[clipUuid];
  28179. }
  28180. }
  28181. // free all resources specific to a particular root target object
  28182. uncacheRoot(root) {
  28183. const rootUuid = root.uuid,
  28184. actionsByClip = this._actionsByClip;
  28185. for (const clipUuid in actionsByClip) {
  28186. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  28187. action = actionByRoot[rootUuid];
  28188. if (action !== undefined) {
  28189. this._deactivateAction(action);
  28190. this._removeInactiveAction(action);
  28191. }
  28192. }
  28193. const bindingsByRoot = this._bindingsByRootAndName,
  28194. bindingByName = bindingsByRoot[rootUuid];
  28195. if (bindingByName !== undefined) {
  28196. for (const trackName in bindingByName) {
  28197. const binding = bindingByName[trackName];
  28198. binding.restoreOriginalState();
  28199. this._removeInactiveBinding(binding);
  28200. }
  28201. }
  28202. }
  28203. // remove a targeted clip from the cache
  28204. uncacheAction(clip, optionalRoot) {
  28205. const action = this.existingAction(clip, optionalRoot);
  28206. if (action !== null) {
  28207. this._deactivateAction(action);
  28208. this._removeInactiveAction(action);
  28209. }
  28210. }
  28211. }
  28212. class Uniform {
  28213. constructor(value) {
  28214. this.value = value;
  28215. }
  28216. clone() {
  28217. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  28218. }
  28219. }
  28220. let id = 0;
  28221. class UniformsGroup extends EventDispatcher {
  28222. constructor() {
  28223. super();
  28224. this.isUniformsGroup = true;
  28225. Object.defineProperty(this, 'id', {
  28226. value: id++
  28227. });
  28228. this.name = '';
  28229. this.usage = StaticDrawUsage;
  28230. this.uniforms = [];
  28231. }
  28232. add(uniform) {
  28233. this.uniforms.push(uniform);
  28234. return this;
  28235. }
  28236. remove(uniform) {
  28237. const index = this.uniforms.indexOf(uniform);
  28238. if (index !== -1) this.uniforms.splice(index, 1);
  28239. return this;
  28240. }
  28241. setName(name) {
  28242. this.name = name;
  28243. return this;
  28244. }
  28245. setUsage(value) {
  28246. this.usage = value;
  28247. return this;
  28248. }
  28249. dispose() {
  28250. this.dispatchEvent({
  28251. type: 'dispose'
  28252. });
  28253. return this;
  28254. }
  28255. copy(source) {
  28256. this.name = source.name;
  28257. this.usage = source.usage;
  28258. const uniformsSource = source.uniforms;
  28259. this.uniforms.length = 0;
  28260. for (let i = 0, l = uniformsSource.length; i < l; i++) {
  28261. this.uniforms.push(uniformsSource[i].clone());
  28262. }
  28263. return this;
  28264. }
  28265. clone() {
  28266. return new this.constructor().copy(this);
  28267. }
  28268. }
  28269. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28270. constructor(array, stride, meshPerAttribute = 1) {
  28271. super(array, stride);
  28272. this.isInstancedInterleavedBuffer = true;
  28273. this.meshPerAttribute = meshPerAttribute;
  28274. }
  28275. copy(source) {
  28276. super.copy(source);
  28277. this.meshPerAttribute = source.meshPerAttribute;
  28278. return this;
  28279. }
  28280. clone(data) {
  28281. const ib = super.clone(data);
  28282. ib.meshPerAttribute = this.meshPerAttribute;
  28283. return ib;
  28284. }
  28285. toJSON(data) {
  28286. const json = super.toJSON(data);
  28287. json.isInstancedInterleavedBuffer = true;
  28288. json.meshPerAttribute = this.meshPerAttribute;
  28289. return json;
  28290. }
  28291. }
  28292. class GLBufferAttribute {
  28293. constructor(buffer, type, itemSize, elementSize, count) {
  28294. this.isGLBufferAttribute = true;
  28295. this.buffer = buffer;
  28296. this.type = type;
  28297. this.itemSize = itemSize;
  28298. this.elementSize = elementSize;
  28299. this.count = count;
  28300. this.version = 0;
  28301. }
  28302. set needsUpdate(value) {
  28303. if (value === true) this.version++;
  28304. }
  28305. setBuffer(buffer) {
  28306. this.buffer = buffer;
  28307. return this;
  28308. }
  28309. setType(type, elementSize) {
  28310. this.type = type;
  28311. this.elementSize = elementSize;
  28312. return this;
  28313. }
  28314. setItemSize(itemSize) {
  28315. this.itemSize = itemSize;
  28316. return this;
  28317. }
  28318. setCount(count) {
  28319. this.count = count;
  28320. return this;
  28321. }
  28322. }
  28323. class Raycaster {
  28324. constructor(origin, direction, near = 0, far = Infinity) {
  28325. this.ray = new Ray(origin, direction);
  28326. // direction is assumed to be normalized (for accurate distance calculations)
  28327. this.near = near;
  28328. this.far = far;
  28329. this.camera = null;
  28330. this.layers = new Layers();
  28331. this.params = {
  28332. Mesh: {},
  28333. Line: {
  28334. threshold: 1
  28335. },
  28336. LOD: {},
  28337. Points: {
  28338. threshold: 1
  28339. },
  28340. Sprite: {}
  28341. };
  28342. }
  28343. set(origin, direction) {
  28344. // direction is assumed to be normalized (for accurate distance calculations)
  28345. this.ray.set(origin, direction);
  28346. }
  28347. setFromCamera(coords, camera) {
  28348. if (camera.isPerspectiveCamera) {
  28349. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  28350. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  28351. this.camera = camera;
  28352. } else if (camera.isOrthographicCamera) {
  28353. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  28354. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  28355. this.camera = camera;
  28356. } else {
  28357. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  28358. }
  28359. }
  28360. intersectObject(object, recursive = true, intersects = []) {
  28361. intersectObject(object, this, intersects, recursive);
  28362. intersects.sort(ascSort);
  28363. return intersects;
  28364. }
  28365. intersectObjects(objects, recursive = true, intersects = []) {
  28366. for (let i = 0, l = objects.length; i < l; i++) {
  28367. intersectObject(objects[i], this, intersects, recursive);
  28368. }
  28369. intersects.sort(ascSort);
  28370. return intersects;
  28371. }
  28372. }
  28373. function ascSort(a, b) {
  28374. return a.distance - b.distance;
  28375. }
  28376. function intersectObject(object, raycaster, intersects, recursive) {
  28377. if (object.layers.test(raycaster.layers)) {
  28378. object.raycast(raycaster, intersects);
  28379. }
  28380. if (recursive === true) {
  28381. const children = object.children;
  28382. for (let i = 0, l = children.length; i < l; i++) {
  28383. intersectObject(children[i], raycaster, intersects, true);
  28384. }
  28385. }
  28386. }
  28387. /**
  28388. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28389. *
  28390. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28391. * The azimuthal angle (theta) is measured from the positive z-axis.
  28392. */
  28393. class Spherical {
  28394. constructor(radius = 1, phi = 0, theta = 0) {
  28395. this.radius = radius;
  28396. this.phi = phi; // polar angle
  28397. this.theta = theta; // azimuthal angle
  28398. return this;
  28399. }
  28400. set(radius, phi, theta) {
  28401. this.radius = radius;
  28402. this.phi = phi;
  28403. this.theta = theta;
  28404. return this;
  28405. }
  28406. copy(other) {
  28407. this.radius = other.radius;
  28408. this.phi = other.phi;
  28409. this.theta = other.theta;
  28410. return this;
  28411. }
  28412. // restrict phi to be between EPS and PI-EPS
  28413. makeSafe() {
  28414. const EPS = 0.000001;
  28415. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  28416. return this;
  28417. }
  28418. setFromVector3(v) {
  28419. return this.setFromCartesianCoords(v.x, v.y, v.z);
  28420. }
  28421. setFromCartesianCoords(x, y, z) {
  28422. this.radius = Math.sqrt(x * x + y * y + z * z);
  28423. if (this.radius === 0) {
  28424. this.theta = 0;
  28425. this.phi = 0;
  28426. } else {
  28427. this.theta = Math.atan2(x, z);
  28428. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  28429. }
  28430. return this;
  28431. }
  28432. clone() {
  28433. return new this.constructor().copy(this);
  28434. }
  28435. }
  28436. /**
  28437. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28438. */
  28439. class Cylindrical {
  28440. constructor(radius = 1, theta = 0, y = 0) {
  28441. this.radius = radius; // distance from the origin to a point in the x-z plane
  28442. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28443. this.y = y; // height above the x-z plane
  28444. return this;
  28445. }
  28446. set(radius, theta, y) {
  28447. this.radius = radius;
  28448. this.theta = theta;
  28449. this.y = y;
  28450. return this;
  28451. }
  28452. copy(other) {
  28453. this.radius = other.radius;
  28454. this.theta = other.theta;
  28455. this.y = other.y;
  28456. return this;
  28457. }
  28458. setFromVector3(v) {
  28459. return this.setFromCartesianCoords(v.x, v.y, v.z);
  28460. }
  28461. setFromCartesianCoords(x, y, z) {
  28462. this.radius = Math.sqrt(x * x + z * z);
  28463. this.theta = Math.atan2(x, z);
  28464. this.y = y;
  28465. return this;
  28466. }
  28467. clone() {
  28468. return new this.constructor().copy(this);
  28469. }
  28470. }
  28471. const _vector$4 = /*@__PURE__*/new Vector2();
  28472. class Box2 {
  28473. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  28474. this.isBox2 = true;
  28475. this.min = min;
  28476. this.max = max;
  28477. }
  28478. set(min, max) {
  28479. this.min.copy(min);
  28480. this.max.copy(max);
  28481. return this;
  28482. }
  28483. setFromPoints(points) {
  28484. this.makeEmpty();
  28485. for (let i = 0, il = points.length; i < il; i++) {
  28486. this.expandByPoint(points[i]);
  28487. }
  28488. return this;
  28489. }
  28490. setFromCenterAndSize(center, size) {
  28491. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  28492. this.min.copy(center).sub(halfSize);
  28493. this.max.copy(center).add(halfSize);
  28494. return this;
  28495. }
  28496. clone() {
  28497. return new this.constructor().copy(this);
  28498. }
  28499. copy(box) {
  28500. this.min.copy(box.min);
  28501. this.max.copy(box.max);
  28502. return this;
  28503. }
  28504. makeEmpty() {
  28505. this.min.x = this.min.y = +Infinity;
  28506. this.max.x = this.max.y = -Infinity;
  28507. return this;
  28508. }
  28509. isEmpty() {
  28510. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28511. return this.max.x < this.min.x || this.max.y < this.min.y;
  28512. }
  28513. getCenter(target) {
  28514. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  28515. }
  28516. getSize(target) {
  28517. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  28518. }
  28519. expandByPoint(point) {
  28520. this.min.min(point);
  28521. this.max.max(point);
  28522. return this;
  28523. }
  28524. expandByVector(vector) {
  28525. this.min.sub(vector);
  28526. this.max.add(vector);
  28527. return this;
  28528. }
  28529. expandByScalar(scalar) {
  28530. this.min.addScalar(-scalar);
  28531. this.max.addScalar(scalar);
  28532. return this;
  28533. }
  28534. containsPoint(point) {
  28535. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28536. }
  28537. containsBox(box) {
  28538. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  28539. }
  28540. getParameter(point, target) {
  28541. // This can potentially have a divide by zero if the box
  28542. // has a size dimension of 0.
  28543. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  28544. }
  28545. intersectsBox(box) {
  28546. // using 4 splitting planes to rule out intersections
  28547. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28548. }
  28549. clampPoint(point, target) {
  28550. return target.copy(point).clamp(this.min, this.max);
  28551. }
  28552. distanceToPoint(point) {
  28553. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  28554. return clampedPoint.sub(point).length();
  28555. }
  28556. intersect(box) {
  28557. this.min.max(box.min);
  28558. this.max.min(box.max);
  28559. return this;
  28560. }
  28561. union(box) {
  28562. this.min.min(box.min);
  28563. this.max.max(box.max);
  28564. return this;
  28565. }
  28566. translate(offset) {
  28567. this.min.add(offset);
  28568. this.max.add(offset);
  28569. return this;
  28570. }
  28571. equals(box) {
  28572. return box.min.equals(this.min) && box.max.equals(this.max);
  28573. }
  28574. }
  28575. const _startP = /*@__PURE__*/new Vector3();
  28576. const _startEnd = /*@__PURE__*/new Vector3();
  28577. class Line3 {
  28578. constructor(start = new Vector3(), end = new Vector3()) {
  28579. this.start = start;
  28580. this.end = end;
  28581. }
  28582. set(start, end) {
  28583. this.start.copy(start);
  28584. this.end.copy(end);
  28585. return this;
  28586. }
  28587. copy(line) {
  28588. this.start.copy(line.start);
  28589. this.end.copy(line.end);
  28590. return this;
  28591. }
  28592. getCenter(target) {
  28593. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28594. }
  28595. delta(target) {
  28596. return target.subVectors(this.end, this.start);
  28597. }
  28598. distanceSq() {
  28599. return this.start.distanceToSquared(this.end);
  28600. }
  28601. distance() {
  28602. return this.start.distanceTo(this.end);
  28603. }
  28604. at(t, target) {
  28605. return this.delta(target).multiplyScalar(t).add(this.start);
  28606. }
  28607. closestPointToPointParameter(point, clampToLine) {
  28608. _startP.subVectors(point, this.start);
  28609. _startEnd.subVectors(this.end, this.start);
  28610. const startEnd2 = _startEnd.dot(_startEnd);
  28611. const startEnd_startP = _startEnd.dot(_startP);
  28612. let t = startEnd_startP / startEnd2;
  28613. if (clampToLine) {
  28614. t = clamp(t, 0, 1);
  28615. }
  28616. return t;
  28617. }
  28618. closestPointToPoint(point, clampToLine, target) {
  28619. const t = this.closestPointToPointParameter(point, clampToLine);
  28620. return this.delta(target).multiplyScalar(t).add(this.start);
  28621. }
  28622. applyMatrix4(matrix) {
  28623. this.start.applyMatrix4(matrix);
  28624. this.end.applyMatrix4(matrix);
  28625. return this;
  28626. }
  28627. equals(line) {
  28628. return line.start.equals(this.start) && line.end.equals(this.end);
  28629. }
  28630. clone() {
  28631. return new this.constructor().copy(this);
  28632. }
  28633. }
  28634. const _vector$3 = /*@__PURE__*/new Vector3();
  28635. class SpotLightHelper extends Object3D {
  28636. constructor(light, color) {
  28637. super();
  28638. this.light = light;
  28639. this.matrix = light.matrixWorld;
  28640. this.matrixAutoUpdate = false;
  28641. this.color = color;
  28642. this.type = 'SpotLightHelper';
  28643. const geometry = new BufferGeometry();
  28644. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  28645. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  28646. const p1 = i / l * Math.PI * 2;
  28647. const p2 = j / l * Math.PI * 2;
  28648. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28649. }
  28650. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28651. const material = new LineBasicMaterial({
  28652. fog: false,
  28653. toneMapped: false
  28654. });
  28655. this.cone = new LineSegments(geometry, material);
  28656. this.add(this.cone);
  28657. this.update();
  28658. }
  28659. dispose() {
  28660. this.cone.geometry.dispose();
  28661. this.cone.material.dispose();
  28662. }
  28663. update() {
  28664. this.light.updateWorldMatrix(true, false);
  28665. this.light.target.updateWorldMatrix(true, false);
  28666. const coneLength = this.light.distance ? this.light.distance : 1000;
  28667. const coneWidth = coneLength * Math.tan(this.light.angle);
  28668. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28669. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  28670. this.cone.lookAt(_vector$3);
  28671. if (this.color !== undefined) {
  28672. this.cone.material.color.set(this.color);
  28673. } else {
  28674. this.cone.material.color.copy(this.light.color);
  28675. }
  28676. }
  28677. }
  28678. const _vector$2 = /*@__PURE__*/new Vector3();
  28679. const _boneMatrix = /*@__PURE__*/new Matrix4();
  28680. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  28681. class SkeletonHelper extends LineSegments {
  28682. constructor(object) {
  28683. const bones = getBoneList(object);
  28684. const geometry = new BufferGeometry();
  28685. const vertices = [];
  28686. const colors = [];
  28687. const color1 = new Color(0, 0, 1);
  28688. const color2 = new Color(0, 1, 0);
  28689. for (let i = 0; i < bones.length; i++) {
  28690. const bone = bones[i];
  28691. if (bone.parent && bone.parent.isBone) {
  28692. vertices.push(0, 0, 0);
  28693. vertices.push(0, 0, 0);
  28694. colors.push(color1.r, color1.g, color1.b);
  28695. colors.push(color2.r, color2.g, color2.b);
  28696. }
  28697. }
  28698. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28699. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28700. const material = new LineBasicMaterial({
  28701. vertexColors: true,
  28702. depthTest: false,
  28703. depthWrite: false,
  28704. toneMapped: false,
  28705. transparent: true
  28706. });
  28707. super(geometry, material);
  28708. this.isSkeletonHelper = true;
  28709. this.type = 'SkeletonHelper';
  28710. this.root = object;
  28711. this.bones = bones;
  28712. this.matrix = object.matrixWorld;
  28713. this.matrixAutoUpdate = false;
  28714. }
  28715. updateMatrixWorld(force) {
  28716. const bones = this.bones;
  28717. const geometry = this.geometry;
  28718. const position = geometry.getAttribute('position');
  28719. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  28720. for (let i = 0, j = 0; i < bones.length; i++) {
  28721. const bone = bones[i];
  28722. if (bone.parent && bone.parent.isBone) {
  28723. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28724. _vector$2.setFromMatrixPosition(_boneMatrix);
  28725. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  28726. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28727. _vector$2.setFromMatrixPosition(_boneMatrix);
  28728. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  28729. j += 2;
  28730. }
  28731. }
  28732. geometry.getAttribute('position').needsUpdate = true;
  28733. super.updateMatrixWorld(force);
  28734. }
  28735. dispose() {
  28736. this.geometry.dispose();
  28737. this.material.dispose();
  28738. }
  28739. }
  28740. function getBoneList(object) {
  28741. const boneList = [];
  28742. if (object.isBone === true) {
  28743. boneList.push(object);
  28744. }
  28745. for (let i = 0; i < object.children.length; i++) {
  28746. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28747. }
  28748. return boneList;
  28749. }
  28750. class PointLightHelper extends Mesh {
  28751. constructor(light, sphereSize, color) {
  28752. const geometry = new SphereGeometry(sphereSize, 4, 2);
  28753. const material = new MeshBasicMaterial({
  28754. wireframe: true,
  28755. fog: false,
  28756. toneMapped: false
  28757. });
  28758. super(geometry, material);
  28759. this.light = light;
  28760. this.color = color;
  28761. this.type = 'PointLightHelper';
  28762. this.matrix = this.light.matrixWorld;
  28763. this.matrixAutoUpdate = false;
  28764. this.update();
  28765. /*
  28766. // TODO: delete this comment?
  28767. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28768. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28769. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28770. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28771. const d = light.distance;
  28772. if ( d === 0.0 ) {
  28773. this.lightDistance.visible = false;
  28774. } else {
  28775. this.lightDistance.scale.set( d, d, d );
  28776. }
  28777. this.add( this.lightDistance );
  28778. */
  28779. }
  28780. dispose() {
  28781. this.geometry.dispose();
  28782. this.material.dispose();
  28783. }
  28784. update() {
  28785. this.light.updateWorldMatrix(true, false);
  28786. if (this.color !== undefined) {
  28787. this.material.color.set(this.color);
  28788. } else {
  28789. this.material.color.copy(this.light.color);
  28790. }
  28791. /*
  28792. const d = this.light.distance;
  28793. if ( d === 0.0 ) {
  28794. this.lightDistance.visible = false;
  28795. } else {
  28796. this.lightDistance.visible = true;
  28797. this.lightDistance.scale.set( d, d, d );
  28798. }
  28799. */
  28800. }
  28801. }
  28802. const _vector$1 = /*@__PURE__*/new Vector3();
  28803. const _color1 = /*@__PURE__*/new Color();
  28804. const _color2 = /*@__PURE__*/new Color();
  28805. class HemisphereLightHelper extends Object3D {
  28806. constructor(light, size, color) {
  28807. super();
  28808. this.light = light;
  28809. this.matrix = light.matrixWorld;
  28810. this.matrixAutoUpdate = false;
  28811. this.color = color;
  28812. this.type = 'HemisphereLightHelper';
  28813. const geometry = new OctahedronGeometry(size);
  28814. geometry.rotateY(Math.PI * 0.5);
  28815. this.material = new MeshBasicMaterial({
  28816. wireframe: true,
  28817. fog: false,
  28818. toneMapped: false
  28819. });
  28820. if (this.color === undefined) this.material.vertexColors = true;
  28821. const position = geometry.getAttribute('position');
  28822. const colors = new Float32Array(position.count * 3);
  28823. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  28824. this.add(new Mesh(geometry, this.material));
  28825. this.update();
  28826. }
  28827. dispose() {
  28828. this.children[0].geometry.dispose();
  28829. this.children[0].material.dispose();
  28830. }
  28831. update() {
  28832. const mesh = this.children[0];
  28833. if (this.color !== undefined) {
  28834. this.material.color.set(this.color);
  28835. } else {
  28836. const colors = mesh.geometry.getAttribute('color');
  28837. _color1.copy(this.light.color);
  28838. _color2.copy(this.light.groundColor);
  28839. for (let i = 0, l = colors.count; i < l; i++) {
  28840. const color = i < l / 2 ? _color1 : _color2;
  28841. colors.setXYZ(i, color.r, color.g, color.b);
  28842. }
  28843. colors.needsUpdate = true;
  28844. }
  28845. this.light.updateWorldMatrix(true, false);
  28846. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  28847. }
  28848. }
  28849. class GridHelper extends LineSegments {
  28850. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  28851. color1 = new Color(color1);
  28852. color2 = new Color(color2);
  28853. const center = divisions / 2;
  28854. const step = size / divisions;
  28855. const halfSize = size / 2;
  28856. const vertices = [],
  28857. colors = [];
  28858. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28859. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28860. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28861. const color = i === center ? color1 : color2;
  28862. color.toArray(colors, j);
  28863. j += 3;
  28864. color.toArray(colors, j);
  28865. j += 3;
  28866. color.toArray(colors, j);
  28867. j += 3;
  28868. color.toArray(colors, j);
  28869. j += 3;
  28870. }
  28871. const geometry = new BufferGeometry();
  28872. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28873. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28874. const material = new LineBasicMaterial({
  28875. vertexColors: true,
  28876. toneMapped: false
  28877. });
  28878. super(geometry, material);
  28879. this.type = 'GridHelper';
  28880. }
  28881. dispose() {
  28882. this.geometry.dispose();
  28883. this.material.dispose();
  28884. }
  28885. }
  28886. class PolarGridHelper extends LineSegments {
  28887. constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  28888. color1 = new Color(color1);
  28889. color2 = new Color(color2);
  28890. const vertices = [];
  28891. const colors = [];
  28892. // create the sectors
  28893. if (sectors > 1) {
  28894. for (let i = 0; i < sectors; i++) {
  28895. const v = i / sectors * (Math.PI * 2);
  28896. const x = Math.sin(v) * radius;
  28897. const z = Math.cos(v) * radius;
  28898. vertices.push(0, 0, 0);
  28899. vertices.push(x, 0, z);
  28900. const color = i & 1 ? color1 : color2;
  28901. colors.push(color.r, color.g, color.b);
  28902. colors.push(color.r, color.g, color.b);
  28903. }
  28904. }
  28905. // create the rings
  28906. for (let i = 0; i < rings; i++) {
  28907. const color = i & 1 ? color1 : color2;
  28908. const r = radius - radius / rings * i;
  28909. for (let j = 0; j < divisions; j++) {
  28910. // first vertex
  28911. let v = j / divisions * (Math.PI * 2);
  28912. let x = Math.sin(v) * r;
  28913. let z = Math.cos(v) * r;
  28914. vertices.push(x, 0, z);
  28915. colors.push(color.r, color.g, color.b);
  28916. // second vertex
  28917. v = (j + 1) / divisions * (Math.PI * 2);
  28918. x = Math.sin(v) * r;
  28919. z = Math.cos(v) * r;
  28920. vertices.push(x, 0, z);
  28921. colors.push(color.r, color.g, color.b);
  28922. }
  28923. }
  28924. const geometry = new BufferGeometry();
  28925. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28926. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28927. const material = new LineBasicMaterial({
  28928. vertexColors: true,
  28929. toneMapped: false
  28930. });
  28931. super(geometry, material);
  28932. this.type = 'PolarGridHelper';
  28933. }
  28934. dispose() {
  28935. this.geometry.dispose();
  28936. this.material.dispose();
  28937. }
  28938. }
  28939. const _v1 = /*@__PURE__*/new Vector3();
  28940. const _v2 = /*@__PURE__*/new Vector3();
  28941. const _v3 = /*@__PURE__*/new Vector3();
  28942. class DirectionalLightHelper extends Object3D {
  28943. constructor(light, size, color) {
  28944. super();
  28945. this.light = light;
  28946. this.matrix = light.matrixWorld;
  28947. this.matrixAutoUpdate = false;
  28948. this.color = color;
  28949. this.type = 'DirectionalLightHelper';
  28950. if (size === undefined) size = 1;
  28951. let geometry = new BufferGeometry();
  28952. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28953. const material = new LineBasicMaterial({
  28954. fog: false,
  28955. toneMapped: false
  28956. });
  28957. this.lightPlane = new Line(geometry, material);
  28958. this.add(this.lightPlane);
  28959. geometry = new BufferGeometry();
  28960. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28961. this.targetLine = new Line(geometry, material);
  28962. this.add(this.targetLine);
  28963. this.update();
  28964. }
  28965. dispose() {
  28966. this.lightPlane.geometry.dispose();
  28967. this.lightPlane.material.dispose();
  28968. this.targetLine.geometry.dispose();
  28969. this.targetLine.material.dispose();
  28970. }
  28971. update() {
  28972. this.light.updateWorldMatrix(true, false);
  28973. this.light.target.updateWorldMatrix(true, false);
  28974. _v1.setFromMatrixPosition(this.light.matrixWorld);
  28975. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  28976. _v3.subVectors(_v2, _v1);
  28977. this.lightPlane.lookAt(_v2);
  28978. if (this.color !== undefined) {
  28979. this.lightPlane.material.color.set(this.color);
  28980. this.targetLine.material.color.set(this.color);
  28981. } else {
  28982. this.lightPlane.material.color.copy(this.light.color);
  28983. this.targetLine.material.color.copy(this.light.color);
  28984. }
  28985. this.targetLine.lookAt(_v2);
  28986. this.targetLine.scale.z = _v3.length();
  28987. }
  28988. }
  28989. const _vector = /*@__PURE__*/new Vector3();
  28990. const _camera = /*@__PURE__*/new Camera();
  28991. /**
  28992. * - shows frustum, line of sight and up of the camera
  28993. * - suitable for fast updates
  28994. * - based on frustum visualization in lightgl.js shadowmap example
  28995. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28996. */
  28997. class CameraHelper extends LineSegments {
  28998. constructor(camera) {
  28999. const geometry = new BufferGeometry();
  29000. const material = new LineBasicMaterial({
  29001. color: 0xffffff,
  29002. vertexColors: true,
  29003. toneMapped: false
  29004. });
  29005. const vertices = [];
  29006. const colors = [];
  29007. const pointMap = {};
  29008. // near
  29009. addLine('n1', 'n2');
  29010. addLine('n2', 'n4');
  29011. addLine('n4', 'n3');
  29012. addLine('n3', 'n1');
  29013. // far
  29014. addLine('f1', 'f2');
  29015. addLine('f2', 'f4');
  29016. addLine('f4', 'f3');
  29017. addLine('f3', 'f1');
  29018. // sides
  29019. addLine('n1', 'f1');
  29020. addLine('n2', 'f2');
  29021. addLine('n3', 'f3');
  29022. addLine('n4', 'f4');
  29023. // cone
  29024. addLine('p', 'n1');
  29025. addLine('p', 'n2');
  29026. addLine('p', 'n3');
  29027. addLine('p', 'n4');
  29028. // up
  29029. addLine('u1', 'u2');
  29030. addLine('u2', 'u3');
  29031. addLine('u3', 'u1');
  29032. // target
  29033. addLine('c', 't');
  29034. addLine('p', 'c');
  29035. // cross
  29036. addLine('cn1', 'cn2');
  29037. addLine('cn3', 'cn4');
  29038. addLine('cf1', 'cf2');
  29039. addLine('cf3', 'cf4');
  29040. function addLine(a, b) {
  29041. addPoint(a);
  29042. addPoint(b);
  29043. }
  29044. function addPoint(id) {
  29045. vertices.push(0, 0, 0);
  29046. colors.push(0, 0, 0);
  29047. if (pointMap[id] === undefined) {
  29048. pointMap[id] = [];
  29049. }
  29050. pointMap[id].push(vertices.length / 3 - 1);
  29051. }
  29052. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  29053. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  29054. super(geometry, material);
  29055. this.type = 'CameraHelper';
  29056. this.camera = camera;
  29057. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  29058. this.matrix = camera.matrixWorld;
  29059. this.matrixAutoUpdate = false;
  29060. this.pointMap = pointMap;
  29061. this.update();
  29062. // colors
  29063. const colorFrustum = new Color(0xffaa00);
  29064. const colorCone = new Color(0xff0000);
  29065. const colorUp = new Color(0x00aaff);
  29066. const colorTarget = new Color(0xffffff);
  29067. const colorCross = new Color(0x333333);
  29068. this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  29069. }
  29070. setColors(frustum, cone, up, target, cross) {
  29071. const geometry = this.geometry;
  29072. const colorAttribute = geometry.getAttribute('color');
  29073. // near
  29074. colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
  29075. colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); // n1, n2
  29076. colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
  29077. colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); // n2, n4
  29078. colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
  29079. colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); // n4, n3
  29080. colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
  29081. colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); // n3, n1
  29082. // far
  29083. colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
  29084. colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); // f1, f2
  29085. colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
  29086. colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); // f2, f4
  29087. colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
  29088. colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); // f4, f3
  29089. colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
  29090. colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); // f3, f1
  29091. // sides
  29092. colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
  29093. colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); // n1, f1
  29094. colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
  29095. colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); // n2, f2
  29096. colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
  29097. colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); // n3, f3
  29098. colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
  29099. colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); // n4, f4
  29100. // cone
  29101. colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
  29102. colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); // p, n1
  29103. colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
  29104. colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); // p, n2
  29105. colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
  29106. colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); // p, n3
  29107. colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
  29108. colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); // p, n4
  29109. // up
  29110. colorAttribute.setXYZ(32, up.r, up.g, up.b);
  29111. colorAttribute.setXYZ(33, up.r, up.g, up.b); // u1, u2
  29112. colorAttribute.setXYZ(34, up.r, up.g, up.b);
  29113. colorAttribute.setXYZ(35, up.r, up.g, up.b); // u2, u3
  29114. colorAttribute.setXYZ(36, up.r, up.g, up.b);
  29115. colorAttribute.setXYZ(37, up.r, up.g, up.b); // u3, u1
  29116. // target
  29117. colorAttribute.setXYZ(38, target.r, target.g, target.b);
  29118. colorAttribute.setXYZ(39, target.r, target.g, target.b); // c, t
  29119. colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
  29120. colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); // p, c
  29121. // cross
  29122. colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
  29123. colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); // cn1, cn2
  29124. colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
  29125. colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); // cn3, cn4
  29126. colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
  29127. colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); // cf1, cf2
  29128. colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
  29129. colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); // cf3, cf4
  29130. colorAttribute.needsUpdate = true;
  29131. }
  29132. update() {
  29133. const geometry = this.geometry;
  29134. const pointMap = this.pointMap;
  29135. const w = 1,
  29136. h = 1;
  29137. // we need just camera projection matrix inverse
  29138. // world matrix must be identity
  29139. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse);
  29140. // center / target
  29141. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  29142. setPoint('t', pointMap, geometry, _camera, 0, 0, 1);
  29143. // near
  29144. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  29145. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  29146. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  29147. setPoint('n4', pointMap, geometry, _camera, w, h, -1);
  29148. // far
  29149. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  29150. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  29151. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  29152. setPoint('f4', pointMap, geometry, _camera, w, h, 1);
  29153. // up
  29154. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  29155. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  29156. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1);
  29157. // cross
  29158. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  29159. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  29160. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  29161. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  29162. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  29163. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  29164. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  29165. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  29166. geometry.getAttribute('position').needsUpdate = true;
  29167. }
  29168. dispose() {
  29169. this.geometry.dispose();
  29170. this.material.dispose();
  29171. }
  29172. }
  29173. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  29174. _vector.set(x, y, z).unproject(camera);
  29175. const points = pointMap[point];
  29176. if (points !== undefined) {
  29177. const position = geometry.getAttribute('position');
  29178. for (let i = 0, l = points.length; i < l; i++) {
  29179. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  29180. }
  29181. }
  29182. }
  29183. const _box = /*@__PURE__*/new Box3();
  29184. class BoxHelper extends LineSegments {
  29185. constructor(object, color = 0xffff00) {
  29186. 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]);
  29187. const positions = new Float32Array(8 * 3);
  29188. const geometry = new BufferGeometry();
  29189. geometry.setIndex(new BufferAttribute(indices, 1));
  29190. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  29191. super(geometry, new LineBasicMaterial({
  29192. color: color,
  29193. toneMapped: false
  29194. }));
  29195. this.object = object;
  29196. this.type = 'BoxHelper';
  29197. this.matrixAutoUpdate = false;
  29198. this.update();
  29199. }
  29200. update(object) {
  29201. if (object !== undefined) {
  29202. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  29203. }
  29204. if (this.object !== undefined) {
  29205. _box.setFromObject(this.object);
  29206. }
  29207. if (_box.isEmpty()) return;
  29208. const min = _box.min;
  29209. const max = _box.max;
  29210. /*
  29211. 5____4
  29212. 1/___0/|
  29213. | 6__|_7
  29214. 2/___3/
  29215. 0: max.x, max.y, max.z
  29216. 1: min.x, max.y, max.z
  29217. 2: min.x, min.y, max.z
  29218. 3: max.x, min.y, max.z
  29219. 4: max.x, max.y, min.z
  29220. 5: min.x, max.y, min.z
  29221. 6: min.x, min.y, min.z
  29222. 7: max.x, min.y, min.z
  29223. */
  29224. const position = this.geometry.attributes.position;
  29225. const array = position.array;
  29226. array[0] = max.x;
  29227. array[1] = max.y;
  29228. array[2] = max.z;
  29229. array[3] = min.x;
  29230. array[4] = max.y;
  29231. array[5] = max.z;
  29232. array[6] = min.x;
  29233. array[7] = min.y;
  29234. array[8] = max.z;
  29235. array[9] = max.x;
  29236. array[10] = min.y;
  29237. array[11] = max.z;
  29238. array[12] = max.x;
  29239. array[13] = max.y;
  29240. array[14] = min.z;
  29241. array[15] = min.x;
  29242. array[16] = max.y;
  29243. array[17] = min.z;
  29244. array[18] = min.x;
  29245. array[19] = min.y;
  29246. array[20] = min.z;
  29247. array[21] = max.x;
  29248. array[22] = min.y;
  29249. array[23] = min.z;
  29250. position.needsUpdate = true;
  29251. this.geometry.computeBoundingSphere();
  29252. }
  29253. setFromObject(object) {
  29254. this.object = object;
  29255. this.update();
  29256. return this;
  29257. }
  29258. copy(source, recursive) {
  29259. super.copy(source, recursive);
  29260. this.object = source.object;
  29261. return this;
  29262. }
  29263. dispose() {
  29264. this.geometry.dispose();
  29265. this.material.dispose();
  29266. }
  29267. }
  29268. class Box3Helper extends LineSegments {
  29269. constructor(box, color = 0xffff00) {
  29270. 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]);
  29271. 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];
  29272. const geometry = new BufferGeometry();
  29273. geometry.setIndex(new BufferAttribute(indices, 1));
  29274. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  29275. super(geometry, new LineBasicMaterial({
  29276. color: color,
  29277. toneMapped: false
  29278. }));
  29279. this.box = box;
  29280. this.type = 'Box3Helper';
  29281. this.geometry.computeBoundingSphere();
  29282. }
  29283. updateMatrixWorld(force) {
  29284. const box = this.box;
  29285. if (box.isEmpty()) return;
  29286. box.getCenter(this.position);
  29287. box.getSize(this.scale);
  29288. this.scale.multiplyScalar(0.5);
  29289. super.updateMatrixWorld(force);
  29290. }
  29291. dispose() {
  29292. this.geometry.dispose();
  29293. this.material.dispose();
  29294. }
  29295. }
  29296. class PlaneHelper extends Line {
  29297. constructor(plane, size = 1, hex = 0xffff00) {
  29298. const color = hex;
  29299. 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];
  29300. const geometry = new BufferGeometry();
  29301. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  29302. geometry.computeBoundingSphere();
  29303. super(geometry, new LineBasicMaterial({
  29304. color: color,
  29305. toneMapped: false
  29306. }));
  29307. this.type = 'PlaneHelper';
  29308. this.plane = plane;
  29309. this.size = size;
  29310. const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  29311. const geometry2 = new BufferGeometry();
  29312. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  29313. geometry2.computeBoundingSphere();
  29314. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29315. color: color,
  29316. opacity: 0.2,
  29317. transparent: true,
  29318. depthWrite: false,
  29319. toneMapped: false
  29320. })));
  29321. }
  29322. updateMatrixWorld(force) {
  29323. this.position.set(0, 0, 0);
  29324. this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
  29325. this.lookAt(this.plane.normal);
  29326. this.translateZ(-this.plane.constant);
  29327. super.updateMatrixWorld(force);
  29328. }
  29329. dispose() {
  29330. this.geometry.dispose();
  29331. this.material.dispose();
  29332. this.children[0].geometry.dispose();
  29333. this.children[0].material.dispose();
  29334. }
  29335. }
  29336. const _axis = /*@__PURE__*/new Vector3();
  29337. let _lineGeometry, _coneGeometry;
  29338. class ArrowHelper extends Object3D {
  29339. // dir is assumed to be normalized
  29340. 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) {
  29341. super();
  29342. this.type = 'ArrowHelper';
  29343. if (_lineGeometry === undefined) {
  29344. _lineGeometry = new BufferGeometry();
  29345. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29346. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  29347. _coneGeometry.translate(0, -0.5, 0);
  29348. }
  29349. this.position.copy(origin);
  29350. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29351. color: color,
  29352. toneMapped: false
  29353. }));
  29354. this.line.matrixAutoUpdate = false;
  29355. this.add(this.line);
  29356. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29357. color: color,
  29358. toneMapped: false
  29359. }));
  29360. this.cone.matrixAutoUpdate = false;
  29361. this.add(this.cone);
  29362. this.setDirection(dir);
  29363. this.setLength(length, headLength, headWidth);
  29364. }
  29365. setDirection(dir) {
  29366. // dir is assumed to be normalized
  29367. if (dir.y > 0.99999) {
  29368. this.quaternion.set(0, 0, 0, 1);
  29369. } else if (dir.y < -0.99999) {
  29370. this.quaternion.set(1, 0, 0, 0);
  29371. } else {
  29372. _axis.set(dir.z, 0, -dir.x).normalize();
  29373. const radians = Math.acos(dir.y);
  29374. this.quaternion.setFromAxisAngle(_axis, radians);
  29375. }
  29376. }
  29377. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  29378. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29379. this.line.updateMatrix();
  29380. this.cone.scale.set(headWidth, headLength, headWidth);
  29381. this.cone.position.y = length;
  29382. this.cone.updateMatrix();
  29383. }
  29384. setColor(color) {
  29385. this.line.material.color.set(color);
  29386. this.cone.material.color.set(color);
  29387. }
  29388. copy(source) {
  29389. super.copy(source, false);
  29390. this.line.copy(source.line);
  29391. this.cone.copy(source.cone);
  29392. return this;
  29393. }
  29394. dispose() {
  29395. this.line.geometry.dispose();
  29396. this.line.material.dispose();
  29397. this.cone.geometry.dispose();
  29398. this.cone.material.dispose();
  29399. }
  29400. }
  29401. class AxesHelper extends LineSegments {
  29402. constructor(size = 1) {
  29403. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29404. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29405. const geometry = new BufferGeometry();
  29406. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  29407. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  29408. const material = new LineBasicMaterial({
  29409. vertexColors: true,
  29410. toneMapped: false
  29411. });
  29412. super(geometry, material);
  29413. this.type = 'AxesHelper';
  29414. }
  29415. setColors(xAxisColor, yAxisColor, zAxisColor) {
  29416. const color = new Color();
  29417. const array = this.geometry.attributes.color.array;
  29418. color.set(xAxisColor);
  29419. color.toArray(array, 0);
  29420. color.toArray(array, 3);
  29421. color.set(yAxisColor);
  29422. color.toArray(array, 6);
  29423. color.toArray(array, 9);
  29424. color.set(zAxisColor);
  29425. color.toArray(array, 12);
  29426. color.toArray(array, 15);
  29427. this.geometry.attributes.color.needsUpdate = true;
  29428. return this;
  29429. }
  29430. dispose() {
  29431. this.geometry.dispose();
  29432. this.material.dispose();
  29433. }
  29434. }
  29435. class ShapePath {
  29436. constructor() {
  29437. this.type = 'ShapePath';
  29438. this.color = new Color();
  29439. this.subPaths = [];
  29440. this.currentPath = null;
  29441. }
  29442. moveTo(x, y) {
  29443. this.currentPath = new Path();
  29444. this.subPaths.push(this.currentPath);
  29445. this.currentPath.moveTo(x, y);
  29446. return this;
  29447. }
  29448. lineTo(x, y) {
  29449. this.currentPath.lineTo(x, y);
  29450. return this;
  29451. }
  29452. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  29453. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  29454. return this;
  29455. }
  29456. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  29457. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  29458. return this;
  29459. }
  29460. splineThru(pts) {
  29461. this.currentPath.splineThru(pts);
  29462. return this;
  29463. }
  29464. toShapes(isCCW) {
  29465. function toShapesNoHoles(inSubpaths) {
  29466. const shapes = [];
  29467. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  29468. const tmpPath = inSubpaths[i];
  29469. const tmpShape = new Shape();
  29470. tmpShape.curves = tmpPath.curves;
  29471. shapes.push(tmpShape);
  29472. }
  29473. return shapes;
  29474. }
  29475. function isPointInsidePolygon(inPt, inPolygon) {
  29476. const polyLen = inPolygon.length;
  29477. // inPt on polygon contour => immediate success or
  29478. // toggling of inside/outside at every single! intersection point of an edge
  29479. // with the horizontal line through inPt, left of inPt
  29480. // not counting lowerY endpoints of edges and whole edges on that line
  29481. let inside = false;
  29482. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  29483. let edgeLowPt = inPolygon[p];
  29484. let edgeHighPt = inPolygon[q];
  29485. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29486. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29487. if (Math.abs(edgeDy) > Number.EPSILON) {
  29488. // not parallel
  29489. if (edgeDy < 0) {
  29490. edgeLowPt = inPolygon[q];
  29491. edgeDx = -edgeDx;
  29492. edgeHighPt = inPolygon[p];
  29493. edgeDy = -edgeDy;
  29494. }
  29495. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  29496. if (inPt.y === edgeLowPt.y) {
  29497. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  29498. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29499. } else {
  29500. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  29501. if (perpEdge === 0) return true; // inPt is on contour ?
  29502. if (perpEdge < 0) continue;
  29503. inside = !inside; // true intersection left of inPt
  29504. }
  29505. } else {
  29506. // parallel or collinear
  29507. if (inPt.y !== edgeLowPt.y) continue; // parallel
  29508. // edge lies on the same horizontal line as inPt
  29509. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  29510. // continue;
  29511. }
  29512. }
  29513. return inside;
  29514. }
  29515. const isClockWise = ShapeUtils.isClockWise;
  29516. const subPaths = this.subPaths;
  29517. if (subPaths.length === 0) return [];
  29518. let solid, tmpPath, tmpShape;
  29519. const shapes = [];
  29520. if (subPaths.length === 1) {
  29521. tmpPath = subPaths[0];
  29522. tmpShape = new Shape();
  29523. tmpShape.curves = tmpPath.curves;
  29524. shapes.push(tmpShape);
  29525. return shapes;
  29526. }
  29527. let holesFirst = !isClockWise(subPaths[0].getPoints());
  29528. holesFirst = isCCW ? !holesFirst : holesFirst;
  29529. // console.log("Holes first", holesFirst);
  29530. const betterShapeHoles = [];
  29531. const newShapes = [];
  29532. let newShapeHoles = [];
  29533. let mainIdx = 0;
  29534. let tmpPoints;
  29535. newShapes[mainIdx] = undefined;
  29536. newShapeHoles[mainIdx] = [];
  29537. for (let i = 0, l = subPaths.length; i < l; i++) {
  29538. tmpPath = subPaths[i];
  29539. tmpPoints = tmpPath.getPoints();
  29540. solid = isClockWise(tmpPoints);
  29541. solid = isCCW ? !solid : solid;
  29542. if (solid) {
  29543. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  29544. newShapes[mainIdx] = {
  29545. s: new Shape(),
  29546. p: tmpPoints
  29547. };
  29548. newShapes[mainIdx].s.curves = tmpPath.curves;
  29549. if (holesFirst) mainIdx++;
  29550. newShapeHoles[mainIdx] = [];
  29551. //console.log('cw', i);
  29552. } else {
  29553. newShapeHoles[mainIdx].push({
  29554. h: tmpPath,
  29555. p: tmpPoints[0]
  29556. });
  29557. //console.log('ccw', i);
  29558. }
  29559. }
  29560. // only Holes? -> probably all Shapes with wrong orientation
  29561. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  29562. if (newShapes.length > 1) {
  29563. let ambiguous = false;
  29564. let toChange = 0;
  29565. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  29566. betterShapeHoles[sIdx] = [];
  29567. }
  29568. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  29569. const sho = newShapeHoles[sIdx];
  29570. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  29571. const ho = sho[hIdx];
  29572. let hole_unassigned = true;
  29573. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  29574. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  29575. if (sIdx !== s2Idx) toChange++;
  29576. if (hole_unassigned) {
  29577. hole_unassigned = false;
  29578. betterShapeHoles[s2Idx].push(ho);
  29579. } else {
  29580. ambiguous = true;
  29581. }
  29582. }
  29583. }
  29584. if (hole_unassigned) {
  29585. betterShapeHoles[sIdx].push(ho);
  29586. }
  29587. }
  29588. }
  29589. if (toChange > 0 && ambiguous === false) {
  29590. newShapeHoles = betterShapeHoles;
  29591. }
  29592. }
  29593. let tmpHoles;
  29594. for (let i = 0, il = newShapes.length; i < il; i++) {
  29595. tmpShape = newShapes[i].s;
  29596. shapes.push(tmpShape);
  29597. tmpHoles = newShapeHoles[i];
  29598. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  29599. tmpShape.holes.push(tmpHoles[j].h);
  29600. }
  29601. }
  29602. //console.log("shape", shapes);
  29603. return shapes;
  29604. }
  29605. }
  29606. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29607. const _tables = /*@__PURE__*/_generateTables();
  29608. function _generateTables() {
  29609. // float32 to float16 helpers
  29610. const buffer = new ArrayBuffer(4);
  29611. const floatView = new Float32Array(buffer);
  29612. const uint32View = new Uint32Array(buffer);
  29613. const baseTable = new Uint32Array(512);
  29614. const shiftTable = new Uint32Array(512);
  29615. for (let i = 0; i < 256; ++i) {
  29616. const e = i - 127;
  29617. // very small number (0, -0)
  29618. if (e < -27) {
  29619. baseTable[i] = 0x0000;
  29620. baseTable[i | 0x100] = 0x8000;
  29621. shiftTable[i] = 24;
  29622. shiftTable[i | 0x100] = 24;
  29623. // small number (denorm)
  29624. } else if (e < -14) {
  29625. baseTable[i] = 0x0400 >> -e - 14;
  29626. baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  29627. shiftTable[i] = -e - 1;
  29628. shiftTable[i | 0x100] = -e - 1;
  29629. // normal number
  29630. } else if (e <= 15) {
  29631. baseTable[i] = e + 15 << 10;
  29632. baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  29633. shiftTable[i] = 13;
  29634. shiftTable[i | 0x100] = 13;
  29635. // large number (Infinity, -Infinity)
  29636. } else if (e < 128) {
  29637. baseTable[i] = 0x7c00;
  29638. baseTable[i | 0x100] = 0xfc00;
  29639. shiftTable[i] = 24;
  29640. shiftTable[i | 0x100] = 24;
  29641. // stay (NaN, Infinity, -Infinity)
  29642. } else {
  29643. baseTable[i] = 0x7c00;
  29644. baseTable[i | 0x100] = 0xfc00;
  29645. shiftTable[i] = 13;
  29646. shiftTable[i | 0x100] = 13;
  29647. }
  29648. }
  29649. // float16 to float32 helpers
  29650. const mantissaTable = new Uint32Array(2048);
  29651. const exponentTable = new Uint32Array(64);
  29652. const offsetTable = new Uint32Array(64);
  29653. for (let i = 1; i < 1024; ++i) {
  29654. let m = i << 13; // zero pad mantissa bits
  29655. let e = 0; // zero exponent
  29656. // normalized
  29657. while ((m & 0x00800000) === 0) {
  29658. m <<= 1;
  29659. e -= 0x00800000; // decrement exponent
  29660. }
  29661. m &= ~0x00800000; // clear leading 1 bit
  29662. e += 0x38800000; // adjust bias
  29663. mantissaTable[i] = m | e;
  29664. }
  29665. for (let i = 1024; i < 2048; ++i) {
  29666. mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  29667. }
  29668. for (let i = 1; i < 31; ++i) {
  29669. exponentTable[i] = i << 23;
  29670. }
  29671. exponentTable[31] = 0x47800000;
  29672. exponentTable[32] = 0x80000000;
  29673. for (let i = 33; i < 63; ++i) {
  29674. exponentTable[i] = 0x80000000 + (i - 32 << 23);
  29675. }
  29676. exponentTable[63] = 0xc7800000;
  29677. for (let i = 1; i < 64; ++i) {
  29678. if (i !== 32) {
  29679. offsetTable[i] = 1024;
  29680. }
  29681. }
  29682. return {
  29683. floatView: floatView,
  29684. uint32View: uint32View,
  29685. baseTable: baseTable,
  29686. shiftTable: shiftTable,
  29687. mantissaTable: mantissaTable,
  29688. exponentTable: exponentTable,
  29689. offsetTable: offsetTable
  29690. };
  29691. }
  29692. // float32 to float16
  29693. function toHalfFloat(val) {
  29694. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  29695. val = clamp(val, -65504, 65504);
  29696. _tables.floatView[0] = val;
  29697. const f = _tables.uint32View[0];
  29698. const e = f >> 23 & 0x1ff;
  29699. return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]);
  29700. }
  29701. // float16 to float32
  29702. function fromHalfFloat(val) {
  29703. const m = val >> 10;
  29704. _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m];
  29705. return _tables.floatView[0];
  29706. }
  29707. var DataUtils = /*#__PURE__*/Object.freeze({
  29708. __proto__: null,
  29709. toHalfFloat: toHalfFloat,
  29710. fromHalfFloat: fromHalfFloat
  29711. });
  29712. // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  29713. function ImmediateRenderObject() {
  29714. console.error('THREE.ImmediateRenderObject has been removed.');
  29715. }
  29716. // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  29717. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  29718. constructor(width, height, options) {
  29719. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  29720. super(width, height, options);
  29721. this.samples = 4;
  29722. }
  29723. }
  29724. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29725. class DataTexture2DArray extends DataArrayTexture {
  29726. constructor(data, width, height, depth) {
  29727. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  29728. super(data, width, height, depth);
  29729. }
  29730. }
  29731. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29732. class DataTexture3D extends Data3DTexture {
  29733. constructor(data, width, height, depth) {
  29734. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  29735. super(data, width, height, depth);
  29736. }
  29737. }
  29738. // r144
  29739. class BoxBufferGeometry extends BoxGeometry {
  29740. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  29741. console.warn('THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.');
  29742. super(width, height, depth, widthSegments, heightSegments, depthSegments);
  29743. }
  29744. }
  29745. // r144
  29746. class CapsuleBufferGeometry extends CapsuleGeometry {
  29747. constructor(radius, length, capSegments, radialSegments) {
  29748. console.warn('THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.');
  29749. super(radius, length, capSegments, radialSegments);
  29750. }
  29751. }
  29752. // r144
  29753. class CircleBufferGeometry extends CircleGeometry {
  29754. constructor(radius, segments, thetaStart, thetaLength) {
  29755. console.warn('THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.');
  29756. super(radius, segments, thetaStart, thetaLength);
  29757. }
  29758. }
  29759. // r144
  29760. class ConeBufferGeometry extends ConeGeometry {
  29761. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  29762. console.warn('THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.');
  29763. super(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  29764. }
  29765. }
  29766. // r144
  29767. class CylinderBufferGeometry extends CylinderGeometry {
  29768. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  29769. console.warn('THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.');
  29770. super(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  29771. }
  29772. }
  29773. // r144
  29774. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29775. constructor(radius, detail) {
  29776. console.warn('THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.');
  29777. super(radius, detail);
  29778. }
  29779. }
  29780. // r144
  29781. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29782. constructor(shapes, options) {
  29783. console.warn('THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.');
  29784. super(shapes, options);
  29785. }
  29786. }
  29787. // r144
  29788. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29789. constructor(radius, detail) {
  29790. console.warn('THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.');
  29791. super(radius, detail);
  29792. }
  29793. }
  29794. // r144
  29795. class LatheBufferGeometry extends LatheGeometry {
  29796. constructor(points, segments, phiStart, phiLength) {
  29797. console.warn('THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.');
  29798. super(points, segments, phiStart, phiLength);
  29799. }
  29800. }
  29801. // r144
  29802. class OctahedronBufferGeometry extends OctahedronGeometry {
  29803. constructor(radius, detail) {
  29804. console.warn('THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.');
  29805. super(radius, detail);
  29806. }
  29807. }
  29808. // r144
  29809. class PlaneBufferGeometry extends PlaneGeometry {
  29810. constructor(width, height, widthSegments, heightSegments) {
  29811. console.warn('THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.');
  29812. super(width, height, widthSegments, heightSegments);
  29813. }
  29814. }
  29815. // r144
  29816. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29817. constructor(vertices, indices, radius, detail) {
  29818. console.warn('THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.');
  29819. super(vertices, indices, radius, detail);
  29820. }
  29821. }
  29822. // r144
  29823. class RingBufferGeometry extends RingGeometry {
  29824. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  29825. console.warn('THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.');
  29826. super(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength);
  29827. }
  29828. }
  29829. // r144
  29830. class ShapeBufferGeometry extends ShapeGeometry {
  29831. constructor(shapes, curveSegments) {
  29832. console.warn('THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.');
  29833. super(shapes, curveSegments);
  29834. }
  29835. }
  29836. // r144
  29837. class SphereBufferGeometry extends SphereGeometry {
  29838. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  29839. console.warn('THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.');
  29840. super(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength);
  29841. }
  29842. }
  29843. // r144
  29844. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29845. constructor(radius, detail) {
  29846. console.warn('THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.');
  29847. super(radius, detail);
  29848. }
  29849. }
  29850. // r144
  29851. class TorusBufferGeometry extends TorusGeometry {
  29852. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  29853. console.warn('THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.');
  29854. super(radius, tube, radialSegments, tubularSegments, arc);
  29855. }
  29856. }
  29857. // r144
  29858. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29859. constructor(radius, tube, tubularSegments, radialSegments, p, q) {
  29860. console.warn('THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.');
  29861. super(radius, tube, tubularSegments, radialSegments, p, q);
  29862. }
  29863. }
  29864. // r144
  29865. class TubeBufferGeometry extends TubeGeometry {
  29866. constructor(path, tubularSegments, radius, radialSegments, closed) {
  29867. console.warn('THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.');
  29868. super(path, tubularSegments, radius, radialSegments, closed);
  29869. }
  29870. }
  29871. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29872. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29873. detail: {
  29874. revision: REVISION
  29875. }
  29876. }));
  29877. }
  29878. if (typeof window !== 'undefined') {
  29879. if (window.__THREE__) {
  29880. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29881. } else {
  29882. window.__THREE__ = REVISION;
  29883. }
  29884. }
  29885. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29886. exports.AddEquation = AddEquation;
  29887. exports.AddOperation = AddOperation;
  29888. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29889. exports.AdditiveBlending = AdditiveBlending;
  29890. exports.AlphaFormat = AlphaFormat;
  29891. exports.AlwaysDepth = AlwaysDepth;
  29892. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29893. exports.AmbientLight = AmbientLight;
  29894. exports.AmbientLightProbe = AmbientLightProbe;
  29895. exports.AnimationClip = AnimationClip;
  29896. exports.AnimationLoader = AnimationLoader;
  29897. exports.AnimationMixer = AnimationMixer;
  29898. exports.AnimationObjectGroup = AnimationObjectGroup;
  29899. exports.AnimationUtils = AnimationUtils;
  29900. exports.ArcCurve = ArcCurve;
  29901. exports.ArrayCamera = ArrayCamera;
  29902. exports.ArrowHelper = ArrowHelper;
  29903. exports.Audio = Audio;
  29904. exports.AudioAnalyser = AudioAnalyser;
  29905. exports.AudioContext = AudioContext;
  29906. exports.AudioListener = AudioListener;
  29907. exports.AudioLoader = AudioLoader;
  29908. exports.AxesHelper = AxesHelper;
  29909. exports.BackSide = BackSide;
  29910. exports.BasicDepthPacking = BasicDepthPacking;
  29911. exports.BasicShadowMap = BasicShadowMap;
  29912. exports.Bone = Bone;
  29913. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29914. exports.Box2 = Box2;
  29915. exports.Box3 = Box3;
  29916. exports.Box3Helper = Box3Helper;
  29917. exports.BoxBufferGeometry = BoxBufferGeometry;
  29918. exports.BoxGeometry = BoxGeometry;
  29919. exports.BoxHelper = BoxHelper;
  29920. exports.BufferAttribute = BufferAttribute;
  29921. exports.BufferGeometry = BufferGeometry;
  29922. exports.BufferGeometryLoader = BufferGeometryLoader;
  29923. exports.ByteType = ByteType;
  29924. exports.Cache = Cache;
  29925. exports.Camera = Camera;
  29926. exports.CameraHelper = CameraHelper;
  29927. exports.CanvasTexture = CanvasTexture;
  29928. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  29929. exports.CapsuleGeometry = CapsuleGeometry;
  29930. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29931. exports.CineonToneMapping = CineonToneMapping;
  29932. exports.CircleBufferGeometry = CircleBufferGeometry;
  29933. exports.CircleGeometry = CircleGeometry;
  29934. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29935. exports.Clock = Clock;
  29936. exports.Color = Color;
  29937. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29938. exports.ColorManagement = ColorManagement;
  29939. exports.CompressedArrayTexture = CompressedArrayTexture;
  29940. exports.CompressedTexture = CompressedTexture;
  29941. exports.CompressedTextureLoader = CompressedTextureLoader;
  29942. exports.ConeBufferGeometry = ConeBufferGeometry;
  29943. exports.ConeGeometry = ConeGeometry;
  29944. exports.CubeCamera = CubeCamera;
  29945. exports.CubeReflectionMapping = CubeReflectionMapping;
  29946. exports.CubeRefractionMapping = CubeRefractionMapping;
  29947. exports.CubeTexture = CubeTexture;
  29948. exports.CubeTextureLoader = CubeTextureLoader;
  29949. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29950. exports.CubicBezierCurve = CubicBezierCurve;
  29951. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29952. exports.CubicInterpolant = CubicInterpolant;
  29953. exports.CullFaceBack = CullFaceBack;
  29954. exports.CullFaceFront = CullFaceFront;
  29955. exports.CullFaceFrontBack = CullFaceFrontBack;
  29956. exports.CullFaceNone = CullFaceNone;
  29957. exports.Curve = Curve;
  29958. exports.CurvePath = CurvePath;
  29959. exports.CustomBlending = CustomBlending;
  29960. exports.CustomToneMapping = CustomToneMapping;
  29961. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29962. exports.CylinderGeometry = CylinderGeometry;
  29963. exports.Cylindrical = Cylindrical;
  29964. exports.Data3DTexture = Data3DTexture;
  29965. exports.DataArrayTexture = DataArrayTexture;
  29966. exports.DataTexture = DataTexture;
  29967. exports.DataTexture2DArray = DataTexture2DArray;
  29968. exports.DataTexture3D = DataTexture3D;
  29969. exports.DataTextureLoader = DataTextureLoader;
  29970. exports.DataUtils = DataUtils;
  29971. exports.DecrementStencilOp = DecrementStencilOp;
  29972. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29973. exports.DefaultLoadingManager = DefaultLoadingManager;
  29974. exports.DepthFormat = DepthFormat;
  29975. exports.DepthStencilFormat = DepthStencilFormat;
  29976. exports.DepthTexture = DepthTexture;
  29977. exports.DirectionalLight = DirectionalLight;
  29978. exports.DirectionalLightHelper = DirectionalLightHelper;
  29979. exports.DiscreteInterpolant = DiscreteInterpolant;
  29980. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  29981. exports.DodecahedronGeometry = DodecahedronGeometry;
  29982. exports.DoubleSide = DoubleSide;
  29983. exports.DstAlphaFactor = DstAlphaFactor;
  29984. exports.DstColorFactor = DstColorFactor;
  29985. exports.DynamicCopyUsage = DynamicCopyUsage;
  29986. exports.DynamicDrawUsage = DynamicDrawUsage;
  29987. exports.DynamicReadUsage = DynamicReadUsage;
  29988. exports.EdgesGeometry = EdgesGeometry;
  29989. exports.EllipseCurve = EllipseCurve;
  29990. exports.EqualDepth = EqualDepth;
  29991. exports.EqualStencilFunc = EqualStencilFunc;
  29992. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29993. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29994. exports.Euler = Euler;
  29995. exports.EventDispatcher = EventDispatcher;
  29996. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  29997. exports.ExtrudeGeometry = ExtrudeGeometry;
  29998. exports.FileLoader = FileLoader;
  29999. exports.Float16BufferAttribute = Float16BufferAttribute;
  30000. exports.Float32BufferAttribute = Float32BufferAttribute;
  30001. exports.Float64BufferAttribute = Float64BufferAttribute;
  30002. exports.FloatType = FloatType;
  30003. exports.Fog = Fog;
  30004. exports.FogExp2 = FogExp2;
  30005. exports.FramebufferTexture = FramebufferTexture;
  30006. exports.FrontSide = FrontSide;
  30007. exports.Frustum = Frustum;
  30008. exports.GLBufferAttribute = GLBufferAttribute;
  30009. exports.GLSL1 = GLSL1;
  30010. exports.GLSL3 = GLSL3;
  30011. exports.GreaterDepth = GreaterDepth;
  30012. exports.GreaterEqualDepth = GreaterEqualDepth;
  30013. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  30014. exports.GreaterStencilFunc = GreaterStencilFunc;
  30015. exports.GridHelper = GridHelper;
  30016. exports.Group = Group;
  30017. exports.HalfFloatType = HalfFloatType;
  30018. exports.HemisphereLight = HemisphereLight;
  30019. exports.HemisphereLightHelper = HemisphereLightHelper;
  30020. exports.HemisphereLightProbe = HemisphereLightProbe;
  30021. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  30022. exports.IcosahedronGeometry = IcosahedronGeometry;
  30023. exports.ImageBitmapLoader = ImageBitmapLoader;
  30024. exports.ImageLoader = ImageLoader;
  30025. exports.ImageUtils = ImageUtils;
  30026. exports.ImmediateRenderObject = ImmediateRenderObject;
  30027. exports.IncrementStencilOp = IncrementStencilOp;
  30028. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  30029. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  30030. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30031. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30032. exports.InstancedMesh = InstancedMesh;
  30033. exports.Int16BufferAttribute = Int16BufferAttribute;
  30034. exports.Int32BufferAttribute = Int32BufferAttribute;
  30035. exports.Int8BufferAttribute = Int8BufferAttribute;
  30036. exports.IntType = IntType;
  30037. exports.InterleavedBuffer = InterleavedBuffer;
  30038. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30039. exports.Interpolant = Interpolant;
  30040. exports.InterpolateDiscrete = InterpolateDiscrete;
  30041. exports.InterpolateLinear = InterpolateLinear;
  30042. exports.InterpolateSmooth = InterpolateSmooth;
  30043. exports.InvertStencilOp = InvertStencilOp;
  30044. exports.KeepStencilOp = KeepStencilOp;
  30045. exports.KeyframeTrack = KeyframeTrack;
  30046. exports.LOD = LOD;
  30047. exports.LatheBufferGeometry = LatheBufferGeometry;
  30048. exports.LatheGeometry = LatheGeometry;
  30049. exports.Layers = Layers;
  30050. exports.LessDepth = LessDepth;
  30051. exports.LessEqualDepth = LessEqualDepth;
  30052. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  30053. exports.LessStencilFunc = LessStencilFunc;
  30054. exports.Light = Light;
  30055. exports.LightProbe = LightProbe;
  30056. exports.Line = Line;
  30057. exports.Line3 = Line3;
  30058. exports.LineBasicMaterial = LineBasicMaterial;
  30059. exports.LineCurve = LineCurve;
  30060. exports.LineCurve3 = LineCurve3;
  30061. exports.LineDashedMaterial = LineDashedMaterial;
  30062. exports.LineLoop = LineLoop;
  30063. exports.LineSegments = LineSegments;
  30064. exports.LinearEncoding = LinearEncoding;
  30065. exports.LinearFilter = LinearFilter;
  30066. exports.LinearInterpolant = LinearInterpolant;
  30067. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30068. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30069. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  30070. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  30071. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  30072. exports.LinearToneMapping = LinearToneMapping;
  30073. exports.Loader = Loader;
  30074. exports.LoaderUtils = LoaderUtils;
  30075. exports.LoadingManager = LoadingManager;
  30076. exports.LoopOnce = LoopOnce;
  30077. exports.LoopPingPong = LoopPingPong;
  30078. exports.LoopRepeat = LoopRepeat;
  30079. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30080. exports.LuminanceFormat = LuminanceFormat;
  30081. exports.MOUSE = MOUSE;
  30082. exports.Material = Material;
  30083. exports.MaterialLoader = MaterialLoader;
  30084. exports.MathUtils = MathUtils;
  30085. exports.Matrix3 = Matrix3;
  30086. exports.Matrix4 = Matrix4;
  30087. exports.MaxEquation = MaxEquation;
  30088. exports.Mesh = Mesh;
  30089. exports.MeshBasicMaterial = MeshBasicMaterial;
  30090. exports.MeshDepthMaterial = MeshDepthMaterial;
  30091. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  30092. exports.MeshLambertMaterial = MeshLambertMaterial;
  30093. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  30094. exports.MeshNormalMaterial = MeshNormalMaterial;
  30095. exports.MeshPhongMaterial = MeshPhongMaterial;
  30096. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30097. exports.MeshStandardMaterial = MeshStandardMaterial;
  30098. exports.MeshToonMaterial = MeshToonMaterial;
  30099. exports.MinEquation = MinEquation;
  30100. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30101. exports.MixOperation = MixOperation;
  30102. exports.MultiplyBlending = MultiplyBlending;
  30103. exports.MultiplyOperation = MultiplyOperation;
  30104. exports.NearestFilter = NearestFilter;
  30105. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30106. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30107. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  30108. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  30109. exports.NeverDepth = NeverDepth;
  30110. exports.NeverStencilFunc = NeverStencilFunc;
  30111. exports.NoBlending = NoBlending;
  30112. exports.NoColorSpace = NoColorSpace;
  30113. exports.NoToneMapping = NoToneMapping;
  30114. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  30115. exports.NormalBlending = NormalBlending;
  30116. exports.NotEqualDepth = NotEqualDepth;
  30117. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  30118. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30119. exports.Object3D = Object3D;
  30120. exports.ObjectLoader = ObjectLoader;
  30121. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  30122. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30123. exports.OctahedronGeometry = OctahedronGeometry;
  30124. exports.OneFactor = OneFactor;
  30125. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30126. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30127. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30128. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30129. exports.OrthographicCamera = OrthographicCamera;
  30130. exports.PCFShadowMap = PCFShadowMap;
  30131. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30132. exports.PMREMGenerator = PMREMGenerator;
  30133. exports.Path = Path;
  30134. exports.PerspectiveCamera = PerspectiveCamera;
  30135. exports.Plane = Plane;
  30136. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30137. exports.PlaneGeometry = PlaneGeometry;
  30138. exports.PlaneHelper = PlaneHelper;
  30139. exports.PointLight = PointLight;
  30140. exports.PointLightHelper = PointLightHelper;
  30141. exports.Points = Points;
  30142. exports.PointsMaterial = PointsMaterial;
  30143. exports.PolarGridHelper = PolarGridHelper;
  30144. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30145. exports.PolyhedronGeometry = PolyhedronGeometry;
  30146. exports.PositionalAudio = PositionalAudio;
  30147. exports.PropertyBinding = PropertyBinding;
  30148. exports.PropertyMixer = PropertyMixer;
  30149. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30150. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30151. exports.Quaternion = Quaternion;
  30152. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30153. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30154. exports.REVISION = REVISION;
  30155. exports.RGBADepthPacking = RGBADepthPacking;
  30156. exports.RGBAFormat = RGBAFormat;
  30157. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  30158. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  30159. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  30160. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  30161. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  30162. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  30163. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  30164. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  30165. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  30166. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  30167. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  30168. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  30169. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  30170. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  30171. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  30172. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  30173. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  30174. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30175. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30176. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30177. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30178. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30179. exports.RGBFormat = RGBFormat;
  30180. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30181. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  30182. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30183. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30184. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30185. exports.RGFormat = RGFormat;
  30186. exports.RGIntegerFormat = RGIntegerFormat;
  30187. exports.RawShaderMaterial = RawShaderMaterial;
  30188. exports.Ray = Ray;
  30189. exports.Raycaster = Raycaster;
  30190. exports.RectAreaLight = RectAreaLight;
  30191. exports.RedFormat = RedFormat;
  30192. exports.RedIntegerFormat = RedIntegerFormat;
  30193. exports.ReinhardToneMapping = ReinhardToneMapping;
  30194. exports.RepeatWrapping = RepeatWrapping;
  30195. exports.ReplaceStencilOp = ReplaceStencilOp;
  30196. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30197. exports.RingBufferGeometry = RingBufferGeometry;
  30198. exports.RingGeometry = RingGeometry;
  30199. exports.SRGBColorSpace = SRGBColorSpace;
  30200. exports.Scene = Scene;
  30201. exports.ShaderChunk = ShaderChunk;
  30202. exports.ShaderLib = ShaderLib;
  30203. exports.ShaderMaterial = ShaderMaterial;
  30204. exports.ShadowMaterial = ShadowMaterial;
  30205. exports.Shape = Shape;
  30206. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30207. exports.ShapeGeometry = ShapeGeometry;
  30208. exports.ShapePath = ShapePath;
  30209. exports.ShapeUtils = ShapeUtils;
  30210. exports.ShortType = ShortType;
  30211. exports.Skeleton = Skeleton;
  30212. exports.SkeletonHelper = SkeletonHelper;
  30213. exports.SkinnedMesh = SkinnedMesh;
  30214. exports.Source = Source;
  30215. exports.Sphere = Sphere;
  30216. exports.SphereBufferGeometry = SphereBufferGeometry;
  30217. exports.SphereGeometry = SphereGeometry;
  30218. exports.Spherical = Spherical;
  30219. exports.SphericalHarmonics3 = SphericalHarmonics3;
  30220. exports.SplineCurve = SplineCurve;
  30221. exports.SpotLight = SpotLight;
  30222. exports.SpotLightHelper = SpotLightHelper;
  30223. exports.Sprite = Sprite;
  30224. exports.SpriteMaterial = SpriteMaterial;
  30225. exports.SrcAlphaFactor = SrcAlphaFactor;
  30226. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30227. exports.SrcColorFactor = SrcColorFactor;
  30228. exports.StaticCopyUsage = StaticCopyUsage;
  30229. exports.StaticDrawUsage = StaticDrawUsage;
  30230. exports.StaticReadUsage = StaticReadUsage;
  30231. exports.StereoCamera = StereoCamera;
  30232. exports.StreamCopyUsage = StreamCopyUsage;
  30233. exports.StreamDrawUsage = StreamDrawUsage;
  30234. exports.StreamReadUsage = StreamReadUsage;
  30235. exports.StringKeyframeTrack = StringKeyframeTrack;
  30236. exports.SubtractEquation = SubtractEquation;
  30237. exports.SubtractiveBlending = SubtractiveBlending;
  30238. exports.TOUCH = TOUCH;
  30239. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  30240. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30241. exports.TetrahedronGeometry = TetrahedronGeometry;
  30242. exports.Texture = Texture;
  30243. exports.TextureLoader = TextureLoader;
  30244. exports.TorusBufferGeometry = TorusBufferGeometry;
  30245. exports.TorusGeometry = TorusGeometry;
  30246. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30247. exports.TorusKnotGeometry = TorusKnotGeometry;
  30248. exports.Triangle = Triangle;
  30249. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30250. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30251. exports.TrianglesDrawMode = TrianglesDrawMode;
  30252. exports.TubeBufferGeometry = TubeBufferGeometry;
  30253. exports.TubeGeometry = TubeGeometry;
  30254. exports.UVMapping = UVMapping;
  30255. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30256. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30257. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30258. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30259. exports.Uniform = Uniform;
  30260. exports.UniformsGroup = UniformsGroup;
  30261. exports.UniformsLib = UniformsLib;
  30262. exports.UniformsUtils = UniformsUtils;
  30263. exports.UnsignedByteType = UnsignedByteType;
  30264. exports.UnsignedInt248Type = UnsignedInt248Type;
  30265. exports.UnsignedIntType = UnsignedIntType;
  30266. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30267. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30268. exports.UnsignedShortType = UnsignedShortType;
  30269. exports.VSMShadowMap = VSMShadowMap;
  30270. exports.Vector2 = Vector2;
  30271. exports.Vector3 = Vector3;
  30272. exports.Vector4 = Vector4;
  30273. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30274. exports.VideoTexture = VideoTexture;
  30275. exports.WebGL1Renderer = WebGL1Renderer;
  30276. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  30277. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  30278. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  30279. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  30280. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  30281. exports.WebGLRenderTarget = WebGLRenderTarget;
  30282. exports.WebGLRenderer = WebGLRenderer;
  30283. exports.WebGLUtils = WebGLUtils;
  30284. exports.WireframeGeometry = WireframeGeometry;
  30285. exports.WrapAroundEnding = WrapAroundEnding;
  30286. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30287. exports.ZeroFactor = ZeroFactor;
  30288. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30289. exports.ZeroStencilOp = ZeroStencilOp;
  30290. exports._SRGBAFormat = _SRGBAFormat;
  30291. exports.sRGBEncoding = sRGBEncoding;